fix: bound post-repair readwrite consent to proven local startup

This commit is contained in:
阿白叔 committed 2026-11-03 09:36:33 +08:00
1 parent 5a758ee3b6
commit aa6684b588
8 files changed
+500 -1

No files matched your search

+2
View File
@@ -65,6 +65,8 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa
{'safe_to_continue': True, 'native_exited': True, 'addresses': []})
def verify(req, **kwargs):
calls.append('verify')
from cbb_refresh_verify.post_repair_consent import PostRepairProof
assert isinstance(req.post_repair_proof, PostRepairProof)
assert not req.maintenance and not req.auto_repair
assert req.lmc_file == request.lmc_file and req.block_name == request.block_name
return runner.VerifyResult('PASS', library_flag='GREEN')
+197
View File
@@ -0,0 +1,197 @@
"""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()
def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch):
from cbb_refresh_verify import post_repair_consent as consent
_, _, proof, job = context
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'