""" backend/app/services/shipping_notice/fulfillment_audit.py 用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。 依赖:audit_service.append_shipping_audit_event、Flask g.request_id、core.http_context、AppError、db.session。 逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用; 默认 strict=True;审计写入包在 SAVEPOINT 内,失败不污染外层业务事务; strict=False 时仅记日志(门禁路径用,禁止审计打断匹配等业务结果); 自动附带 request_id 与客户端 IP/UA(仅哈希入库);透传 Workflow 软引用字段。 """ from __future__ import annotations import logging from typing import Any from app import db from app.core.errors import ServiceUnavailableError from app.services.shipping_notice.audit_service import append_shipping_audit_event _LOGGER = logging.getLogger(__name__) def _request_id() -> str | None: """尽量读取当前请求 ID;Worker 场景允许为空。""" try: from flask import g return str(getattr(g, 'request_id', '') or '') or None except RuntimeError: return None def _client_request_context() -> tuple[str | None, str | None]: """ 读取当前请求客户端 IP 与 User-Agent(仅供哈希入库)。 核心逻辑:优先 X-Forwarded-For 首段;无请求上下文时返回 (None, None)。 """ try: from app.core.http_context import header, remote_addr forwarded = header('X-Forwarded-For').split(',')[0].strip() ip = forwarded or remote_addr() or None ua = header('User-Agent').strip() or None return ip, ua except RuntimeError: return None, None def resolve_request_audit_context() -> dict[str, str | None]: """ 解析当前 HTTP 请求的审计关联上下文。 核心逻辑:合并 request_id 与原始 IP/UA(供 append 侧哈希);无 Flask 请求时全空。 Returns: 含 request_id / client_ip / user_agent 的字典;值均可为 None。 """ client_ip, user_agent = _client_request_context() return { 'request_id': _request_id(), 'client_ip': client_ip, 'user_agent': user_agent, } def record_fulfillment_audit( *, event_type: str, aggregate_type: str, aggregate_id: str, action: str, actor_type: str = 'user', actor_id: str | int | None = None, run_no: str | None = None, task_no: str | None = None, document_id: str | int | None = None, review_case_no: str | None = None, conversation_id: 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, reason_code: str | None = None, reason: str | None = None, result: str = 'success', error_code: str | None = None, before: dict[str, Any] | None = None, after: dict[str, Any] | None = None, metadata: dict[str, Any] | None = None, source: str = 'api', strict: bool = True, sensitivity_level: str | None = None, ) -> None: """ 追加履约审计。 核心逻辑:审计写入包在 SAVEPOINT 内,与外层业务状态隔离;strict=True 时失败抛错, 但已回滚审计子事务,不把会话留在失败态;strict=False 时仅记日志,业务继续。 自动附带 request_id 与客户端 IP/UA 哈希;透传 Workflow 软引用。 Args: event_type/action: 稳定事件与动作码。 workflow_id/workflow_item_id/workflow_item_version_id/version_no: Workflow 软引用。 before/after: 必须已是白名单可投影的状态摘要。 error_code: 拒绝/失败时的稳定业务错误码。 sensitivity_level: 可选敏感分级(如 sensitive),透传审计表。 strict: True 时审计失败阻断调用方;False 时仅记日志(门禁等业务关键路径)。 """ request_id = _request_id() client_ip, user_agent = _client_request_context() try: # [STEP] SAVEPOINT:审计 INSERT 失败不得污染外层业务事务(否则匹配等结果会整单回滚)。 with db.session.begin_nested(): append_shipping_audit_event( event_type=event_type, aggregate_type=aggregate_type, aggregate_id=str(aggregate_id), action=action, actor_type=actor_type, actor_id=actor_id, request_id=request_id, operation_id=request_id, run_no=run_no, task_no=task_no, document_id=document_id, review_case_no=review_case_no, conversation_id=conversation_id, workflow_id=workflow_id, workflow_item_id=workflow_item_id, workflow_item_version_id=workflow_item_version_id, version_no=version_no, owner_user_id=owner_user_id, client_ip=client_ip, user_agent=user_agent, reason_code=reason_code, reason=reason, result=result, error_code=error_code, before=before, after=after, metadata=metadata or {}, source=source, sensitivity_level=sensitivity_level, ) except Exception as exc: _LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id) if strict: raise ServiceUnavailableError( f'Shipping audit persistence failed: {exc}', code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED', details={ 'event_type': event_type, 'aggregate_id': str(aggregate_id), 'cause': str(exc)[:500], }, ) from exc def emit_stp_auto_create_blocked_manual_audit( *, case: Any | None, job_id: int, error_code: str, next_action: str, details: dict[str, Any] | None = None, ) -> None: """ 记录 STP 自动建单业务阻断的人工处理审计事件。 核心逻辑:使用订单复核 Case 作为可选聚合,Job 作为稳定元数据引用;Worker 无请求上下文时仍可写入。 Args: case: 可选 ShippingOrderReviewCase,优先提供 case_no;不得传入正文或凭据。 job_id: STP Job 主键。 error_code: 稳定业务阻断错误码。 next_action: 后续人工处理动作编码。 details: 脱敏诊断事实,仅允许审计元数据白名单字段。 Returns: None。审计失败由 record_fulfillment_audit 按 strict 契约抛出。 """ case_no = str(getattr(case, 'case_no', '') or '').strip() or None metadata = { 'job_id': int(job_id), 'next_action': str(next_action or '').strip() or None, **dict(details or {}), } record_fulfillment_audit( event_type='stp_auto_create_blocked_manual', aggregate_type='order_review_case' if case_no else 'shipping_job', aggregate_id=case_no or str(job_id), action='stp_auto_create_blocked_manual', actor_type='worker', task_no=case_no, review_case_no=case_no, reason_code=str(error_code or '').strip() or None, error_code=str(error_code or '').strip() or None, result='rejected', metadata=metadata, source='worker', ) def record_access_audit( *, action: str, aggregate_type: str, aggregate_id: str, actor_id: str | int | None, actor_type: str = 'user', run_no: str | None = None, task_no: str | None = None, document_id: str | int | None = None, review_case_no: str | None = None, conversation_id: 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, reason_code: str | None = None, metadata: dict[str, Any] | None = None, strict: bool = True, ) -> bool: """ 记录敏感读取/导出访问审计(无业务正文);每次调用均落库。 核心逻辑:自行提交;失败时回滚并按 strict 抛错,禁止静默丢审计;附带客户端哈希; 可选 reason_code 供审计中心按可解释性码筛选(如 Excel 下载)。 Args: reason_code: 可选稳定原因/动作码(访问类事件通常为业务动作标识)。 Returns: True 表示本次写入了新事件。 """ from app import db request_id = _request_id() client_ip, user_agent = _client_request_context() resolved_reason = str(reason_code or '').strip() or None meta = dict(metadata or {'access': True}) if resolved_reason: meta.setdefault('reason_code', resolved_reason) try: append_shipping_audit_event( event_type='shipping_resource_accessed', aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128], action=str(action)[:64], actor_type=actor_type, actor_id=actor_id, request_id=request_id, operation_id=request_id, run_no=run_no, task_no=task_no, document_id=document_id, review_case_no=review_case_no, conversation_id=conversation_id, workflow_id=workflow_id, workflow_item_id=workflow_item_id, workflow_item_version_id=workflow_item_version_id, version_no=version_no, owner_user_id=owner_user_id, client_ip=client_ip, user_agent=user_agent, reason_code=resolved_reason, result='success', metadata=meta, source='api', persist_snapshots=False, sensitivity_level='sensitive', ) db.session.commit() return True except Exception as exc: db.session.rollback() _LOGGER.exception('access audit append failed action=%s aggregate_id=%s', action, aggregate_id) if strict: raise ServiceUnavailableError( 'Shipping access audit persistence failed', code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED', details={'action': action, 'aggregate_id': str(aggregate_id)}, ) from exc return False