""" backend/tests/test_shipping_audit_event.py 用途:验证货代统一审计事件的脱敏、白名单快照和 append-only 契约。 依赖:ShippingAuditEvent、audit_service、progress_audit_contract、SQLAlchemy 内存会话。 逻辑:审计写入只保存白名单快照/哈希和受控元数据;更新、删除或敏感内容均必须被拒绝。 """ from __future__ import annotations import ast from pathlib import Path import pytest from app import db from app.core.errors import ValidationError from app.models import ShippingAuditEvent from app.services.shipping_notice.audit_service import ( append_shipping_audit_event, hash_client_context_value, project_audit_snapshot, ) from app.services.shipping_notice.progress_audit_contract import ( AUDIT_FORBIDDEN_KEYS, AUDIT_RETENTION_DAYS, I18N_KEY_INVENTORY, ) def test_append_shipping_audit_event_hashes_state_and_rejects_sensitive_metadata(app): """状态审计保存白名单快照与哈希,正文或凭据类元数据必须在入库前拒绝。""" with app.app_context(): event = append_shipping_audit_event( event_type='order_extraction_run_status_changed', aggregate_type='order_extraction_run', aggregate_id='SNER-1', run_no='SNER-1', operation_id='op-stage0-1', before={'status': 'queued'}, after={'status': 'processing'}, metadata={'target_status': 'processing'}, ) db.session.commit() # 关键断言:可追溯性来自哈希与白名单快照,而不是把订单、邮件正文写进审计表。 assert event.before_hash and event.after_hash assert event.before_snapshot_json == {'status': 'queued'} assert event.after_snapshot_json == {'status': 'processing'} assert event.operation_id == 'op-stage0-1' assert event.metadata_json == {'target_status': 'processing'} assert event.retention_expires_at is None with pytest.raises(ValidationError) as caught: append_shipping_audit_event( event_type='invalid', aggregate_type='run', aggregate_id='1', metadata={'email_body': 'secret'}, ) assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN' db.session.rollback() @pytest.mark.parametrize('forbidden_key', sorted(AUDIT_FORBIDDEN_KEYS)) def test_audit_forbidden_keys_blacklist_rejects_metadata_and_snapshot(app, forbidden_key: str): """阶段 0 冻结的敏感键黑名单必须对元数据与快照同时生效。""" with app.app_context(): with pytest.raises(ValidationError) as meta_err: append_shipping_audit_event( event_type='probe', aggregate_type='run', aggregate_id='SNER-BL', metadata={forbidden_key: 'x'}, ) assert meta_err.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN' with pytest.raises(ValidationError) as snap_err: project_audit_snapshot({'status': 'queued', forbidden_key: 'x'}) assert snap_err.value.code == 'SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN' db.session.rollback() def test_audit_snapshot_whitelist_strips_unknown_business_keys(app): """未授权业务键不得进入快照;敏感键仍被拒绝。""" with app.app_context(): projected = project_audit_snapshot({ 'status': 'extracting', 'progress_version': 3, 'orders': [{'po': '45001'}], }) assert projected == {'status': 'extracting', 'progress_version': 3} def test_audit_evidence_refs_reject_url_payload(app): """证据引用禁止携带对象存储 URL 等敏感键。""" with app.app_context(): with pytest.raises(ValidationError) as caught: append_shipping_audit_event( event_type='evidence_viewed', aggregate_type='document', aggregate_id='12', evidence_refs=[{'file_asset_id': 9, 'url': 'https://minio.example/x'}], ) assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN' db.session.rollback() def test_shipping_audit_event_rejects_orm_update_and_delete(app): """已经提交的统一审计事件必须拒绝更新和删除,避免业务清理破坏追溯事实。""" with app.app_context(): event = append_shipping_audit_event(event_type='created', aggregate_type='run', aggregate_id='SNER-2') db.session.commit() event.reason_code = 'changed' with pytest.raises(ValidationError, match='append-only'): db.session.commit() db.session.rollback() persisted = db.session.get(ShippingAuditEvent, event.id) db.session.delete(persisted) with pytest.raises(ValidationError, match='append-only'): db.session.commit() db.session.rollback() def test_append_shipping_audit_event_hashes_client_context_and_workflow_refs(app): """Workflow 审计必须记录属主/软引用与哈希链,且 IP/UA 仅存哈希。""" with app.app_context(): event = append_shipping_audit_event( event_type='workflow_item_created', aggregate_type='shipping_notice_workflow_item', aggregate_id='SWI-1', workflow_id='SWF-1', workflow_item_id='SWI-1', version_no=1, owner_user_id=42, conversation_id='conv-session-1', client_ip='203.0.113.9', user_agent='Mozilla/5.0 TestAgent', after={ 'lifecycle_status': 'pending_review', 'current_version_no': 1, 'item_no': 'SWI-1', 'workflow_no': 'SWF-1', }, metadata={'source': 'upload'}, ) db.session.commit() assert event.workflow_id == 'SWF-1' assert event.workflow_item_id == 'SWI-1' assert event.version_no == 1 assert event.event_hash assert event.diff_json is not None assert event.owner_user_id == '42' assert event.client_ip_hash == hash_client_context_value('203.0.113.9') assert event.user_agent_hash == hash_client_context_value('Mozilla/5.0 TestAgent') assert event.client_ip_hash != '203.0.113.9' assert event.after_snapshot_json == { 'lifecycle_status': 'pending_review', 'current_version_no': 1, 'item_no': 'SWI-1', 'workflow_no': 'SWF-1', } with pytest.raises(ValidationError) as caught: append_shipping_audit_event( event_type='probe', aggregate_type='shipping_notice_workflow_item', aggregate_id='SWI-2', metadata={'client_ip': '203.0.113.9'}, ) assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN' db.session.rollback() def test_stage0_i18n_key_inventory_is_frozen(): """四语言所需 key 清单必须冻结且覆盖阶段/健康/取消/审计错误前缀。""" assert AUDIT_RETENTION_DAYS == 365 * 3 joined = '\n'.join(I18N_KEY_INVENTORY) assert 'shippingOrderExtractionUserStage.cancellation_requested' in joined assert 'shippingOrderExtractionHealthTip.processing_attention' in joined assert 'SHIPPING_NOTICE.CANCEL_REASON_REQUIRED' in joined assert 'admin.shippingAudit.export' in joined def test_shipping_audit_result_literals_follow_service_contract(): """生产代码中的审计 result 字面量必须受统一枚举约束,禁止 ok/failed/needs_review 等业务状态越界。""" allowed_results = {'success', 'failure', 'rejected', 'ignored'} backend_app = Path(__file__).resolve().parents[1] / 'app' invalid_literals: list[str] = [] def _result_literal_values(node: ast.AST) -> list[str]: """提取 result 表达式实际可能返回的字符串分支,不把比较条件中的事件名误判为结果值。""" if isinstance(node, ast.Constant) and isinstance(node.value, str): return [node.value] if isinstance(node, ast.IfExp): return _result_literal_values(node.body) + _result_literal_values(node.orelse) return [] # 关键断言:递归检查条件表达式中的所有字符串分支,避免只验证最终运行到的单一路径。 for source_path in backend_app.rglob('*.py'): tree = ast.parse(source_path.read_text(encoding='utf-8-sig'), filename=str(source_path)) for node in ast.walk(tree): if not isinstance(node, ast.Call): continue function_name = ( node.func.id if isinstance(node.func, ast.Name) else node.func.attr if isinstance(node.func, ast.Attribute) else '' ) if function_name not in {'append_shipping_audit_event', '_layout_job_audit'}: continue result_keyword = next((item for item in node.keywords if item.arg == 'result'), None) if result_keyword is None: continue for result_value in _result_literal_values(result_keyword.value): if result_value not in allowed_results: relative_path = source_path.relative_to(backend_app.parent) invalid_literals.append(f'{relative_path}:{node.lineno}:{result_value}') assert invalid_literals == []