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

203 lines
6.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/fulfillment_audit.py
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / 工作项写路径调用;
默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕;
自动附带 request_id 与客户端 IP/UA(仅哈希入库)。
"""
from __future__ import annotations
import logging
from typing import Any
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 flask import request
forwarded = str(request.headers.get('X-Forwarded-For') or '').split(',')[0].strip()
ip = forwarded or str(request.remote_addr or '').strip() or None
ua = str(request.headers.get('User-Agent') or '').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,
session_item_id: str | None = None,
owner_user_id: str | int | None = None,
reason_code: str | None = None,
reason: str | None = None,
result: str = 'success',
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
source: str = 'api',
strict: bool = True,
) -> None:
"""
追加履约审计。
核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存;
自动附带 request_id 与客户端 IP/UA 哈希。
Args:
event_type/action: 稳定事件与动作码。
before/after: 必须已是白名单可投影的状态摘要。
strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。
"""
request_id = _request_id()
client_ip, user_agent = _client_request_context()
try:
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,
session_item_id=session_item_id,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
reason_code=reason_code,
reason=reason,
result=result,
before=before,
after=after,
metadata=metadata or {},
source=source,
)
except Exception as exc:
_LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id)
if strict:
raise ServiceUnavailableError(
'Shipping audit persistence failed',
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
details={'event_type': event_type, 'aggregate_id': str(aggregate_id)},
) from exc
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,
session_item_id: str | None = None,
owner_user_id: str | int | None = None,
metadata: dict[str, Any] | None = None,
strict: bool = True,
) -> bool:
"""
记录敏感读取/导出访问审计(无业务正文);每次调用均落库。
核心逻辑:自行提交;失败时回滚并按 strict 抛错,禁止静默丢审计;附带客户端哈希。
Returns:
True 表示本次写入了新事件。
"""
from app import db
request_id = _request_id()
client_ip, user_agent = _client_request_context()
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,
session_item_id=session_item_id,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
result='success',
metadata=metadata or {'access': True},
source='api',
persist_snapshots=False,
)
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