463 lines
20 KiB
Python
463 lines
20 KiB
Python
"""
|
||
backend/app/services/shipping_notice/audit_service.py
|
||
|
||
用途:货代领域统一审计事件的唯一写入入口;要求操作上下文与前后快照(可为空),
|
||
写入 Workflow 软引用与哈希链字段;XFA 敏感变更可同事务挂接加密完整快照引用。
|
||
依赖:ShippingAuditEvent、progress_audit_contract、audit_snapshot_service(在 append 内导入以避免环)、
|
||
SQLAlchemy 会话。
|
||
逻辑:Run、Task、Workflow Item、库存、门禁 Attempt、Chatflow 与 XFA Profile 服务调用本模块;
|
||
写入前投影白名单快照 → 可选创建 XFA 加密完整快照 → 计算 diff → 解析同聚合
|
||
previous_event_hash → 计算 event_hash;本服务不提交事务,由调用方保证业务与审计原子性;
|
||
审计/快照写入失败时业务不得提交。支持 operation_id、白名单前后快照、证据引用、
|
||
Workflow 软引用、属主;actor_type 含 worker;货代统一账本永久保留(expires=None)。
|
||
"""
|
||
|
||
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,
|
||
is_permanent_audit_event_type,
|
||
)
|
||
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,
|
||
actor_display: 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,
|
||
workflow_id: str | None = None,
|
||
workflow_item_id: str | None = None,
|
||
workflow_item_version_id: str | None = None,
|
||
version_no: int | 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,
|
||
sensitivity_level: str | None = None,
|
||
retention_expires_at: datetime | None = None,
|
||
persist_snapshots: bool = True,
|
||
full_before: dict[str, Any] | None = None,
|
||
full_after: dict[str, Any] | None = None,
|
||
full_payload: dict[str, Any] | None = None,
|
||
full_payload_purpose: str = 'full',
|
||
) -> ShippingAuditEvent:
|
||
"""
|
||
追加一条货代审计事实(唯一写入口)。
|
||
|
||
Args:
|
||
event_type: 稳定业务事件名,例如 ``workflow_item_created``;禁止传入用户自由文本。
|
||
aggregate_type/aggregate_id: 业务聚合类型与稳定编号,不使用可删除记录的外键。
|
||
operation_id: 同一次用户/系统操作的关联键,与 request_id 共同贯通事件链。
|
||
workflow_id: Workflow.workflow_no 软引用。
|
||
workflow_item_id: WorkflowItem.item_no 软引用。
|
||
workflow_item_version_id: ItemVersion 主键或稳定编号的字符串软引用。
|
||
version_no: 当前版本号(可选)。
|
||
actor_display: 操作者展示名(可选)。
|
||
sensitivity_level: ``normal`` / ``sensitive`` 等分级标签。
|
||
owner_user_id: 业务属主,与 actor_id(实际操作者)区分,支撑代操作审计。
|
||
client_ip/user_agent: 原始客户端上下文,仅哈希后入库;也可直接传 *_hash。
|
||
before/after: 可复现的受控状态投影;持久化白名单快照及其哈希,并计算 diff_json。
|
||
evidence_refs/artifact_refs: FileAsset ID、SHA-256、版本与证据坐标,禁止 URL/正文。
|
||
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
|
||
persist_snapshots: False 时只写哈希(兼容历史调用方仅传 before/after 哈希语义)。
|
||
full_before/full_after/full_payload: XFA 完整敏感载荷;加密写入 shipping_xfa_audit_snapshots,
|
||
引用挂到 context_refs.snapshot_*_ref;缺主密钥时失败关闭。
|
||
full_payload_purpose: full_payload 的用途标签(默认 full)。
|
||
|
||
Returns:
|
||
尚未提交的审计事件,由调用方与业务写入在同一事务提交。
|
||
|
||
Raises:
|
||
ValidationError: actor 类型、元数据或快照包含正文、凭据等敏感字段。
|
||
ServiceUnavailableError: 需要加密快照但主密钥缺失。
|
||
"""
|
||
# 延迟导入:audit_snapshot_service.sanitize_snapshot 会回引 project_audit_snapshot,避免模块环。
|
||
from app.services.shipping_notice.audit_snapshot_service import (
|
||
build_event_hash_payload,
|
||
compute_event_hash,
|
||
compute_snapshot_diff,
|
||
create_xfa_audit_snapshot,
|
||
resolve_previous_event_hash,
|
||
)
|
||
|
||
# worker:门禁 Attempt / Job 租约路径的执行主体(Phase 4+)。
|
||
allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'}
|
||
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')
|
||
|
||
# [STEP 1] 投影白名单快照并计算 diff。
|
||
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
|
||
diff_json = compute_snapshot_diff(before_snapshot, after_snapshot)
|
||
|
||
# [STEP 1b] XFA 完整载荷 → 加密不可变快照;失败则阻断业务提交。
|
||
resolved_context = dict(context_refs or {}) if context_refs is not None else {}
|
||
snapshot_refs: list[dict[str, Any]] = []
|
||
if full_before is not None:
|
||
before_row = create_xfa_audit_snapshot(
|
||
payload=full_before,
|
||
object_type=str(aggregate_type)[:64],
|
||
object_id=str(aggregate_id)[:128],
|
||
purpose='before',
|
||
actor_id=actor_id,
|
||
request_id=request_id,
|
||
operation_id=operation_id,
|
||
)
|
||
resolved_context['snapshot_before_ref'] = before_row.snapshot_ref
|
||
snapshot_refs.append({
|
||
'kind': 'xfa_audit_snapshot',
|
||
'purpose': 'before',
|
||
'snapshot_ref': before_row.snapshot_ref,
|
||
'plaintext_sha256': before_row.plaintext_sha256,
|
||
})
|
||
if full_after is not None:
|
||
after_row = create_xfa_audit_snapshot(
|
||
payload=full_after,
|
||
object_type=str(aggregate_type)[:64],
|
||
object_id=str(aggregate_id)[:128],
|
||
purpose='after',
|
||
actor_id=actor_id,
|
||
request_id=request_id,
|
||
operation_id=operation_id,
|
||
)
|
||
resolved_context['snapshot_after_ref'] = after_row.snapshot_ref
|
||
snapshot_refs.append({
|
||
'kind': 'xfa_audit_snapshot',
|
||
'purpose': 'after',
|
||
'snapshot_ref': after_row.snapshot_ref,
|
||
'plaintext_sha256': after_row.plaintext_sha256,
|
||
})
|
||
if full_payload is not None:
|
||
full_row = create_xfa_audit_snapshot(
|
||
payload=full_payload,
|
||
object_type=str(aggregate_type)[:64],
|
||
object_id=str(aggregate_id)[:128],
|
||
purpose=str(full_payload_purpose or 'full'),
|
||
actor_id=actor_id,
|
||
request_id=request_id,
|
||
operation_id=operation_id,
|
||
)
|
||
resolved_context['snapshot_full_ref'] = full_row.snapshot_ref
|
||
snapshot_refs.append({
|
||
'kind': 'xfa_audit_snapshot',
|
||
'purpose': full_row.purpose,
|
||
'snapshot_ref': full_row.snapshot_ref,
|
||
'plaintext_sha256': full_row.plaintext_sha256,
|
||
})
|
||
if resolved_context:
|
||
_sanitize_metadata(resolved_context)
|
||
merged_evidence = list(evidence_refs or [])
|
||
if snapshot_refs:
|
||
merged_evidence.extend(snapshot_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)
|
||
|
||
resolved_workflow_id = str(workflow_id)[:64] if workflow_id else None
|
||
resolved_workflow_item_id = str(workflow_item_id)[:64] if workflow_item_id else None
|
||
resolved_workflow_item_version_id = (
|
||
str(workflow_item_version_id)[:64] if workflow_item_version_id else None
|
||
)
|
||
resolved_version_no = int(version_no) if version_no is not None else None
|
||
resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None
|
||
resolved_operation_id = str(operation_id)[:64] if operation_id else None
|
||
resolved_request_id = str(request_id)[:64] if request_id else None
|
||
resolved_run_no = str(run_no)[:64] if run_no else None
|
||
resolved_task_no = str(task_no)[:64] if task_no else None
|
||
resolved_document_id = str(document_id)[:64] if document_id is not None else None
|
||
resolved_review_case_no = str(review_case_no)[:64] if review_case_no else None
|
||
resolved_action = str(action)[:64] if action else None
|
||
resolved_reason_code = str(reason_code)[:128] if reason_code else None
|
||
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
|
||
|
||
# #region debug-point A/B/C/D:submission-audit-flush
|
||
try:
|
||
import os
|
||
import urllib.request
|
||
debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'order-submission-deadlock.env'
|
||
debug_values = {
|
||
line.split('=', 1)[0]: line.split('=', 1)[1].strip()
|
||
for line in debug_env.read_text(encoding='utf-8').splitlines()
|
||
if '=' in line
|
||
}
|
||
urllib.request.urlopen(urllib.request.Request(
|
||
debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'),
|
||
data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'order-submission-deadlock'), 'runId': 'pre-fix', 'hypothesisId': 'A/B/C/D', 'location': 'audit_service.py:349', 'msg': '[DEBUG] audit flush lock state', 'data': {'pid': os.getpid(), 'aggregate_type': str(aggregate_type)[:64], 'aggregate_id': str(aggregate_id)[:128], 'event_type': str(event_type)[:64], 'in_transaction': db.session.in_transaction()}}).encode(),
|
||
headers={'Content-Type': 'application/json'},
|
||
), timeout=1).read()
|
||
except Exception:
|
||
pass
|
||
# #endregion
|
||
|
||
# [STEP 2] flush 同事务先前事件,保证哈希链前驱可查。
|
||
db.session.flush()
|
||
previous_event_hash = resolve_previous_event_hash(
|
||
aggregate_type=str(aggregate_type)[:64],
|
||
aggregate_id=str(aggregate_id)[:128],
|
||
)
|
||
hash_payload = build_event_hash_payload(
|
||
event_type=str(event_type)[:64],
|
||
aggregate_type=str(aggregate_type)[:64],
|
||
aggregate_id=str(aggregate_id)[:128],
|
||
action=resolved_action,
|
||
result=result,
|
||
reason_code=resolved_reason_code,
|
||
workflow_id=resolved_workflow_id,
|
||
workflow_item_id=resolved_workflow_item_id,
|
||
workflow_item_version_id=resolved_workflow_item_version_id,
|
||
version_no=resolved_version_no,
|
||
run_no=resolved_run_no,
|
||
document_id=resolved_document_id,
|
||
review_case_no=resolved_review_case_no,
|
||
task_no=resolved_task_no,
|
||
operation_id=resolved_operation_id,
|
||
request_id=resolved_request_id,
|
||
actor_type=actor_type,
|
||
actor_id=resolved_actor_id,
|
||
before_snapshot=before_snapshot if persist_snapshots else None,
|
||
after_snapshot=after_snapshot if persist_snapshots else None,
|
||
diff_json=diff_json,
|
||
previous_event_hash=previous_event_hash,
|
||
sensitivity_level=resolved_sensitivity,
|
||
)
|
||
event_hash = compute_event_hash(hash_payload)
|
||
|
||
# [STEP 3] 货代统一审计账本:全业务节点永久保留,忽略调用方传入的到期时间。
|
||
# default_retention_expires_at 仅保留给遗留清理 Job / 运维工具兼容,新写入一律为 None。
|
||
resolved_retention: datetime | None = None
|
||
if not is_permanent_audit_event_type(str(event_type)) and retention_expires_at is not None:
|
||
resolved_retention = retention_expires_at
|
||
elif not is_permanent_audit_event_type(str(event_type)):
|
||
resolved_retention = default_retention_expires_at()
|
||
event = ShippingAuditEvent(
|
||
event_type=str(event_type)[:64],
|
||
aggregate_type=str(aggregate_type)[:64],
|
||
aggregate_id=str(aggregate_id)[:128],
|
||
run_no=resolved_run_no,
|
||
task_no=resolved_task_no,
|
||
intake_no=str(intake_no)[:64] if intake_no else None,
|
||
actor_type=actor_type,
|
||
actor_id=resolved_actor_id,
|
||
actor_role=str(actor_role)[:64] if actor_role else None,
|
||
actor_display=str(actor_display)[:128] if actor_display else None,
|
||
request_id=resolved_request_id,
|
||
operation_id=resolved_operation_id,
|
||
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=resolved_document_id,
|
||
review_case_no=resolved_review_case_no,
|
||
workflow_id=resolved_workflow_id,
|
||
workflow_item_id=resolved_workflow_item_id,
|
||
workflow_item_version_id=resolved_workflow_item_version_id,
|
||
version_no=resolved_version_no,
|
||
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=resolved_action,
|
||
reason_code=resolved_reason_code,
|
||
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,
|
||
diff_json=diff_json,
|
||
previous_event_hash=previous_event_hash,
|
||
event_hash=event_hash,
|
||
sensitivity_level=resolved_sensitivity,
|
||
evidence_refs_json=_sanitize_refs(merged_evidence or None, field_name='evidence_refs'),
|
||
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
|
||
context_refs_json=resolved_context or None,
|
||
metadata_json=_sanitize_metadata(metadata),
|
||
retention_expires_at=resolved_retention,
|
||
)
|
||
db.session.add(event)
|
||
db.session.flush()
|
||
return event
|
||
|
||
|
||
# 供测试与 OpenAPI 契约引用的冻结黑名单导出。
|
||
FORBIDDEN_AUDIT_METADATA_KEYS = AUDIT_FORBIDDEN_KEYS
|