""" backend/tests/test_shipping_audit_snapshot_service.py 用途:验收审计快照白名单、Diff 计算与同聚合 event_hash 哈希链完整性。 依赖:audit_snapshot_service、audit_service、ShippingAuditEvent、SQLAlchemy Core UPDATE。 逻辑:sanitize/diff 只保留白名单键;连续 append 形成 previous→event 链; Core UPDATE 篡改后 verify_event_hash_chain 必须失败。 """ from __future__ import annotations from sqlalchemy import text from app import db from app.models import ShippingAuditEvent from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.audit_snapshot_service import ( compute_snapshot_diff, sanitize_snapshot, verify_event_hash_chain, ) def test_sanitize_snapshot_whitelists_keys(app): """sanitize_snapshot 仅保留白名单键,未知业务键被剔除。""" with app.app_context(): projected = sanitize_snapshot({ 'status': 'processing', 'progress_version': 2, 'orders': [{'po': '45001'}], 'lifecycle_status': 'extracting', }) # 关键断言:白名单键保留,订单正文类键不得进入快照。 assert projected == { 'status': 'processing', 'progress_version': 2, 'lifecycle_status': 'extracting', } def test_compute_snapshot_diff_detects_changed_keys(app): """compute_snapshot_diff 输出 changed/added/removed 三段。""" with app.app_context(): diff = compute_snapshot_diff( {'status': 'queued', 'progress_version': 1}, {'status': 'processing', 'lifecycle_status': 'extracting'}, ) # 关键断言:status 变更、lifecycle 新增、progress_version 移除。 assert diff is not None assert diff['changed']['status'] == {'from': 'queued', 'to': 'processing'} assert diff['added']['lifecycle_status'] == 'extracting' assert diff['removed']['progress_version'] == 1 def test_append_builds_event_hash_chain_and_verify_passes(app): """同聚合连续 3 条事件形成 previous_event_hash → event_hash 链,校验通过。""" with app.app_context(): aggregate_type = 'shipping_notice_workflow_item' aggregate_id = 'WFI-HASH-CHAIN-1' events = [] for index in range(3): events.append( append_shipping_audit_event( event_type='workflow_stage_changed', aggregate_type=aggregate_type, aggregate_id=aggregate_id, workflow_id='WF-HASH-1', workflow_item_id=aggregate_id, action=f'step-{index}', before={'lifecycle_status': f's-{index}'}, after={'lifecycle_status': f's-{index + 1}'}, ) ) db.session.commit() # 关键断言:首条无前驱;后续 previous 等于上一条 event_hash。 assert events[0].event_hash assert events[0].previous_event_hash is None assert events[1].previous_event_hash == events[0].event_hash assert events[2].previous_event_hash == events[1].event_hash assert len({e.event_hash for e in events}) == 3 ordered = ( ShippingAuditEvent.query .filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id) .order_by(ShippingAuditEvent.id.asc()) .all() ) ok, failures = verify_event_hash_chain(ordered) assert ok is True assert failures == [] def test_verify_event_hash_chain_fails_after_core_tamper(app): """经 Core UPDATE 篡改 event_hash 后,链校验必须失败。""" with app.app_context(): aggregate_type = 'shipping_notice_workflow_item' aggregate_id = 'WFI-HASH-TAMPER-1' for index in range(3): append_shipping_audit_event( event_type='workflow_stage_changed', aggregate_type=aggregate_type, aggregate_id=aggregate_id, workflow_id='WF-HASH-T', workflow_item_id=aggregate_id, action=f'tamper-{index}', after={'lifecycle_status': f't-{index}'}, ) db.session.commit() middle = ( ShippingAuditEvent.query .filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id) .order_by(ShippingAuditEvent.id.asc()) .offset(1) .first() ) assert middle is not None # Core UPDATE 绕过 ORM append-only 守卫,模拟存储层篡改。 db.session.execute( text('UPDATE shipping_audit_events SET event_hash = :h WHERE id = :id'), {'h': 'deadbeef', 'id': middle.id}, ) db.session.commit() ordered = ( ShippingAuditEvent.query .filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id) .order_by(ShippingAuditEvent.id.asc()) .all() ) ok, failures = verify_event_hash_chain(ordered) # 关键断言:至少一条 event_hash_mismatch 或后续 previous_hash_mismatch。 assert ok is False assert any(row['reason'] in {'event_hash_mismatch', 'previous_hash_mismatch'} for row in failures)