"""收料文件下载和人工补偿的权限/审计契约测试。""" from __future__ import annotations def _headers(username: str, role: str) -> dict[str, str]: return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, monkeypatch): """排程接收人可下载原样文件;非接收人不可通过猜测 ID 越权。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): recipient = User(username='receipt-download-user', email='receipt-download@example.com', role='user', status='active') other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active') db.session.add_all([recipient, other]); db.session.flush() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success') db.session.add(run); db.session.flush() unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64) db.session.add(report_file); db.session.commit() file_id = report_file.id monkeypatch.setattr('app.services.shipping_notice.receipt_report_access.file_asset_storage.get_bytes', lambda _key: b'xlsx') allowed = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user')) denied = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user')) assert allowed.status_code == 200 assert allowed.data == b'xlsx' assert denied.status_code == 403 def test_receipt_recipient_lists_only_own_archived_files(app, client): """接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): recipient = User(username='receipt-list-user', email='receipt-list@example.com', role='user', status='active') other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active') db.session.add_all([recipient, other]); db.session.flush() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id]) db.session.add_all([own_task, other_task]); db.session.flush() own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success') other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success') db.session.add_all([own_run, other_run]); db.session.flush() own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={}) other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={}) db.session.add_all([own_unit, other_unit]); db.session.flush() own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64) db.session.add_all([own_file, ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)]) db.session.commit() own_file_id = own_file.id response = client.get('/api/workspace/receipt-report-files', headers=_headers('receipt-list-user', 'user')) assert response.status_code == 200 items = response.get_json()['data']['items'] # 关键断言:列表投影不能泄露非接收人的文件或对象存储定位。 assert [item['id'] for item in items] == [own_file_id] assert 'storage_key' not in items[0] assert items[0]['download_url'].endswith(f'/receipt-report-files/{own_file_id}/download') def test_receipt_file_list_filters_before_applying_limit(app): """其他人的新文件再多,也不能挤掉接收人较早的可见归档。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User from app.services.shipping_notice.receipt_report_access import list_receipt_report_files with app.app_context(): recipient = User(username='receipt-limit-user', email='receipt-limit@example.com', role='user', status='active') other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active') db.session.add_all([recipient, other]); db.session.flush() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id]) db.session.add_all([own_task, other_task]); db.session.flush() own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success') other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success') db.session.add_all([own_run, other_run]); db.session.flush() own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={}) other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={}) db.session.add_all([own_unit, other_unit]); db.session.flush() own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64) db.session.add(own_file); db.session.flush() for index in range(3): db.session.add(ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64)) db.session.commit() items = list_receipt_report_files(recipient, limit=1) # 关键断言:授权过滤发生在截断之前,避免被其他排程的归档饿死。 assert [item['id'] for item in items] == [own_file.id] def test_admin_can_resend_without_reexporting(app, client, monkeypatch): """管理员重发只调用文件投递,不创建 RPA 单元或 trigger。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id]) db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success') db.session.add(run); db.session.flush() unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64) db.session.add(report_file); db.session.commit() file_id = report_file.id calls = [] monkeypatch.setattr('app.api.schedule.runs.deliver_receipt_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0}) response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin')) assert response.status_code == 200 assert calls == [(file_id, True)] def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch): """失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed') db.session.add(run); db.session.flush() failed = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []}) db.session.add(failed); db.session.commit() failed_id = failed.id captured = [] monkeypatch.setattr('app.api.schedule.runs.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json') response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin')) assert response.status_code == 200 with app.app_context(): retry = ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=failed_id).one() assert retry.status == 'awaiting_rpa' assert retry.callback_id != 'receipt-failed' assert captured and captured[0][1][0]['callback_id'] == retry.callback_id def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client): """管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed') db.session.add(run); db.session.flush() unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={}) db.session.add(unit); db.session.commit() unit_id = unit.id response = client.get('/api/admin/receipt-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin')) assert response.status_code == 200 assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id] with app.app_context(): assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_units_listed').count() == 1