"""Local recovery consent boundaries. No native application may be launched.""" from dataclasses import replace import json import os from pathlib import Path from types import SimpleNamespace import pytest @pytest.fixture(autouse=True) def no_native_launch(monkeypatch): import subprocess, win32process, win32com.client def forbidden(*a, **k): raise AssertionError('native launching forbidden in consent tests') monkeypatch.setattr(subprocess, 'Popen', forbidden) monkeypatch.setattr(win32process, 'CreateProcess', forbidden) monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden) monkeypatch.setattr(win32com.client, 'Dispatch', forbidden) @pytest.fixture def context(tmp_path, monkeypatch): from test_native_repair import target_fixture, complete_native_success from cbb_refresh_verify import post_repair_consent as consent request, _, target = target_fixture(tmp_path) request = replace(request, maintenance=True) # Existing fixture contains only required native files and no address. (target.project.parent/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n') monkeypatch.setattr(consent, '_process_records', lambda: []) monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name', lambda: 'CbbVerify_fixture') proof = consent.PostRepairProof.create(request, target, complete_native_success(target)) job = {'root': str(tmp_path/'verify'), 'lmc_file': str(request.lmc_file), 'project': str(target.project), 'pcb': str(target.project.parent/'PCB/actual.pcb'), 'block_name': request.block_name, 'desktop': 'CbbVerify_fixture', 'supervisor_pid': 55, 'interactive_input': False, 'native_lm_verify': False} Path(job['root']).mkdir() job['post_repair_consent'] = proof.for_job(job) return request, target, proof, job def snapshot(): from cbb_refresh_verify.post_repair_consent import PROMPT_TEXT from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase return WindowSnapshot(100, 20, 'ExpeditionPCB.exe', 'pcb', '#32770', 'Expedition PCB', DialogPhase.PCB_STARTING, ( ControlSnapshot(106, 6, 'Button', '是(&Y)'), ControlSnapshot(107, 7, 'Button', '否(&N)'), ControlSnapshot(120, 20, 'Static', ''), ControlSnapshot(199, 65535, 'Static', PROMPT_TEXT))) def test_no_generic_maintenance_flag_can_mint_consent(tmp_path): from cbb_refresh_verify.post_repair_consent import PostRepairProof from test_native_repair import target_fixture, complete_native_success request, _, target = target_fixture(tmp_path) with pytest.raises(ValueError): PostRepairProof.create(request, target, complete_native_success(target)) for status in ('RESTORED_REVIEW_REQUIRED', 'UNCONFIRMED', 'FAIL'): result = complete_native_success(target); result['status'] = status with pytest.raises(ValueError): PostRepairProof.create(replace(request, maintenance=True), target, result) @pytest.mark.parametrize('kind', ['unc', 'network', 'removable', 'reparse']) def test_consent_rejects_nonlocal_or_reparse_paths(context, monkeypatch, kind): from cbb_refresh_verify import post_repair_consent as consent request, _, _, _ = context path = request.lmc_file if kind == 'unc': path = Path(r'\\server\share\library.lmc') monkeypatch.setattr(consent, '_drive_type', lambda path: {'network': 4, 'removable': 2}.get(kind, 3)) if kind == 'reparse': original = Path.lstat monkeypatch.setattr(Path, 'lstat', lambda self: SimpleNamespace(st_file_attributes=0x400) if self == path.parent else original(self)) with pytest.raises(ValueError, match='LOCAL_FIXED'): consent.require_local_fixed(path) @pytest.mark.parametrize('obstacle', ['owner', 'address', 'exclusive', 'wrong_target', 'network', 'desktop']) def test_prelaunch_proof_blocks_without_launch(context, monkeypatch, obstacle): import win32file, win32con from cbb_refresh_verify import post_repair_consent as consent _, target, _, job = context handle = None if obstacle == 'owner': monkeypatch.setattr(consent, '_process_records', lambda: [(777, 'viewdraw.exe', '', '', 0)]) if obstacle == 'address': p = target.database/'cdbsvr/sAddress.adr'; p.parent.mkdir(parents=True); p.touch() if obstacle == 'exclusive': handle = win32file.CreateFile(str(target.project.parent/'PCB/Layout/LayoutDB.lyt'), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None) if obstacle == 'wrong_target': job['pcb'] = str(Path(job['pcb']).with_name('other.pcb')) if obstacle == 'network': monkeypatch.setattr(consent, '_drive_type', lambda path: 4) if obstacle == 'desktop': monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name', lambda: 'Default') try: with pytest.raises((ValueError, OSError)): consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit']) assert not (Path(job['root'])/'post-repair-prelaunch.json').exists() finally: if handle: handle.Close() @pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template']) def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch, pcb_config): from cbb_refresh_verify import post_repair_consent as consent _, _, proof, job = context if pcb_config == 'legacy_template': pcb = Path(job['pcb']) (pcb.parent/'pcb.prj').rename(pcb.parent/'template.prj') pcb.write_text('KEY ProjectFile "../'+Path(job['project']).name+'"\n') command = ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'] consent.prepare_launch(job, command) controller = consent.ConsentController(proof, job) monkeypatch.setattr(consent, '_validate_current_processes', lambda *args: None) calls = [] def perform(snap, payload, phase): calls.append(payload) return SimpleNamespace(accepted_controls=(6,), channel='win32_button_click', error_code='', detail='') first = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=19, worker_pid=os.getpid(), companion_pids=(), perform=perform) assert first.action_sent and calls[0]['target'] == {'control_id': 6} again = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=19, worker_pid=os.getpid(), companion_pids=(), perform=perform) assert not again.action_sent and len(calls) == 1 changed = replace(snapshot(), hwnd=101) rejected = controller.handle(changed, (changed,), target_pid=20, launcher_pid=19, worker_pid=os.getpid(), companion_pids=(), perform=perform) assert rejected.error_code == 'DATABASE_RECOVERY_REQUIRED' and len(calls) == 1 @pytest.mark.parametrize('change', ['pid', 'phase', 'text', 'button', 'extra', 'proof', 'foreign_owner']) def test_consent_rejects_unbound_or_changed_prompt(context, monkeypatch, change): from cbb_refresh_verify import post_repair_consent as consent from cbb_refresh_verify.dialog_models import DialogPhase, ControlSnapshot _, _, proof, job = context consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit']) controller = consent.ConsentController(proof, job) snap = snapshot() if change == 'pid': snap = replace(snap, pid=99) if change == 'phase': snap = replace(snap, phase=DialogPhase.SAVE) if change == 'text': snap = replace(snap, controls=(*snap.controls[:-1], replace(snap.controls[-1], name='Confirm read/write?'))) if change == 'button': snap = replace(snap, controls=(replace(snap.controls[0], enabled=False), *snap.controls[1:])) if change == 'extra': snap = replace(snap, controls=(*snap.controls, ControlSnapshot(300, 99, 'Button', 'Overwrite'))) if change == 'proof': (Path(job['root'])/'post-repair-prelaunch.json').write_text('{}') def processes(*a): if change == 'foreign_owner': raise ValueError('unexpected owner') monkeypatch.setattr(consent, '_validate_current_processes', processes) result = controller.handle(snap, (snap,), target_pid=20, launcher_pid=19, worker_pid=os.getpid(), companion_pids=(), perform=lambda *a: pytest.fail('unapproved consent sent')) assert result.error_code == 'DATABASE_RECOVERY_REQUIRED' @pytest.mark.parametrize('change', ['', 'other_owner', 'target_command', 'launcher_command', 'target_parent', 'launcher_parent', 'executable', 'missing_launcher']) def test_current_process_identity_requires_exact_owned_launch_chain(context, monkeypatch, change): from cbb_refresh_verify import post_repair_consent as consent _, _, _, job = context launcher = r'C:\Mentor\common\win32\bin\ExpeditionPCB.exe' worker = r'C:\Mentor\wg\win32\bin\ExpeditionPCB.exe' command = lambda exe: f'"{exe}" "{job["pcb"]}" -ReusableCircuit' rows = [(19, 'ExpeditionPCB.exe', launcher, command(launcher), 18), (20, 'ExpeditionPCB.exe', worker, command(worker), 19)] if change == 'other_owner': rows.append((99, 'viewdraw.exe', 'viewdraw.exe', '', 0)) if change == 'target_command': rows[1] = (20, 'ExpeditionPCB.exe', worker, 'other.pcb -ReusableCircuit', 19) if change == 'launcher_command': rows[0] = (19, 'ExpeditionPCB.exe', launcher, 'other.pcb -ReusableCircuit', 18) if change == 'target_parent': rows[1] = (*rows[1][:4], 999) if change == 'launcher_parent': rows[0] = (*rows[0][:4], 999) if change == 'executable': rows[1] = (20, 'ExpeditionPCB.exe', 'C:/unrelated/ExpeditionPCB.exe', command(worker), 19) if change == 'missing_launcher': rows.pop(0) monkeypatch.setattr(consent, '_process_records', lambda: rows) args = (job, {'command': [launcher, job['pcb'], '-ReusableCircuit']}, 20, 19, 18, ()) if change: with pytest.raises(ValueError): consent._validate_current_processes(*args) else: consent._validate_current_processes(*args) @pytest.mark.parametrize('change', ['', 'desktop', 'pid', 'text', 'button', 'generic_action']) def test_agent_revalidates_real_window_before_single_button_message(monkeypatch, change): import win32gui, win32process from cbb_refresh_verify.dialog_agent import DialogActionExecutor from cbb_refresh_verify import native_repair_ui value = snapshot() controls = {c.handle: c for c in value.controls} monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default' if change == 'desktop' else 'CbbVerify_fixture') monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99 if change == 'pid' else 20)) monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: '#32770' if hwnd == 100 else controls[hwnd].class_name) monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else 'changed prompt' if change == 'text' and hwnd == 199 else controls[hwnd].name) monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True) monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd: not (change == 'button' and hwnd == 106)) monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: controls[hwnd].control_id) monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, callback, arg: [callback(child, arg) for child in controls]) calls = [] monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: calls.append(args)) payload = {'action': 'post_repair_local_read_write', 'channels': ['win32_button_click'], 'target': {'control_id': 6}, 'pid': 20, 'desktop': 'CbbVerify_fixture'} if change == 'generic_action': payload.pop('desktop') result = DialogActionExecutor().perform(value, payload) assert bool(result.accepted_controls) is (not change) assert len(calls) == (0 if change else 1) def test_ordinary_rule_remains_hard_blocked_for_exact_recovery_prompt(): from cbb_refresh_verify.dialog_rules import decide assert decide(snapshot(), ()).error_code == 'DATABASE_RECOVERY_REQUIRED' def enriched_snapshot(): """Sanitized actual aa-r2 merged Win32/UIA capture (only HWNDs changed).""" from cbb_refresh_verify.dialog_models import ControlSnapshot value = snapshot() native = (replace(value.controls[0], name='是(Y)', automation_id='6', control_type='Button', patterns=('Invoke',)), replace(value.controls[1], name='否(N)', automation_id='7', control_type='Button', patterns=('Invoke',)), replace(value.controls[2], automation_id='20', control_type='Image'), replace(value.controls[3], automation_id='65535', control_type='Text')) return replace(value, controls=(*native, ControlSnapshot(value.hwnd, 0, '#32770', 'Expedition PCB', control_type='Window', patterns=('Window',)), ControlSnapshot(0, 0, '', '', control_type='TitleBar', patterns=('Value',)), ControlSnapshot(0, 0, '', '关闭', control_type='Button', enabled=False, patterns=('Invoke',)))) @pytest.mark.parametrize('change', ['', 'extra_real_child', 'enabled_close', 'titlebar_text', 'other_self']) def test_enriched_native_prompt_ignores_only_observed_uia_chrome(change): from cbb_refresh_verify.post_repair_consent import exact_prompt from cbb_refresh_verify.dialog_models import ControlSnapshot value = enriched_snapshot() if change == 'extra_real_child': value = replace(value, controls=(*value.controls, ControlSnapshot(888, 0, '', '关闭', control_type='Button', enabled=False, patterns=('Invoke',)))) if change == 'enabled_close': value = replace(value, controls=(*value.controls[:-1], replace(value.controls[-1], enabled=True))) if change == 'titlebar_text': value = replace(value, controls=(*value.controls[:-2], replace(value.controls[-2], name='unexpected'), value.controls[-1])) if change == 'other_self': value = replace(value, controls=(*value.controls[:4], replace(value.controls[4], handle=999), *value.controls[5:])) assert exact_prompt(value) is (not change) def test_enriched_prompt_still_reaches_live_native_child_check(monkeypatch): import win32gui, win32process from cbb_refresh_verify.post_repair_consent import validate_action_window from cbb_refresh_verify import native_repair_ui value = enriched_snapshot() native = {c.handle: c for c in value.controls[:4]} monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_fixture') monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 20)) monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True) monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd: True) monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: value.window_class if hwnd == value.hwnd else native[hwnd].class_name) monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: value.title if hwnd == value.hwnd else native[hwnd].name) monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: native[hwnd].control_id) monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: [fn(child, arg) for child in native]) validate_action_window(value, {'pid':20, 'desktop':'CbbVerify_fixture'})