Files
syops/backend/tests/test_shipping_audit_snapshot_service.py

357 lines
15 KiB
Python

"""
backend/tests/test_shipping_audit_snapshot_service.py
用途:验收审计快照白名单/Diff/哈希链,以及 XFA 加密不可变完整快照(阶段 5)。
依赖:audit_snapshot_service、audit_service、ShippingAuditEvent、ShippingXfaAuditSnapshot。
逻辑:sanitize/diff 白名单;连续 append 形成哈希链;Core 篡改后链校验失败;
XFA 完整快照用 SECRET_KEY 派生 Fernet 加密入库(无独立审计密钥);
缺 SECRET_KEY 失败关闭、密文静态不可读、脱敏摘要可导出。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from sqlalchemy import text
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.audit_snapshot_service import (
compute_snapshot_diff,
create_xfa_audit_snapshot,
decrypt_xfa_audit_snapshot_row,
require_xfa_audit_crypto,
sanitize_snapshot,
serialize_xfa_audit_snapshot_summary,
verify_event_hash_chain,
)
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
def _ensure_secret_key(app) -> None:
"""确保 SECRET_KEY 可用于派生 XFA 审计快照 Fernet(无独立审计密钥)。"""
if not str(app.config.get('SECRET_KEY') or '').strip():
app.config['SECRET_KEY'] = 'test-shipping-xfa-audit-secret'
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)
def test_xfa_audit_event_types_cover_plan_nodes(app):
"""方案文档列出的 XFA 操作节点均已注册为可审计事件码。"""
with app.app_context():
# 关键断言:阶段 0 冻结的 XFA 审计事件集合非空且含关键写/读/运行节点。
required = {
'xfa_sample_uploaded',
'xfa_parse_started',
'xfa_parse_completed',
'xfa_mapping_saved',
'xfa_sensitive_sample_value_read',
'xfa_profile_matched',
'xfa_extraction_completed',
'xfa_audit_snapshot_viewed',
}
assert required.issubset(XFA_AUDIT_EVENT_TYPES)
def test_xfa_encrypted_snapshot_not_plaintext_and_roundtrip(app):
"""完整快照密文静态不可读;解密后与原文一致。"""
with app.app_context():
_ensure_secret_key(app)
payload = {
'definition': {'template_mode': 'xfa_dataset', 'header_mappings': [{'field_code': 'po'}]},
'definition_checksum': 'abc123',
'raw_sample': '4510039227',
}
row = create_xfa_audit_snapshot(
payload=payload,
object_type='shipping_order_document_profile',
object_id='99',
purpose='after',
actor_id=7,
operation_id='op-xfa-1',
request_id='req-xfa-1',
)
db.session.commit()
persisted = db.session.get(ShippingXfaAuditSnapshot, row.id)
assert persisted is not None
# 关键断言:库内仅密文,不含明文订单号。
assert '4510039227' not in persisted.ciphertext
assert persisted.ciphertext_sha256
assert persisted.plaintext_sha256
assert persisted.retention_expires_at is not None
# 保留期约 3 年(1095 天 ± 1 天缓冲)。
delta = persisted.retention_expires_at - datetime.utcnow()
assert timedelta(days=1090) <= delta <= timedelta(days=1100)
summary = serialize_xfa_audit_snapshot_summary(persisted)
assert 'ciphertext' not in summary
assert summary['redacted_summary'].get('definition_checksum') == 'abc123'
assert 'raw_sample' not in (summary.get('redacted_summary') or {})
decrypted = decrypt_xfa_audit_snapshot_row(persisted)
assert decrypted['raw_sample'] == '4510039227'
assert decrypted['definition_checksum'] == 'abc123'
def test_xfa_sensitive_write_fails_closed_without_master_key(app):
"""缺少 SECRET_KEY 时敏感写(加密快照)失败关闭。"""
with app.app_context():
app.config['SECRET_KEY'] = ''
with pytest.raises(ServiceUnavailableError) as caught:
require_xfa_audit_crypto()
assert caught.value.code == 'SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_SECRET_MISSING'
with pytest.raises(ServiceUnavailableError):
append_shipping_audit_event(
event_type='xfa_mapping_saved',
aggregate_type='shipping_order_document_profile',
aggregate_id='1',
actor_type='admin',
actor_id=1,
operation_id='op-no-key',
result='success',
sensitivity_level='sensitive',
after={'definition_checksum': 'x', 'template_mode': 'xfa_dataset'},
full_after={'definition': {'template_mode': 'xfa_dataset'}, 'definition_checksum': 'x'},
)
def test_xfa_change_event_includes_checksum_diff_and_snapshot_refs(app):
"""变更事件含 before/after checksum、脱敏 diff 与完整快照引用;同事务可回滚。"""
with app.app_context():
_ensure_secret_key(app)
event = append_shipping_audit_event(
event_type='xfa_mapping_saved',
aggregate_type='shipping_order_document_profile',
aggregate_id='42',
actor_type='admin',
actor_id=3,
operation_id='op-map-1',
request_id='req-map-1',
result='success',
sensitivity_level='sensitive',
before={'definition_checksum': 'before-cs', 'template_mode': 'xfa_dataset', 'bound_field_count': 1},
after={'definition_checksum': 'after-cs', 'template_mode': 'xfa_dataset', 'bound_field_count': 2},
full_before={'definition': {'v': 1}, 'definition_checksum': 'before-cs'},
full_after={'definition': {'v': 2}, 'definition_checksum': 'after-cs'},
)
db.session.commit()
# 关键断言:actor/time/request/operation/对象/结果齐全。
assert event.actor_id == '3'
assert event.created_at is not None
assert event.request_id == 'req-map-1'
assert event.operation_id == 'op-map-1'
assert event.aggregate_id == '42'
assert event.result == 'success'
assert event.before_hash
assert event.after_hash
assert event.diff_json is not None
assert event.diff_json['changed']['definition_checksum']['from'] == 'before-cs'
ctx = event.context_refs_json or {}
assert ctx.get('snapshot_before_ref', '').startswith('xfa-snap-')
assert ctx.get('snapshot_after_ref', '').startswith('xfa-snap-')
assert ShippingXfaAuditSnapshot.query.count() >= 2
def test_audit_failure_rolls_back_business_marker(app):
"""审计/快照失败时业务写入不得提交(同事务回滚)。"""
with app.app_context():
prior_secret = app.config.get('SECRET_KEY')
app.config['SECRET_KEY'] = ''
try:
# 同事务先写入一条普通审计作为“业务侧事实”,再触发敏感快照失败。
append_shipping_audit_event(
event_type='xfa_draft_created',
aggregate_type='shipping_order_document_profile',
aggregate_id='rollback-1',
actor_type='admin',
actor_id=1,
result='success',
after={'template_mode': 'xfa_dataset', 'definition_checksum': 'draft'},
)
with pytest.raises(ServiceUnavailableError):
append_shipping_audit_event(
event_type='xfa_mapping_saved',
aggregate_type='shipping_order_document_profile',
aggregate_id='rollback-1',
actor_type='admin',
actor_id=1,
result='success',
sensitivity_level='sensitive',
after={'definition_checksum': 'x', 'template_mode': 'xfa_dataset'},
full_after={'definition': {'template_mode': 'xfa_dataset'}, 'definition_checksum': 'x'},
)
db.session.rollback()
# 关键断言:失败回滚后该聚合无任何审计事件。
assert (
ShippingAuditEvent.query
.filter_by(aggregate_type='shipping_order_document_profile', aggregate_id='rollback-1')
.count()
) == 0
assert ShippingXfaAuditSnapshot.query.filter_by(object_id='rollback-1').count() == 0
finally:
app.config['SECRET_KEY'] = prior_secret
def test_stp_auto_create_nodes_write_traceable_audit(app):
"""自动建单尝试/成功/幂等/失败均可追溯到 Run、Candidate、Profile。"""
with app.app_context():
for event_type, result, action in (
('candidate_qualification_evaluated', 'success', 'evaluate'),
('order_stp_auto_create_attempted', 'success', 'attempt'),
('order_stp_auto_create_succeeded', 'success', 'create'),
('order_stp_auto_create_idempotent_replay', 'ignored', 'replay'),
('order_stp_auto_create_failed', 'failure', 'create'),
):
append_shipping_audit_event(
event_type=event_type,
aggregate_type='shipping_order_candidate',
aggregate_id='CAND-XFA-1',
run_no='SNER-XFA-1',
actor_type='system',
result=result,
action=action,
operation_id=f'op-{action}',
request_id=f'req-{action}',
after={
'candidate_no': 'CAND-XFA-1',
'run_no': 'SNER-XFA-1',
'profile_code': 'XFA_PO_V1',
'profile_version': 1,
'definition_checksum': 'pub-cs',
},
metadata={'revision_no': 3},
)
db.session.commit()
rows = (
ShippingAuditEvent.query
.filter(ShippingAuditEvent.aggregate_id == 'CAND-XFA-1')
.order_by(ShippingAuditEvent.id.asc())
.all()
)
# 关键断言:五条节点均带 Run/Candidate/Profile 身份与 operation_id。
assert len(rows) == 5
for row in rows:
assert row.run_no == 'SNER-XFA-1'
assert row.operation_id
assert row.request_id
assert (row.after_snapshot_json or {}).get('profile_code') == 'XFA_PO_V1'