fix: bound post-repair readwrite consent to proven local startup
This commit is contained in:
1 parent
5a758ee3b6
commit
aa6684b588
8 files changed
+500
-1
No files matched your search
@@ -236,6 +236,14 @@ class DialogActionExecutor:
|
||||
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
|
||||
channels = tuple(action.get("channels", ()))
|
||||
action_name = action.get("action")
|
||||
if action_name == 'post_repair_local_read_write':
|
||||
try:
|
||||
from .post_repair_consent import validate_action_window
|
||||
validate_action_window(snapshot, action)
|
||||
if channels != ('win32_button_click',) or action.get('target') != {'control_id': 6}:
|
||||
raise ValueError('POST_REPAIR_ACTION_MISMATCH')
|
||||
except Exception as error:
|
||||
return ActionResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error))
|
||||
if action_name == "accept_license":
|
||||
target = self._license_target(snapshot)
|
||||
elif action_name == "restore_last_saved":
|
||||
|
||||
@@ -196,8 +196,11 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
owner_safe = safe and (confirmed or completed_failure)
|
||||
if confirmed:
|
||||
emit('repair_verify', detail='原生修复及释放已确认,重新打开同一工程校验')
|
||||
from .post_repair_consent import PostRepairProof
|
||||
owner_safe = False
|
||||
verified = verify(replace(request, maintenance=False, auto_repair=False))
|
||||
proof = PostRepairProof.create(request, target, recovery)
|
||||
verified = verify(replace(request, maintenance=False, auto_repair=False,
|
||||
post_repair_proof=proof, interactive_input=False, native_lm_verify=False))
|
||||
owner_safe = verified.safe_to_continue
|
||||
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
||||
recovery.update(status='REPAIRED' if good else 'REPAIR_VALIDATION_FAILED',
|
||||
|
||||
@@ -736,6 +736,9 @@ def execute_job(job, emit):
|
||||
emit(stage='lm_session_ready', lm_pid=lm_pid, block=job['block_name'])
|
||||
else:
|
||||
command = build_pcb_launch_command(job['pcb'], job.get('mentor_bin'))
|
||||
if job.get('post_repair_consent') is not None:
|
||||
from .post_repair_consent import prepare_launch
|
||||
prepare_launch(job, command)
|
||||
emit(stage='pcb_launch', command=list(command), strategy='reusable_circuit_direct')
|
||||
launcher_process = launch_pcb_process(command, Path(job['pcb']).parent)
|
||||
worker_parent_pid = int(launcher_process.pid)
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
"""One-use, local-only read/write consent after proven explicit native Repair.
|
||||
|
||||
No normal Verify or declarative rule can enable this path. Database recovery
|
||||
choices other than the captured read/write question remain unsupported.
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
PROMPT_TEXT = ("If an XDS or ExpeditionPCB is running on this design, it's likely that\n"
|
||||
"your file system and/or network system was too slow to determine\n"
|
||||
"which product the design is open in within the 15 second timeout\nperiod.\n\n"
|
||||
"Otherwise, the design may not have been closed properly due to\n"
|
||||
"the XDS or ExpeditionPCB crashing in the last session.\n\n"
|
||||
"Before continuing, please confirm that no other users have the\ndesign open.\n\n"
|
||||
"Continue to open the design with read/write access permission?")
|
||||
|
||||
|
||||
def _drive_type(path):
|
||||
import win32file
|
||||
return win32file.GetDriveType(str(Path(path).anchor))
|
||||
|
||||
|
||||
def require_local_fixed(path):
|
||||
from .network_path import absolute_preserving_drive
|
||||
path = absolute_preserving_drive(path)
|
||||
if path.drive.startswith('\\') or _drive_type(path) != 3:
|
||||
raise ValueError('LOCAL_FIXED_REQUIRED: 修复后读写确认仅支持本地固定磁盘;UNC/网络盘不自动授权')
|
||||
for item in (path, *path.parents):
|
||||
if item.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
raise ValueError('LOCAL_FIXED_REQUIRED: 不允许重解析点、目录链接或挂载路径')
|
||||
return path
|
||||
|
||||
|
||||
def _same(a, b):
|
||||
return Path(a).resolve() == Path(b).resolve()
|
||||
|
||||
|
||||
def _process_records():
|
||||
import win32com.client
|
||||
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'XDS.exe',
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
|
||||
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe')
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
rows = service.ExecQuery('SELECT ProcessId, Name, ExecutablePath, CommandLine, ParentProcessId '
|
||||
'FROM Win32_Process WHERE ' + ' OR '.join(f"Name='{n}'" for n in names))
|
||||
records = []
|
||||
for item in rows:
|
||||
name, command = str(item.Name), str(item.CommandLine or '')
|
||||
if name.casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe') and command and not any(
|
||||
flag in command for flag in ('--verify-worker', '--repair-worker', '--management-worker', '--dialog-agent')):
|
||||
continue
|
||||
records.append((int(item.ProcessId), name, str(item.ExecutablePath or ''), command, int(item.ParentProcessId or 0)))
|
||||
return records
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PostRepairProof:
|
||||
library: str
|
||||
project: str
|
||||
pcb: str
|
||||
block: str
|
||||
repair_project: str
|
||||
repair_database: str
|
||||
repair_json: str
|
||||
nonce: str
|
||||
|
||||
@classmethod
|
||||
def create(cls, request, target, recovery):
|
||||
from .native_repair import native_success_confirmed
|
||||
from .verify_runner import preflight
|
||||
if request.maintenance is not True or not native_success_confirmed(target, recovery):
|
||||
raise ValueError('POST_REPAIR_PROOF_REQUIRED: 必须是明确维护且严格确认的原生修复')
|
||||
if request.mapped_remote_root:
|
||||
raise ValueError('LOCAL_FIXED_REQUIRED: 网络映射库不自动确认修复后的读写访问')
|
||||
project, pcb = preflight(request)
|
||||
for path in (request.lmc_file, project, pcb, target.database/'icdb.dat', pcb.parent/'Layout/LayoutDB.lyt'):
|
||||
require_local_fixed(path)
|
||||
return cls(str(request.lmc_file), str(project), str(pcb), request.block_name,
|
||||
str(target.project), str(target.database), json.dumps(recovery, ensure_ascii=False, default=str), uuid4().hex)
|
||||
|
||||
def for_job(self, job):
|
||||
if (job.get('interactive_input') or job.get('native_lm_verify')
|
||||
or not str(job.get('desktop', '')).startswith('CbbVerify_')
|
||||
or job['block_name'] != self.block
|
||||
or not all(_same(job[key], value) for key, value in (
|
||||
('lmc_file', self.library), ('project', self.project), ('pcb', self.pcb)))):
|
||||
raise ValueError('POST_REPAIR_TARGET_MISMATCH')
|
||||
return {'nonce': self.nonce, 'intent': 'explicit_maintenance_after_confirmed_repair',
|
||||
'library': self.library, 'project': self.project, 'pcb': self.pcb, 'block': self.block,
|
||||
'repair_project': self.repair_project, 'repair_database': self.repair_database,
|
||||
'repair': json.loads(self.repair_json), 'desktop': job['desktop'], 'root': job['root']}
|
||||
|
||||
|
||||
def _validate_grant(job):
|
||||
from .native_repair import RepairTarget, native_success_confirmed
|
||||
grant = job.get('post_repair_consent')
|
||||
if (not isinstance(grant, dict) or grant.get('intent') != 'explicit_maintenance_after_confirmed_repair'
|
||||
or not isinstance(grant.get('nonce'), str) or len(grant['nonce']) != 32
|
||||
or job.get('interactive_input') or job.get('native_lm_verify') or job.get('mapped_remote_root')
|
||||
or grant.get('desktop') != job.get('desktop') or not str(job.get('desktop', '')).startswith('CbbVerify_')
|
||||
or not _same(grant['root'], job['root']) or grant.get('block') != job.get('block_name')
|
||||
or not all(_same(grant[key], job[field]) for key, field in (
|
||||
('library', 'lmc_file'), ('project', 'project'), ('pcb', 'pcb')))):
|
||||
raise ValueError('POST_REPAIR_PROOF_INVALID')
|
||||
target = RepairTarget(Path(grant['repair_project']), Path(grant['repair_database']))
|
||||
if not native_success_confirmed(target, grant['repair']):
|
||||
raise ValueError('POST_REPAIR_PROOF_INVALID: 原生成功证据不完整')
|
||||
return grant
|
||||
|
||||
|
||||
def prepare_launch(job, command):
|
||||
"""Called on the private worker immediately before direct PCB launch."""
|
||||
import win32file, win32con
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
from .management import _write_json
|
||||
grant = _validate_grant(job)
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
if _current_desktop_name() != job['desktop']:
|
||||
raise ValueError('POST_REPAIR_PRIVATE_DESKTOP_REQUIRED')
|
||||
library, project, pcb = (Path(job[key]) for key in ('lmc_file', 'project', 'pcb'))
|
||||
for path in (library, project, pcb, pcb.parent/'pcb.prj'):
|
||||
require_local_fixed(path)
|
||||
if len(command) != 3 or not _same(command[1], pcb) or command[2] != '-ReusableCircuit':
|
||||
raise ValueError('POST_REPAIR_LAUNCH_MISMATCH')
|
||||
def require_idle():
|
||||
# Self is an expected automation worker, never a native owner.
|
||||
others = [r for r in _process_records() if r[0] not in (os.getpid(), int(job['supervisor_pid']))
|
||||
and not (r[1].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
and '--dialog-agent' in r[3] and r[4] == int(job['supervisor_pid']))]
|
||||
if others: raise ValueError('POST_REPAIR_FOREIGN_OWNER: 存在其他原生进程或助手')
|
||||
require_idle()
|
||||
if unreleased_addresses(library, project, pcb): raise ValueError('POST_REPAIR_ADDRESS_REMAINS')
|
||||
files = [library, pcb.parent/'Layout/LayoutDB.lyt']
|
||||
files.extend(folder/'icdb.dat' for folder in database_directories(library, project, pcb) if (folder/'icdb.dat').is_file())
|
||||
with ExitStack() as stack:
|
||||
for path in dict.fromkeys(files):
|
||||
require_local_fixed(path)
|
||||
try:
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
except Exception as error:
|
||||
raise ValueError(f'POST_REPAIR_EXCLUSIVE_ACCESS_REQUIRED: {path}: {error}') from error
|
||||
stack.callback(handle.Close)
|
||||
if unreleased_addresses(library, project, pcb): raise ValueError('POST_REPAIR_ADDRESS_CHANGED')
|
||||
require_idle()
|
||||
_write_json(Path(job['root'])/'post-repair-prelaunch.json', {
|
||||
'nonce': grant['nonce'], 'desktop': job['desktop'], 'project': str(project), 'pcb': str(pcb),
|
||||
'library': str(library), 'worker_pid': os.getpid(), 'supervisor_pid': job['supervisor_pid'],
|
||||
'command': list(command), 'exclusive_files': [str(path) for path in dict.fromkeys(files)],
|
||||
'addresses': [], 'monotonic': time.monotonic()})
|
||||
|
||||
|
||||
def exact_prompt(snapshot):
|
||||
from .dialog_models import DialogPhase
|
||||
if (snapshot.phase != DialogPhase.PCB_STARTING or snapshot.process_name.casefold() != 'expeditionpcb.exe'
|
||||
or snapshot.process_role != 'pcb' or snapshot.window_class != '#32770' or snapshot.title != 'Expedition PCB'):
|
||||
return False
|
||||
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
|
||||
static = [c for c in snapshot.controls if c.class_name == 'Static' and c.name.strip()]
|
||||
return (len(buttons) == 2 and {c.control_id for c in buttons} == {6, 7}
|
||||
and all(c.enabled for c in buttons) and len(static) == 1 and static[0].control_id == 65535
|
||||
and ' '.join(static[0].name.split()) == ' '.join(PROMPT_TEXT.split())
|
||||
and all(c.class_name == 'Button' or c.class_name == 'Static' and c.control_id in (20, 65535)
|
||||
for c in snapshot.controls))
|
||||
|
||||
|
||||
def _validate_current_processes(job, prelaunch, target_pid, launcher_pid, worker_pid, companion_pids):
|
||||
from .mentor_adapter import is_reusable_circuit_pcb
|
||||
rows = _process_records()
|
||||
by_pid = {r[0]: r for r in rows}
|
||||
if target_pid not in by_pid or launcher_pid not in by_pid:
|
||||
raise ValueError('POST_REPAIR_PROCESS_UNCONFIRMED')
|
||||
target, launcher = by_pid[target_pid], by_pid[launcher_pid]
|
||||
executable = Path(prelaunch['command'][0])
|
||||
expected_worker = executable.parents[3]/'wg/win32/bin/ExpeditionPCB.exe'
|
||||
if (not _same(launcher[2], executable) or not _same(target[2], expected_worker)
|
||||
or launcher[4] != worker_pid or target[4] != launcher_pid
|
||||
or not is_reusable_circuit_pcb(target[2], target[3], job['pcb'])
|
||||
or not is_reusable_circuit_pcb(launcher[2], launcher[3], job['pcb'])):
|
||||
raise ValueError('POST_REPAIR_PROCESS_IDENTITY_MISMATCH')
|
||||
allowed = {target_pid, launcher_pid, worker_pid, int(job['supervisor_pid']), *companion_pids}
|
||||
if any(r[0] not in allowed for r in rows): raise ValueError('POST_REPAIR_FOREIGN_OWNER')
|
||||
|
||||
|
||||
class ConsentController:
|
||||
def __init__(self, proof, job):
|
||||
if not isinstance(proof, PostRepairProof): raise ValueError('POST_REPAIR_PROOF_REQUIRED')
|
||||
self.grant = proof.for_job(job)
|
||||
self.job = json.loads(json.dumps(job))
|
||||
self.used = False
|
||||
self.snapshot = None
|
||||
self.sent_at = 0.0
|
||||
|
||||
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, companion_pids, perform):
|
||||
from .dialog_supervisor import DialogPollResult
|
||||
from .management import _write_json
|
||||
try:
|
||||
if not exact_prompt(snapshot) or snapshot.pid != target_pid:
|
||||
raise ValueError('POST_REPAIR_PROMPT_MISMATCH')
|
||||
if len(snapshots) != 1:
|
||||
raise ValueError('POST_REPAIR_ADDITIONAL_DIALOG')
|
||||
if self.used:
|
||||
if (self.snapshot.hwnd == snapshot.hwnd and self.snapshot.signature == snapshot.signature
|
||||
and time.monotonic() - self.sent_at < 2):
|
||||
return DialogPollResult(activity=False, observed_snapshots=tuple(snapshots))
|
||||
raise ValueError('POST_REPAIR_CONSENT_ALREADY_USED')
|
||||
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
|
||||
required = {Path(self.grant['library']).resolve(),
|
||||
(Path(self.grant['pcb']).parent/'Layout/LayoutDB.lyt').resolve(),
|
||||
(Path(self.grant['repair_database'])/'icdb.dat').resolve()}
|
||||
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
|
||||
or pre.get('worker_pid') != worker_pid or pre.get('addresses') != []
|
||||
or pre.get('supervisor_pid') != self.job['supervisor_pid']
|
||||
or not required.issubset({Path(p).resolve() for p in pre.get('exclusive_files', [])})
|
||||
or not 0 <= time.monotonic() - pre.get('monotonic', 0) <= 180
|
||||
or not all(_same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
|
||||
raise ValueError('POST_REPAIR_PRELAUNCH_PROOF_INVALID')
|
||||
for path in (self.grant['library'], self.grant['project'], self.grant['pcb']): require_local_fixed(path)
|
||||
_validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
|
||||
payload = {'action': 'post_repair_local_read_write', 'channels': ['win32_button_click'],
|
||||
'target': {'control_id': 6}, 'postcondition': 'window_gone',
|
||||
'desktop': self.job['desktop'], 'pid': target_pid}
|
||||
# Consume before messaging: failure/timeout cannot authorize another click.
|
||||
self.used = True; self.snapshot = snapshot; self.sent_at = time.monotonic()
|
||||
_write_json(Path(self.job['root'])/'post-repair-consent.json', {
|
||||
'nonce': self.grant['nonce'], 'consumed': True, 'target_pid': target_pid,
|
||||
'launcher_pid': launcher_pid, 'worker_pid': worker_pid, 'snapshot': snapshot.to_record()})
|
||||
result = perform(snapshot, payload, snapshot.phase)
|
||||
return DialogPollResult(activity=True, action_sent=bool(result.accepted_controls), snapshot=snapshot,
|
||||
error_code=result.error_code, detail=result.detail, accepted_controls=result.accepted_controls,
|
||||
action=payload['action'], channel=result.channel, rule_id='explicit-local-post-repair-consent',
|
||||
observed_snapshots=tuple(snapshots))
|
||||
except Exception as error:
|
||||
return DialogPollResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error),
|
||||
snapshot=snapshot, observed_snapshots=tuple(snapshots))
|
||||
|
||||
|
||||
def validate_action_window(snapshot, action):
|
||||
"""Final check on the agent's actual private desktop, immediately before Yes."""
|
||||
import win32gui, win32process
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
from .dialog_models import ControlSnapshot
|
||||
if (not exact_prompt(snapshot) or snapshot.pid != action.get('pid')
|
||||
or _current_desktop_name() != action.get('desktop')
|
||||
or not str(action.get('desktop', '')).startswith('CbbVerify_')
|
||||
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
|
||||
or win32gui.GetClassName(snapshot.hwnd) != snapshot.window_class
|
||||
or win32gui.GetWindowText(snapshot.hwnd) != snapshot.title or not win32gui.IsWindowVisible(snapshot.hwnd)):
|
||||
raise ValueError('POST_REPAIR_LIVE_WINDOW_MISMATCH')
|
||||
children = []
|
||||
win32gui.EnumChildWindows(snapshot.hwnd, lambda hwnd, _: children.append(int(hwnd)), None)
|
||||
live = tuple(ControlSnapshot(hwnd, win32gui.GetDlgCtrlID(hwnd) & 0xFFFF,
|
||||
win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd), enabled=bool(win32gui.IsWindowEnabled(hwnd)))
|
||||
for hwnd in children)
|
||||
from dataclasses import replace
|
||||
if not exact_prompt(replace(snapshot, controls=live)):
|
||||
raise ValueError('POST_REPAIR_LIVE_PROMPT_CHANGED')
|
||||
yes = next(c for c in live if c.control_id == 6)
|
||||
if yes.handle != next(c.handle for c in snapshot.controls if c.control_id == 6):
|
||||
raise ValueError('POST_REPAIR_BUTTON_CHANGED')
|
||||
@@ -572,6 +572,8 @@ class MainWindow(QWidget):
|
||||
f'{"(仅勾选项)" if self.selected_records() else ""}。未确认状态不等于损坏。\n'
|
||||
'无地址阻止时逐项校验;已有工程地址记录时先核对所有者和独占访问、完整备份,'
|
||||
'再由官方工具确认未占用并检查/修复。不会删除地址文件。\n'
|
||||
'仅本地固定磁盘:严格确认修复并重新独占检查后,可一次确认本次异常退出的读写访问提示。'
|
||||
'网络盘、UNC 或链接路径不自动确认该提示。\n'
|
||||
'共享符号库不支持自动修复。若原生工具恢复了旧备份,需人工核对版本;'
|
||||
'会话安全无法确认时停止队列。\n\n是否开始检查与修复?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
||||
if answer == QMessageBox.Yes:
|
||||
|
||||
@@ -64,6 +64,7 @@ class VerifyRequest:
|
||||
mapped_remote_root: str = ''
|
||||
auto_repair: bool = True
|
||||
maintenance: bool = False
|
||||
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -808,11 +809,19 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'desktop': 'CbbVerify_' + uuid4().hex[:12],
|
||||
'cancel_signal': str(root/'cancel-worker.signal'),
|
||||
'start_gate': str(root/'start-worker.signal')}
|
||||
consent = None
|
||||
if request.post_repair_proof is not None:
|
||||
from .post_repair_consent import PostRepairProof, ConsentController
|
||||
if not isinstance(request.post_repair_proof, PostRepairProof):
|
||||
return finish(VerifyResult('BLOCKED', stderr='POST_REPAIR_PROOF_REQUIRED', safe_to_continue=False))
|
||||
job['post_repair_consent'] = request.post_repair_proof.for_job(job)
|
||||
consent = ConsentController(request.post_repair_proof, job)
|
||||
job_path = root/'request.json'
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
events = root/'events.jsonl'
|
||||
offset = 0
|
||||
target_pid = None
|
||||
launcher_pid = None
|
||||
lm_pid = None
|
||||
verify_invoked = False
|
||||
invoke_returned = False
|
||||
@@ -875,6 +884,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
break
|
||||
timing.record(event)
|
||||
if event.get('pcb_pid'): target_pid = event['pcb_pid']
|
||||
if event.get('launcher_pid'): launcher_pid = event['launcher_pid']
|
||||
if event.get('lm_pid'): lm_pid = event['lm_pid']
|
||||
stage = event.get('stage')
|
||||
if stage == 'verify_invoke': verify_invoked = True
|
||||
@@ -926,6 +936,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
dialog_result = dialog_supervisor.poll()
|
||||
else:
|
||||
dialog_result = dialog_supervisor.poll()
|
||||
if (consent is not None and dialog_agent is not None
|
||||
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
|
||||
and dialog_result.snapshot is not None):
|
||||
consent_snapshot = dialog_result.snapshot
|
||||
if consent_snapshot.hwnd in {int(h) for h in process.desktop.EnumDesktopWindows()}:
|
||||
dialog_result = consent.handle(consent_snapshot, dialog_result.observed_snapshots,
|
||||
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
|
||||
companion_pids=tuple(process.companion_pids), perform=dialog_supervisor.backend.perform)
|
||||
# Normal progress stays in memory. Only actions/errors and the
|
||||
# last failure snapshots are persisted, not every elapsed tick.
|
||||
latest_snapshots = dialog_result.observed_snapshots
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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'
|
||||
Reference in new issue
Block a user