import json from pathlib import Path from types import SimpleNamespace import pytest def test_installed_binary_mismatch_disables_removal(tmp_path): from cbb_refresh_verify.native_management import NativeManagementAdapter adapter = NativeManagementAdapter(mentor_home=tmp_path) caps = adapter.capabilities() assert not caps['remove'].supported and 'CleanWGLib' in caps['remove'].reason assert not caps['add'].supported and not caps['update'].supported def test_public_add_cannot_bypass_disabled_capability(tmp_path, monkeypatch): import cbb_refresh_verify.native_management as native from cbb_refresh_verify.management import ManagementRequest adapter = native.NativeManagementAdapter(mentor_home=tmp_path) monkeypatch.setattr(adapter, '_worker', lambda *a: pytest.fail('public disabled Add launched worker')) monkeypatch.setattr(native, 'engineering_identity', lambda *a: pytest.fail('public disabled Add accessed source')) result = adapter.add(ManagementRequest('add', tmp_path/'arbitrary.lmc', 'Block', source=tmp_path/'source/original.prj'), tmp_path/'add') assert not result.success and result.safe_to_continue def test_empty_fixture_creation_uses_existing_new_library_guard_route(tmp_path, monkeypatch): import cbb_refresh_verify.native_management as native seen = [] monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '') monkeypatch.setattr(native.NativeManagementAdapter, '_worker', lambda adapter, job, evidence: (seen.append((job, evidence)) or {'success': True, 'safe_to_continue': True, 'entries': []})) root = tmp_path/'fresh' result = native.create_owned_fixture(root) assert result['success'] and result['entries'] == [] assert seen[0][0]['operation'] == 'probe_create' assert Path(seen[0][0]['library']) == root/'native-add/fixture/mentor_lib.lmc' assert seen[0][0]['probe_token'] == result['probe_token'] existing = tmp_path/'existing'; existing.mkdir() with pytest.raises(ValueError): native.create_owned_fixture(existing) assert len(seen) == 1 def test_unprepared_add_rejected_before_native_activation(tmp_path, monkeypatch): import cbb_refresh_verify.native_management as native import win32com.client monkeypatch.setattr(win32com.client, 'DispatchEx', lambda *a: pytest.fail('unprepared native activation')) with pytest.raises(ValueError): native._catalog_com({'operation': 'add', 'library': str(tmp_path/'arbitrary.lmc')}, tmp_path/'add') def test_removed_marker_cannot_cross_carriage_return_record(): from cbb_refresh_verify.native_management import removal_output_ok assert not removal_output_ok(0, "# Note: Removed unrelated\rrecord 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical') @pytest.mark.parametrize('invalid', ['', 'nonce', 'lease', 'source', 'backup', 'expired', 'token']) def test_fixture_add_authority_requires_live_lease_and_fresh_staging(tmp_path, monkeypatch, invalid): import cbb_refresh_verify.native_management as native from cbb_refresh_verify.management import ManagementRequest from cbb_refresh_verify.library_lock import LibraryLock library = tmp_path/'native-add/fixture/mentor_lib.lmc' library.parent.mkdir(parents=True); library.write_bytes(b'owned fixture') source = tmp_path/'original/Source.prj' source.parent.mkdir(); source.write_bytes(b'original source') (tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8') adapter = native.NativeManagementAdapter(mentor_home=tmp_path) monkeypatch.setattr(adapter, 'route_capabilities', lambda: {'add': native.Capability(True, 'ready')}) monkeypatch.setattr(native, 'engineering_identity', lambda _: {'source': 'bytes'}) def launch(job, root): staged = Path(job['source']) assert staged == root/'source/Source.prj' and staged != source prepared_path = root/'add-prepared.json' prepared = json.loads(prepared_path.read_text(encoding='utf-8')) if invalid == 'nonce': job['transaction_nonce'] = 'foreign' if invalid == 'token': job['probe_token'] = 'foreign' if invalid == 'lease': prepared['lease_id'] = 'foreign' if invalid == 'source': job['source'] = str(source) if invalid == 'backup': (root/'library-before/mentor_lib.lmc').write_bytes(b'changed') if invalid == 'expired': import cbb_refresh_verify.library_lock as locks monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False) prepared_path.write_text(json.dumps(prepared), encoding='utf-8') if invalid: with pytest.raises(ValueError): native.validate_owned_fixture_add(job, root) else: assert native.validate_owned_fixture_add(job, root) == staged assert source.read_bytes() == b'original source' return {'success': not invalid, 'safe_to_continue': True, 'identity_matches': not invalid} monkeypatch.setattr(adapter, '_launch_worker', launch) with LibraryLock(library): result = adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source), tmp_path/'shared-add', probe_token='owned') assert result.success is (not invalid) def test_fixture_metadata_without_current_thread_lease_cannot_stage_source(tmp_path): import cbb_refresh_verify.native_management as native library = tmp_path/'native-add/fixture/mentor_lib.lmc' library.parent.mkdir(parents=True); library.touch() (tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8') root = tmp_path/'add'; root.mkdir() with pytest.raises(ValueError, match='current thread'): native.prepare_owned_fixture_add({'library': str(library), 'probe_token': 'owned'}, root) assert not (root/'source').exists() @pytest.mark.parametrize('outcome', ['unsafe', 'exception', 'safe']) def test_owned_fixture_retains_default_caller_lease_until_native_release(tmp_path, monkeypatch, outcome): import cbb_refresh_verify.native_management as native from cbb_refresh_verify.management import ManagementRequest from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy, blocker_path, _owners, _guard library = tmp_path/'native-add/fixture/mentor_lib.lmc' library.parent.mkdir(parents=True); library.write_bytes(b'fixture') source = tmp_path/'original/Source.prj'; source.parent.mkdir(); source.write_bytes(b'source') (tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8') adapter = native.NativeManagementAdapter(mentor_home=tmp_path) monkeypatch.setattr(adapter, 'route_capabilities', lambda: {'add': native.Capability(True, 'ready')}) monkeypatch.setattr(native, 'engineering_identity', lambda _: {'source': 'bytes'}) def launch(*args): if outcome == 'exception': raise OSError('worker result lost after dispatch') return {'success': outcome == 'safe', 'safe_to_continue': outcome == 'safe'} monkeypatch.setattr(adapter, '_launch_worker', launch) lease = LibraryLock(library) try: with lease: if outcome == 'exception': with pytest.raises(OSError, match='after dispatch'): adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source), tmp_path/'add', probe_token='owned') else: adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source), tmp_path/'add', probe_token='owned') assert blocker_path(library).exists() is (outcome != 'safe') if outcome != 'safe': with pytest.raises(LibraryBusy): with LibraryLock(library): pass import win32file, win32con, pywintypes with pytest.raises(pywintypes.error): win32file.CreateFile(str(lease.path), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None) else: with LibraryLock(library): pass finally: # Only the file-only fake worker above ran; release its test lease. with _guard: owner = _owners.pop(lease.key, None) if owner: owner['handle'].Close() blocker_path(library).unlink(missing_ok=True) def test_fixture_nested_inside_source_tree_rejected_before_staging(tmp_path): import cbb_refresh_verify.native_management as native from cbb_refresh_verify.library_lock import LibraryLock library = tmp_path/'native-add/fixture/mentor_lib.lmc' library.parent.mkdir(parents=True); library.write_bytes(b'fixture') source = tmp_path/'native-add/Source.prj'; source.write_bytes(b'original source') (tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8') root = tmp_path/'add'; root.mkdir() with LibraryLock(library): with pytest.raises(ValueError, match='independent'): native.prepare_owned_fixture_add({'library': str(library), 'source': str(source), 'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {}, 'probe_token': 'owned'}, root) assert source.read_bytes() == b'original source' and library.read_bytes() == b'fixture' assert not (root/'source').exists() def test_add_route_readiness_is_separate_from_conservative_capability_gate(tmp_path, monkeypatch): import hashlib import cbb_refresh_verify.native_management as native proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()} monkeypatch.setattr(native, '_BINARY_PROOF', proof) path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified') adapter = native.NativeManagementAdapter(mentor_home=tmp_path) assert adapter.route_capabilities()['add'].supported assert not adapter.capabilities()['add'].supported assert 'icdb2ascii' in adapter.capabilities()['add'].reason @pytest.mark.parametrize('bad', [None, 'CleanWGLib.exe', 'LibraryManager.exe', 'LMCDLL70.dll', 'LMCDocAddin70.dll', 'icdb2ascii.exe', 'icdb2csv.exe', 'edifExporter.exe']) def test_public_crud_requires_pinned_core_and_every_identity_exporter(tmp_path, monkeypatch, bad): import hashlib import cbb_refresh_verify.native_management as native import cbb_refresh_verify.native_engineering_identity as identity core = {relative: hashlib.sha256(Path(relative).name.encode()).hexdigest() for relative in native._BINARY_PROOF} exporters = {name: hashlib.sha256(name.encode()).hexdigest() for name in identity.EXPORTER_PROOF} monkeypatch.setattr(native, '_BINARY_PROOF', core) monkeypatch.setattr(identity, 'EXPORTER_PROOF', exporters) for relative in core: path = tmp_path/relative; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(path.name.encode()) for name in exporters: path = tmp_path/('wv/win32/bin' if name == 'edifExporter.exe' else 'iCDB/win32/bin')/name path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(name.encode()) if bad: next(tmp_path.rglob(bad)).write_bytes(b'changed binary') caps = native.NativeManagementAdapter(mentor_home=tmp_path).capabilities() assert caps['add'].supported is (bad is None) assert caps['update'].supported is (bad is None) if bad in exporters: assert caps['remove'].supported @pytest.mark.parametrize('operation', ['add', 'update', 'remove']) @pytest.mark.parametrize('flow,partition', [(2, 'Logical-Physical'), (1, 'Unsupported')]) def test_public_crud_scope_refuses_unproven_flow_or_partition(tmp_path, operation, flow, partition): from cbb_refresh_verify.management import ManagementRequest, Catalog from cbb_refresh_verify.native_management import NativeManagementAdapter request = ManagementRequest(operation, tmp_path/'lib.lmc', 'Block', partition=partition) with pytest.raises(ValueError): NativeManagementAdapter(mentor_home=tmp_path).preflight(request, Catalog(request.library, flow, ())) def test_owned_fixture_add_passes_existing_library_and_source_to_worker(tmp_path, monkeypatch): from cbb_refresh_verify.management import ManagementRequest import cbb_refresh_verify.native_management as native source = tmp_path/'source.prj'; source.write_bytes(b'source') library = tmp_path/'library.lmc'; library.write_bytes(b'library') seen = {} adapter = native.NativeManagementAdapter(mentor_home=tmp_path) monkeypatch.setattr(adapter, 'route_capabilities', lambda: { 'add': native.Capability(True, 'route ready')}) monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)}) def worker(job, evidence): seen.update(job=job, evidence=evidence) return {'success': True, 'safe_to_continue': True, 'identity_matches': True, 'detail': 'native add accepted'} monkeypatch.setattr(adapter, '_worker', worker) request = ManagementRequest('add', library, 'Block', source=source, mapped_drive='S:', mapped_remote_root=r'\\server\share', timeout_seconds=23) result = adapter.add_owned_fixture(request, tmp_path/'evidence', probe_token='owned') assert result.success and result.safe_to_continue and result.identity_matches is True assert seen['job'] == { 'operation': 'add', 'library': str(library), 'source': str(source), 'name': 'Block', 'partition': 'Logical-Physical', 'top_level_block': '', 'mapped_drive': 'S:', 'mapped_remote_root': r'\\server\share', 'timeout_seconds': 23, 'source_identity': {'source': str(source)}, 'probe_token': 'owned', } def test_native_add_identity_mismatch_is_native_success_with_evidence(tmp_path, monkeypatch): from cbb_refresh_verify.management import ManagementRequest import cbb_refresh_verify.native_management as native source = tmp_path/'source.prj'; source.write_bytes(b'source') library = tmp_path/'library.lmc'; library.write_bytes(b'library') adapter = native.NativeManagementAdapter(mentor_home=tmp_path) monkeypatch.setattr(adapter, 'route_capabilities', lambda: { 'add': native.Capability(True, 'route ready')}) monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)}) monkeypatch.setattr(adapter, '_worker', lambda job, evidence: { 'success': True, 'safe_to_continue': True, 'identity_matches': False, 'detail': 'engineering identity readback mismatch', }) original = source.read_bytes() result = adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source), tmp_path/'evidence', probe_token='owned') assert result.success and result.identity_matches is False assert 'identity' in result.detail assert result.evidence_path == tmp_path/'evidence' assert source.read_bytes() == original @pytest.mark.parametrize('name', ['A\tB', 'A\nB', '../A', '中文']) def test_delete_record_rejects_ambiguous_encoding_or_injection(name): from cbb_refresh_verify.native_management import removal_input with pytest.raises(ValueError): removal_input(name, 'Logical-Physical') def test_delete_record_is_exact_shipped_tcl_contract(): from cbb_refresh_verify.native_management import removal_input, removal_output_ok assert removal_input('Block', 'Logical-Physical') == b'REUSE_BLOCK\tLogical-Physical\tBlock\n' assert not removal_output_ok(0, '', 'Block', 'Logical-Physical') assert not removal_output_ok(0, "# Warning: Unable to remove REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical') assert removal_output_ok(0, "# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical') def test_upgrade_dialog_is_refused_and_only_cancel_is_allowed(): from cbb_refresh_verify.native_management import catalog_dialog_action assert catalog_dialog_action('Library Manager', 'This Central Library must be updated before it can be opened in Library Manager. Select OK to continue.') == 'cancel' assert catalog_dialog_action('Select flow type', '') == 'cancel' assert catalog_dialog_action('Library Manager', 'Would you like to save?') == 'observe' def test_catalog_never_falls_back_to_folder_list(tmp_path): from cbb_refresh_verify.native_management import NativeManagementAdapter library = tmp_path/'lib.lmc'; library.touch() (tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True) adapter = NativeManagementAdapter() adapter._worker = lambda *_: {'success': False, 'safe_to_continue': True, 'detail': 'upgrade refused'} with pytest.raises(RuntimeError, match='upgrade refused'): adapter.catalog(library, tmp_path/'evidence') def test_private_worker_timeout_retains_native_and_never_kills(tmp_path, monkeypatch): import cbb_refresh_verify.native_management as native monkeypatch.setattr(native, '_retained_workers', []) from cbb_refresh_verify.native_management import NativeManagementAdapter class Running: def __init__(self, *a): pass def poll(self): return None def close(self): pytest.fail('closing live DesktopWorker kills automation') def kill(self): pytest.fail('must preserve native owner') adapter = NativeManagementAdapter(worker_factory=Running, timeout_seconds=0) result = adapter._worker({'operation': 'catalog', 'library': str(tmp_path/'lib.lmc')}, tmp_path/'out') assert result['safe_to_continue'] is False assert 'TIMEOUT' in result['detail'] def test_hidden_worker_and_probe_dispatch_before_qt(monkeypatch, tmp_path): import cbb_refresh_verify.native_management as native from cbb_refresh_verify.application import main seen = [] monkeypatch.setattr(native, 'management_worker_main', lambda p: (seen.append(p) or 17)) assert main(['--management-worker', str(tmp_path/'job.json')]) == 17 assert seen == [tmp_path/'job.json'] def test_probe_cannot_use_existing_fixture_or_mutate_source(tmp_path): from cbb_refresh_verify.native_management import run_isolated_probe existing = tmp_path/'existing' existing.mkdir() with pytest.raises(ValueError, match='new|新'): run_isolated_probe(tmp_path/'source.prj', existing, 'Block') def test_probe_requires_owned_new_native_library_path(tmp_path): import os from cbb_refresh_verify.native_management import prepare_probe_library from cbb_refresh_verify.library_lock import LibraryLock outside = tmp_path/'production.lmc'; outside.write_bytes(b'unchanged') root = tmp_path/'worker'; root.mkdir() with pytest.raises(ValueError): prepare_probe_library({'library': str(outside)}, root) assert outside.read_bytes() == b'unchanged' owned = root/'fixture/mentor_lib.lmc' owned.parent.mkdir() job = {'library': str(owned), 'probe_token': 'test-token', 'supervisor_pid': os.getpid()} (root/'probe-prepared.json').write_text(json.dumps({'library': str(owned), 'token': 'test-token', 'supervisor_pid': os.getpid()}), encoding='utf-8') with LibraryLock(owned): assert prepare_probe_library(job, root) == owned owned.write_bytes(b'first creation') with pytest.raises(ValueError): prepare_probe_library(job, root) @pytest.mark.parametrize('records', [[], [('Actual', 'Logical-Physical')]]) @pytest.mark.parametrize('mapped', [False, True]) @pytest.mark.parametrize('flow', [1, 2]) def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records, mapped, flow): import cbb_refresh_verify.native_management as native import cbb_refresh_verify.mentor_adapter as mentor import win32com.client library_path = tmp_path/'lib.lmc'; library_path.touch() if mapped: original_resolve = Path.resolve def resolve(path, *a, **k): return tmp_path/'canonical/lib.lmc' if path == library_path else original_resolve(path, *a, **k) monkeypatch.setattr(Path, 'resolve', resolve) (tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True) class Collection: def __init__(self, items): self.items = items; self.Count = len(items) def Item(self, index): return self.items[index - 1] items = Collection([SimpleNamespace(Name=name, PartitionName=partition) for name, partition in records]) class Library: FullName = str(library_path) FlowType = flow def Partitions(self, kind): assert kind == 7 return Collection([items]) def Close(self): pass state = {'running': False} class App: def OpenLibrary(self, path): assert path == str(library_path) return Library() def Quit(self): state['running'] = False def dispatch(_): state['running'] = True; return App() monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch) monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test')) monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else []) monkeypatch.setattr(native, '_wait_native_exit', lambda _: not state['running']) result = native._catalog_native({'operation': 'catalog', 'library': str(library_path), 'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path)}, tmp_path) assert result['success'] and result['safe_to_continue'] assert [(entry['name'], entry['partition']) for entry in result['entries']] == records assert result['flow'] == flow def test_production_caps_require_all_validated_binary_hashes(tmp_path, monkeypatch): import hashlib import cbb_refresh_verify.native_management as native proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()} monkeypatch.setattr(native, '_BINARY_PROOF', proof) path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified') adapter = native.NativeManagementAdapter(mentor_home=tmp_path) assert adapter.capabilities()['remove'].supported assert not adapter.capabilities()['add'].supported path.write_bytes(b'different') assert not adapter.capabilities()['remove'].supported def test_probe_readd_requires_creation_token_and_fixed_owned_library(tmp_path): from cbb_refresh_verify.native_management import validate_probe_readd root = tmp_path/'native-readd'; root.mkdir() library = tmp_path/'native-add/fixture/mentor_lib.lmc' library.parent.mkdir(parents=True); library.touch() job = {'library': str(library), 'probe_token': 'owned-token'} with pytest.raises(ValueError): validate_probe_readd(job, root) (tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'other'}), encoding='utf-8') with pytest.raises(ValueError): validate_probe_readd(job, root) (tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned-token'}), encoding='utf-8') assert validate_probe_readd(job, root) == library outside = tmp_path/'production.lmc'; outside.touch() with pytest.raises(ValueError): validate_probe_readd({**job, 'library': str(outside)}, root) def test_com_failure_without_owner_identity_cannot_claim_release(tmp_path, monkeypatch): import cbb_refresh_verify.native_management as native monkeypatch.setattr(native, '_catalog_com', lambda *a: {'success': False, 'safe_to_continue': False, 'native_pids': [], 'detail': 'COM startup ambiguous'}) assert native._catalog_native({}, tmp_path)['safe_to_continue'] is False @pytest.mark.parametrize('registered', [True, False]) def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered): import cbb_refresh_verify.native_management as native import cbb_refresh_verify.mentor_adapter as mentor import win32com.client library_path = tmp_path/'lib.lmc'; library_path.touch() events = [] class Collection: def __init__(self, items): self.items = items; self.Count = len(items) def Item(self, index): return self.items[index - 1] class Library: FullName = str(library_path) FlowType = 1 def Partitions(self, kind): events.append('catalog') return Collection([Collection([SimpleNamespace(Name='Block', PartitionName='Logical-Physical')] if registered else [])]) def Close(self): events.append('close') state = {'running': False} class App: def OpenLibrary(self, path): assert path == str(library_path) events.append('open') return Library() def Quit(self): state['running'] = False def dispatch(_): state['running'] = True; return App() monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch) monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test')) monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else []) monkeypatch.setattr(native, '_probe_add_dialog', lambda *a, **k: events.append('add')) monkeypatch.setattr(native, 'validate_owned_fixture_add', lambda *a: None) result = native._catalog_com({'operation': 'add', 'library': str(library_path), 'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {'expected': 'bytes'}}, tmp_path) assert events == ['open', 'add', 'close', 'open', 'catalog', 'close'] assert result['success'] is registered assert result['identity_matches'] is False assert ('engineering identity' if registered else 'exact name and partition') in result['detail']