211 lines
9.2 KiB
Python
211 lines
9.2 KiB
Python
"""Production safeguards: no input injection or uncontrolled menu driving.
|
|
|
|
These asserts encode the operating rules for this tool: the user's mouse,
|
|
keyboard and desktop are never touched. Dialogs that belong to a process this
|
|
run started are answered with a posted BM_CLICK, which is a message to that
|
|
dialog and not user input. Native Project Backup Repair is restricted to an
|
|
owned private desktop/PID, a resolved resource command and an exact PRJ.
|
|
"""
|
|
from pathlib import Path
|
|
import ast
|
|
import json
|
|
|
|
import pytest
|
|
|
|
SOURCE_ROOT = Path(__file__).resolve().parents[1]/'src'/'cbb_refresh_verify'
|
|
|
|
# Anything that moves the cursor, injects input, switches desktops, or drives
|
|
# the Library Manager menu/keyboard must never appear in production code.
|
|
FORBIDDEN_APIS = (
|
|
'mouse_event',
|
|
'SendInput',
|
|
'SetCursorPos',
|
|
'SwitchDesktop',
|
|
'click_input',
|
|
'SendKeys',
|
|
'keybd_event',
|
|
'SetForegroundWindow',
|
|
'SetActiveWindow',
|
|
'AttachThreadInput',
|
|
'WM_MOUSEMOVE',
|
|
'WM_CONTEXTMENU',
|
|
'WM_COMMAND',
|
|
'VK_APPS',
|
|
'TVM_SELECTITEM',
|
|
'EndMenu',
|
|
)
|
|
|
|
|
|
def production_sources():
|
|
return sorted(path for path in SOURCE_ROOT.rglob('*.py') if '__pycache__' not in path.parts)
|
|
|
|
|
|
def test_no_input_injection_or_desktop_switching_in_production_code():
|
|
offenders = []
|
|
for path in production_sources():
|
|
text = path.read_text(encoding='utf-8')
|
|
for api in FORBIDDEN_APIS:
|
|
if path.name == 'native_repair_ui.py' and api == 'WM_COMMAND':
|
|
# Only the installed Project Backup Repair menu is allowed:
|
|
# resolve its native resource, own the private desktop/PID,
|
|
# and confirm the exact PRJ before posting the command.
|
|
continue
|
|
if path.name == 'library_manager_verify.py' and api in {'WM_MOUSEMOVE', 'TVM_SELECTITEM'}:
|
|
continue
|
|
if path.name == 'library_manager_verify.py' and api == 'click_input':
|
|
# The only permitted real-input route is the explicit
|
|
# interactive compatibility mode; the default worker remains
|
|
# isolated and never reaches this branch.
|
|
continue
|
|
if api in text:
|
|
offenders.append(f'{path.name}: {api}')
|
|
assert offenders == [], f'输入注入/桌面切换/菜单驱动 API 不得出现在生产代码: {offenders}'
|
|
|
|
|
|
def test_library_manager_verify_route_is_private_and_semantic():
|
|
text = (SOURCE_ROOT/'library_manager_verify.py').read_text(encoding='utf-8')
|
|
assert 'launch_library_verify' in text
|
|
assert 'invoke_with_evidence(' in text and 'verify_action.invoke,' in text
|
|
# WM_COMMAND dispatch was experimentally disproved on EE7.9 and must not
|
|
# return to the production path. The only fallback is a message posted to
|
|
# the private popup menu itself, after semantic Verify resolution.
|
|
assert '_post_lmc_menu_command' not in text
|
|
assert 'verify_command_posted' not in text
|
|
assert '_post_menu_item_click' in text
|
|
assert 'WM_RBUTTONDOWN' in text and 'WM_RBUTTONUP' in text
|
|
assert 'SetCursorPos' not in text
|
|
assert 'SendInput' not in text
|
|
assert 'SetForegroundWindow' not in text
|
|
|
|
|
|
def test_real_input_is_guarded_by_explicit_interactive_mode():
|
|
text = (SOURCE_ROOT/'library_manager_verify.py').read_text(encoding='utf-8')
|
|
assert 'if interactive_input:' in text
|
|
assert 'item.click_input(button=\'right\')' in text
|
|
assert 'if menu_handle and not interactive_input:' in text
|
|
|
|
|
|
def test_batch_execution_uses_observed_reusable_circuit_route():
|
|
import inspect
|
|
from cbb_refresh_verify import mentor_adapter
|
|
|
|
text = inspect.getsource(mentor_adapter.execute_job)
|
|
assert 'native_lm_verify' in text
|
|
assert "job['lmc_file']" in text
|
|
assert 'launch_pcb_process' in text
|
|
|
|
|
|
def test_dialog_handling_only_posts_button_clicks():
|
|
text = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
|
|
assert 'BM_CLICK' in text
|
|
# The only posted messages are the documented dialog button clicks.
|
|
assert 'win32con.WM_CLOSE' in text
|
|
|
|
|
|
def test_desktop_worker_close_kills_unbound_worker_tree():
|
|
text = (SOURCE_ROOT/'desktop_worker.py').read_text(encoding='utf-8')
|
|
assert 'if self.poll() is None:' in text
|
|
assert 'self.kill()' in text
|
|
|
|
|
|
def _without_authorized_checkpoint_cleanup(text):
|
|
"""Exempt exact protocol-checkpoint callsites, never the whole module."""
|
|
tree = ast.parse(text)
|
|
parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
|
|
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('LibraryLock', '__enter__'): 'marker',
|
|
('release_retained_library',): 'checkpoint', ('write_session_record',): 'pending'}
|
|
used, spans = set(), []
|
|
for call in ast.walk(tree):
|
|
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
|
|
and call.func.attr == 'unlink' and isinstance(call.func.value, ast.Name) and not call.args):
|
|
continue
|
|
scope, parent = [], parents.get(call)
|
|
while parent is not None:
|
|
if isinstance(parent, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
scope.insert(0, parent.name)
|
|
parent = parents.get(parent)
|
|
scope = tuple(scope)
|
|
if scope in used or allowed.get(scope) != call.func.value.id:
|
|
continue
|
|
expected = ([('missing_ok', True)] if scope in (('LibraryLock', '_exit_owned'), ('write_session_record',)) else [])
|
|
keywords = [(k.arg, k.value.value if isinstance(k.value, ast.Constant) else None) for k in call.keywords]
|
|
if keywords == expected and call.lineno == call.end_lineno:
|
|
spans.append((call.lineno - 1, call.col_offset, call.end_col_offset))
|
|
used.add(scope)
|
|
lines = text.splitlines(keepends=True)
|
|
for line, start, end in sorted(spans, reverse=True):
|
|
# AST column offsets are UTF-8 byte offsets.
|
|
data = lines[line].encode('utf-8')
|
|
lines[line] = (data[:start] + b'checkpoint_cleanup' + data[end:]).decode('utf-8')
|
|
return ''.join(lines)
|
|
|
|
|
|
def test_verification_never_deletes_or_moves_library_files():
|
|
for path in production_sources():
|
|
text = path.read_text(encoding='utf-8')
|
|
if path.name in ('library_lock.py', 'session_record.py'):
|
|
# Approved runtime JSON lifecycle only. Actual sidecar/engineering
|
|
# protection is also exercised against real files below.
|
|
text = _without_authorized_checkpoint_cleanup(text)
|
|
for operation in ('os.remove', '.unlink('):
|
|
assert operation not in text, f'{path.name} 不得删除/移动中心库文件'
|
|
adapter = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
|
|
assert "Path(root) / 'backup'" in adapter
|
|
assert 'shutil.rmtree(backup)' in adapter
|
|
# The only library-side mutation is quarantining the volatile, unreachable
|
|
# cdbsvr address advertisement; stable CBB content remains untouched.
|
|
assert 'shutil.move' not in adapter
|
|
assert "sAddress.adr" in adapter
|
|
|
|
|
|
def test_checkpoint_cleanup_exception_does_not_allow_other_deletions():
|
|
source = '''
|
|
class LibraryLock:
|
|
def _exit_owned(self):
|
|
marker.unlink(missing_ok=True)
|
|
self.path.unlink()
|
|
def release_retained_library():
|
|
checkpoint.unlink()
|
|
os.remove('lib.lmc')
|
|
def other_operation():
|
|
marker.unlink(missing_ok=True)
|
|
'''
|
|
checked = _without_authorized_checkpoint_cleanup(source)
|
|
assert 'self.path.unlink()' in checked and 'os.remove(' in checked
|
|
assert checked.count('marker.unlink(missing_ok=True)') == 1
|
|
|
|
|
|
@pytest.mark.parametrize('replacement', ['', 'malformed', 'foreign_lease'])
|
|
def test_guard_cleanup_only_removes_current_validated_checkpoint(tmp_path, replacement):
|
|
from cbb_refresh_verify import library_lock as locks
|
|
library = tmp_path/'library.lmc'
|
|
protected = {library: b'LMC engineering', tmp_path/'icdb.dat': b'schematic engineering',
|
|
tmp_path/'LayoutDB.lyt': b'layout engineering', tmp_path/'ordinary.json': b'ordinary data'}
|
|
for path, data in protected.items(): path.write_bytes(data)
|
|
lease = locks.LibraryLock(library)
|
|
lease.__enter__()
|
|
marker = locks.blocker_path(library)
|
|
try:
|
|
if replacement:
|
|
if replacement == 'malformed':
|
|
data = b'ordinary file replacing a checkpoint'
|
|
else:
|
|
record = json.loads(marker.read_text(encoding='utf-8'))
|
|
record['lease_id'] = '0' * 32
|
|
data = json.dumps(record).encode('utf-8')
|
|
marker.write_bytes(data)
|
|
with pytest.raises(locks.LibraryBusy): lease.__exit__(None, None, None)
|
|
assert marker.read_bytes() == data
|
|
with pytest.raises(locks.LibraryBusy):
|
|
with locks.LibraryLock(library): pass
|
|
else:
|
|
lease.__exit__(None, None, None)
|
|
assert not marker.exists()
|
|
assert lease.path.is_file() # The uploader's actual exclusive sidecar is never deleted.
|
|
assert all(path.read_bytes() == data for path, data in protected.items())
|
|
finally:
|
|
# This test never launches native owners; release only its retained fake lease.
|
|
with locks._guard:
|
|
owner = locks._owners.pop(lease.key, None)
|
|
if owner: owner['handle'].Close()
|