From d40fa3a75047ebacdb16442b72e44ecf9f31a641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Tue, 17 Nov 2026 01:22:57 +0800 Subject: [PATCH] fix: reject native source renames before management writes --- src/cbb_refresh_verify/management.py | 2 + src/cbb_refresh_verify/native_management.py | 35 ++++++++++--- .../ui/management_dialog.py | 5 +- tests/test_issue15_native_source_name.py | 49 +++++++++++++++++++ tests/test_management_native_transaction.py | 4 +- tests/test_native_add_failures.py | 15 ++++-- tests/test_native_management.py | 12 ++--- 7 files changed, 102 insertions(+), 20 deletions(-) create mode 100644 tests/test_issue15_native_source_name.py diff --git a/src/cbb_refresh_verify/management.py b/src/cbb_refresh_verify/management.py index b486a61..9e7ecea 100644 --- a/src/cbb_refresh_verify/management.py +++ b/src/cbb_refresh_verify/management.py @@ -289,6 +289,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro if request.operation in ('add', 'update'): if request.source is None: raise ValueError('新增/更新需要完整来源工程。') + if hasattr(adapter, 'validate_source'): + adapter.validate_source(request) source, pcb, top = source_project(request.source, request.top_level_block) if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent) or evidence.is_relative_to(source.parent) diff --git a/src/cbb_refresh_verify/native_management.py b/src/cbb_refresh_verify/native_management.py index 3d64011..d31a8bc 100644 --- a/src/cbb_refresh_verify/native_management.py +++ b/src/cbb_refresh_verify/native_management.py @@ -308,12 +308,29 @@ class NativeManagementAdapter: removal_input(request.name, request.partition) if request.partition != 'Logical-Physical' or catalog.flow != 1: raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。') + self.validate_source(request) + + def validate_source(self, request): + if request.operation not in ('add', 'update'): + return + if request.source is None: + raise ValueError('请选择完整来源工程。') + source = Path(request.source).resolve(strict=True) + if not source.is_file() or source.suffix.casefold() != '.prj': + raise ValueError('请选择完整来源工程的 PRJ 文件。') + if source.stem.casefold() != request.name.casefold(): + raise ValueError(f'SOURCE_NAME_MISMATCH: 来源工程名 {source.stem} 与目标 {request.name} 不一致;' + '当前版本不支持改名,请重新选择同名 PRJ。') def add(self, request, evidence): # Route readiness never grants production mutation authority. capability = self.capabilities()['add'] if not capability.supported: return NativeOutcome(False, True, capability.reason, evidence_path=Path(evidence)) + try: + self.validate_source(request) + except (OSError, ValueError) as error: + return NativeOutcome(False, True, str(error), evidence_path=Path(evidence)) return self._add_transaction(request, Path(evidence)) def prepare_add_transaction(self, request, root, *, original_source): @@ -323,6 +340,7 @@ class NativeManagementAdapter: from .management import source_project from .backup_recovery import _align_library try: + self.validate_source(request) if not self.capabilities()['add'].supported: raise ValueError(self.capabilities()['add'].reason) validate_native_copy_paths(request.source, request.library, request.name) @@ -450,6 +468,7 @@ class NativeManagementAdapter: return NativeOutcome(False, True, 'Native Add requires an existing staged PRJ source project.', evidence_path=evidence) try: + self.validate_source(request) source_identity = engineering_identity(source) except (ValueError, OSError) as error: return NativeOutcome(False, True, f'Unable to read source engineering identity: {error}', @@ -694,11 +713,11 @@ def _dispatch_diagnostics(root, stage, app, library, *, paths=None): stream.write(json.dumps(record, ensure_ascii=False, default=str) + '\n') -def _set_probe_field(hwnd, control_id, expected, root): - """Set/read a remote Edit with a one-second total message budget.""" +def _set_probe_field(hwnd, control_id, expected, root, *, read_only=False): + """Set/read or revalidate a remote Edit with a one-second total message budget.""" from ctypes import wintypes record = {'control_id': control_id, 'hwnd': int(hwnd), 'expected': expected, - 'actual': None, 'matched': False} + 'actual': None, 'matched': False, 'read_only': read_only} deadline = time.monotonic() + 1.0 try: user32 = ctypes.WinDLL('user32', use_last_error=True) @@ -715,9 +734,10 @@ def _set_probe_field(hwnd, control_id, expected, root): remaining, ctypes.byref(returned)): raise TimeoutError(f'原生字段消息超时或失败:{control_id}, Windows={ctypes.get_last_error()}') return returned.value - text = ctypes.create_unicode_buffer(expected) - if not message(0x000C, 0, text): # WM_SETTEXT - raise RuntimeError(f'原生字段拒绝写入:{control_id}') + if not read_only: + text = ctypes.create_unicode_buffer(expected) + if not message(0x000C, 0, text): # WM_SETTEXT + raise RuntimeError(f'原生字段拒绝写入:{control_id}') buffer = ctypes.create_unicode_buffer(32768) copied = message(0x000D, len(buffer), buffer) # WM_GETTEXT, remote Edit marshalled by Windows. record['actual'] = buffer.value @@ -851,6 +871,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None) if not hwnd or win32gui.GetClassName(hwnd) != 'Edit': raise RuntimeError(f'原生新增字段身份不匹配:{control}') _set_probe_field(hwnd, control, value, root) + # Changing source/top fields can make Mentor derive a different name. + for control, value in fields.items(): + _set_probe_field(win32gui.GetDlgItem(dialog, control), control, value, root, read_only=True) _write_json(root/'submitted-fields.json', fields) ok = win32gui.GetDlgItem(dialog, 1083) if not ok: diff --git a/src/cbb_refresh_verify/ui/management_dialog.py b/src/cbb_refresh_verify/ui/management_dialog.py index 09ed6e7..f129a27 100644 --- a/src/cbb_refresh_verify/ui/management_dialog.py +++ b/src/cbb_refresh_verify/ui/management_dialog.py @@ -156,10 +156,13 @@ class ManagementDialog(QDialog): try: if not requests: raise ValueError('请先选择来源工程。') + if hasattr(self.adapter, 'validate_source'): + for request in requests: + self.adapter.validate_source(request) # Per-item input errors belong in batch results, so valid rows still run. if len({(r.partition.casefold(), r.name.casefold()) for r in requests}) != len(requests): raise ValueError('批次包含重复目标名称。') - except ValueError as error: + except (OSError, ValueError) as error: self.status_label.setText(str(error)); return preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests) description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update' diff --git a/tests/test_issue15_native_source_name.py b/tests/test_issue15_native_source_name.py new file mode 100644 index 0000000..b899741 --- /dev/null +++ b/tests/test_issue15_native_source_name.py @@ -0,0 +1,49 @@ +"""EE7.9 imports by source PRJ name; reject rename before any native mutation.""" +from dataclasses import replace + +import pytest + +from cbb_refresh_verify.management import ManagementRequest, run_management +from cbb_refresh_verify.native_management import NativeManagementAdapter +from test_management import project + + +@pytest.mark.parametrize('operation', ['add', 'update']) +def test_real_adapter_rejects_mismatched_source_before_native_catalog_or_remove(tmp_path, monkeypatch, operation): + library=tmp_path/'library/mentor.lmc';library.parent.mkdir();library.write_bytes(b'unchanged library') + target=project(library.parent/'ReusableBlocksLP/Block/Work','Block',b'unchanged target') + source=project(tmp_path/'source','Other') + adapter=NativeManagementAdapter() + monkeypatch.setattr(adapter,'_binary_capability',lambda:'') + calls=[] + monkeypatch.setattr(adapter,'_worker',lambda *args:calls.append(args) or pytest.fail('native boundary reached')) + request=ManagementRequest(operation,library,'Block',source=source,evidence_dir=tmp_path/'evidence') + result=run_management(request,adapter=adapter,idle_check=lambda *_:None) + assert result.safe_to_continue and 'SOURCE_NAME_MISMATCH' in result.detail + assert calls == [] + assert library.read_bytes()==b'unchanged library' + assert (target.parent/'database/icdb.dat').read_bytes()==b'unchanged target' + + +def test_source_name_check_uses_windows_case_insensitive_identity(tmp_path): + source=project(tmp_path/'source','BLOCK') + request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=source) + NativeManagementAdapter().validate_source(request) + + +def test_management_preview_reports_mismatch_and_allows_rechoose(qtbot,tmp_path,monkeypatch): + from PySide6.QtWidgets import QMessageBox + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + from cbb_refresh_verify.ui import timed_prompt + wrong=project(tmp_path/'wrong','Other');right=project(tmp_path/'right','Block') + request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=wrong) + dialog=ManagementDialog([request],adapter=NativeManagementAdapter()) + qtbot.addWidget(dialog);dialog.show() + questions=[] + monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:questions.append(a) or QMessageBox.No) + dialog.execute_button.click() + assert 'SOURCE_NAME_MISMATCH' in dialog.status_label.text() + assert not questions and dialog.execute_button.isEnabled() + dialog.table.item(0,2).setText(str(right)) + dialog.execute_button.click() + assert len(questions)==1 and not dialog.busy diff --git a/tests/test_management_native_transaction.py b/tests/test_management_native_transaction.py index f3dac02..2e80dbe 100644 --- a/tests/test_management_native_transaction.py +++ b/tests/test_management_native_transaction.py @@ -18,7 +18,7 @@ def transaction(tmp_path, monkeypatch): library = root/'native-add/fixture/mentor_lib.lmc' library.parent.mkdir(parents=True); library.write_bytes(b'fixture library') (root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8') - source = project(tmp_path/'source') + source = project(tmp_path/'source', 'Block') for path in (source, source.parent/'PCB/pcb.prj'): with path.open('a') as stream: stream.write(f'KEY CentralLibrary "{library}"\n') state = {'entries': [], 'calls': [], 'corrupt': False, 'fail_add': False} @@ -80,7 +80,7 @@ def test_owned_fixture_engine_add_conflict_update_remove_and_identity(transactio root, request, state = transaction original = request.source.read_bytes() assert execute(root, request).status == 'UPLOADED' - registered = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj' + registered = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj' assert project_library(registered) == request.library.resolve() calls = len(state['calls']) assert execute(root, request).status == 'UPLOAD_FAILED' diff --git a/tests/test_native_add_failures.py b/tests/test_native_add_failures.py index 948e253..9954669 100644 --- a/tests/test_native_add_failures.py +++ b/tests/test_native_add_failures.py @@ -68,7 +68,8 @@ def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_pat @pytest.mark.parametrize('cancel', [True, False]) @pytest.mark.parametrize('journal_error', [False, True]) -def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, cancel, journal_error, owned_add_process): +@pytest.mark.parametrize('changed_name', [False, True]) +def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, cancel, journal_error, changed_name, owned_add_process): import os,sys from types import SimpleNamespace import win32gui,win32process @@ -90,7 +91,10 @@ def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, canc monkeypatch.setattr(win32gui,'GetWindowText',lambda h:{100:'Reusable Blocks',200:'New Reusable Block'}[int(h)]) monkeypatch.setattr(win32gui,'GetDlgItem',lambda h,c:110 if h==100 else 210 if c==1083 else c+1000) monkeypatch.setattr(win32gui,'GetClassName',lambda h:'Edit') - monkeypatch.setattr(native,'_set_probe_field',lambda *a:None) + def field(*args, read_only=False): + if read_only and args[1] == 1215 and changed_name: + raise RuntimeError('NATIVE_ADD_NAME_CHANGED') + monkeypatch.setattr(native,'_set_probe_field',field) def post(h,*args): state['posted'].append(h) if h==110:state['new']=True @@ -113,11 +117,12 @@ def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, canc if journal_error: def fail(*a, **kw): raise OSError('phase journal unavailable') monkeypatch.setattr('cbb_refresh_verify.session_record.write_session_record', fail) - expected = OSError if journal_error and not cancel else RuntimeError - message = 'NATIVE_ADD_CANCELLED' if cancel else 'phase journal unavailable' if journal_error else 'unsafe OK posted' + expected = OSError if journal_error and not cancel and not changed_name else RuntimeError + message = ('NATIVE_ADD_NAME_CHANGED' if changed_name else 'NATIVE_ADD_CANCELLED' if cancel + else 'phase journal unavailable' if journal_error else 'unsafe OK posted') with pytest.raises(expected, match=message): native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{owned_add_process.pid},root) - assert state['posted']==([110] if cancel or journal_error else [110,210]) + assert state['posted']==([110] if cancel or journal_error or changed_name else [110,210]) def test_unknown_pending_add_does_not_send_cleanup_dialog_actions(tmp_path, monkeypatch): diff --git a/tests/test_native_management.py b/tests/test_native_management.py index 2f8fcf1..9c5d157 100644 --- a/tests/test_native_management.py +++ b/tests/test_native_management.py @@ -63,7 +63,7 @@ def test_fixture_add_authority_requires_live_lease_and_fresh_staging(tmp_path, m 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 = tmp_path/'original/Block.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) @@ -71,7 +71,7 @@ def test_fixture_add_authority_requires_live_lease_and_fresh_staging(tmp_path, m 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 + assert staged == root/'source/Block.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' @@ -114,7 +114,7 @@ def test_owned_fixture_retains_default_caller_lease_until_native_release(tmp_pat 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') + source = tmp_path/'original/Block.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')}) @@ -156,7 +156,7 @@ def test_fixture_nested_inside_source_tree_rejected_before_staging(tmp_path): 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') + source = tmp_path/'native-add/Block.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): @@ -217,7 +217,7 @@ def test_public_crud_scope_refuses_unproven_flow_or_partition(tmp_path, operatio 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') + source = tmp_path/'Block.prj'; source.write_bytes(b'source') library = tmp_path/'library.lmc'; library.write_bytes(b'library') seen = {} adapter = native.NativeManagementAdapter(mentor_home=tmp_path) @@ -244,7 +244,7 @@ def test_owned_fixture_add_passes_existing_library_and_source_to_worker(tmp_path 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') + source = tmp_path/'Block.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: {