diff --git a/tests/test_safety.py b/tests/test_safety.py index 2aa7853..2392f03 100644 --- a/tests/test_safety.py +++ b/tests/test_safety.py @@ -7,6 +7,10 @@ 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' @@ -104,9 +108,44 @@ def test_desktop_worker_close_kills_unbound_worker_tree(): 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__'): 'marker', ('release_retained_library',): 'checkpoint'} + 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 = ([] if scope == ('release_retained_library',) else [('missing_ok', True)]) + 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 == SOURCE_ROOT/'library_lock.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') @@ -116,3 +155,55 @@ def test_verification_never_deletes_or_moves_library_files(): # 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__(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()