fix: require owned fixture authority for native Add research

This commit is contained in:
阿白叔 committed 2026-11-03 11:22:27 +08:00
1 parent 07a9c1eaaf
commit b97556dcc1
4 files changed
+208 -18

No files matched your search

@@ -1,7 +0,0 @@
# Task 5: shared native Add route
The adapter now routes Add on an existing owned library through the same private-desktop UIA executor used by the isolated probe. Worker startup checks the pinned route and staged source identity; the executor retains bounded field readback, exact native success message, child-first close, then closes/reopens the library for strict catalog readback. Exact name/partition absence is a native failure; registered content with different raw engineering identity is native success with `identity_matches=False` and an evidence directory.
`route_capabilities()['add']` reports binary-pinned route readiness independently of `capabilities()`. Production Add remains disabled with the explicit engineering-identity reason. Update remains disabled and the management engine still composes remove plus Add. Probe CreateLibrary and readd token/fixture guards remain unchanged. No native tools, Mentor processes, or builds were launched in this task.
Verification: three new boundary tests failed for the missing route method before implementation, then passed. The focused native/management/source/probe-guard/UI suite passed 86 tests. Two additional mocked COM tests passed for close/reopen ordering and strict name/partition versus identity mismatch. Source bytes remained unchanged at the adapter boundary. `git diff --check` passed. Full suite and serialized native validation remain with the coordinator.
+11
View File
@@ -0,0 +1,11 @@
# Native CRUD integration and review follow-up
The shared native Add transport uses the proven private-desktop UIA executor, bounded field readback and exact native success message. It closes/reopens the library before comparing exact catalog name/partition and raw engineering identity. Native registration with different engineering bytes returns `success=True`, `identity_matches=False`; missing registration is a native failure. Production Add and Update remain disabled pending independent engineering identity proof.
The review of 07a9c1e identified that route readiness alone did not authorize existing-library mutation. The follow-up makes public `add()` refuse before reading a source or launching a worker. Research callers must use `add_owned_fixture(..., probe_token=...)` against the fixed library created by the diagnostic workflow and matching probe-owner record. It requires the calling thread's live library lease, checks its lease ID against the checkpoint, owns the management mutex during submission, creates a fresh staged source copy and verified library snapshot, and binds the transaction nonce to target, name, partition, source identity and manifests.
Before native activation the worker revalidates that evidence, exact current lease and live supervisor. It duplicates the supervisor's still-open exclusive sidecar handle and checks its final path, so JSON metadata alone cannot establish ownership. Source alignment is confined to the newly copied worker source. Existing probe CreateLibrary/readd guards remain intact. Removal success matching again excludes both carriage returns and newlines.
Verification is mocked/file-only: the original focused suite passed 86 tests plus two close/reopen checks. Follow-up tests reject public bypass, unprepared activation, missing current-thread ownership, invalid nonce/token/lease, substituted original source, changed backup and expired supervisor, and exercise a valid leased fixture with unchanged original source bytes. No Mentor processes, builds or full suite were launched by this implementation agent; serialized native evidence and semantic-identity research remain coordinator-owned.
The follow-up focused suite passed 99 tests. After restoring ordinary catalog queries for non-DxDesigner flow readback, the native boundary/field subset passed 47 tests (including four additional flow cases). `git diff --check` passed. The original ignored scratch report remains on disk but is removed from version control.
+111 -4
View File
@@ -39,7 +39,7 @@ def removal_input(name, partition):
def removal_output_ok(code, output, name, partition):
return (code == 0 and '# Warning:' not in output and '# Error:' not in output
and re.search(r"# Note: Removed [^\n]+ '" + re.escape(name)
and re.search(r"# Note: Removed [^\r\n]+ '" + re.escape(name)
+ r"' from partition '" + re.escape(partition) + r"'\.", output) is not None)
@@ -102,6 +102,20 @@ class NativeManagementAdapter:
'mapped_drive': job.get('mapped_drive', self.mapped_drive),
'mapped_remote_root': job.get('mapped_remote_root', self.mapped_remote_root),
'timeout_seconds': timeout, 'supervisor_pid': os.getpid()}
if job['operation'] == 'add':
import win32con, win32event
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
raise RuntimeError('Another CBB operation owns the management mutex.')
job = prepare_owned_fixture_add(job, evidence)
return self._launch_worker(job, evidence)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
if job['operation'] == 'probe_create_add':
# Prepare the fixed NEW fixture before a native owner can start.
# The parent owns its sidecar for the entire create/add invocation.
@@ -174,6 +188,12 @@ class NativeManagementAdapter:
raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。')
def add(self, request, evidence):
# Route readiness never grants production mutation authority.
return NativeOutcome(False, True, self.capabilities()['add'].reason,
evidence_path=Path(evidence))
def add_owned_fixture(self, request, evidence, *, probe_token):
"""Research only: stage and back up a token-bound, actively leased fixture."""
evidence = Path(evidence)
validate_name(request.name)
if request.partition != 'Logical-Physical':
@@ -202,6 +222,7 @@ class NativeManagementAdapter:
'mapped_remote_root': request.mapped_remote_root or self.mapped_remote_root,
'timeout_seconds': request.timeout_seconds,
'source_identity': source_identity,
'probe_token': probe_token,
}, evidence)
identity_matches = result.get('identity_matches')
detail = result.get('detail', '')
@@ -211,6 +232,89 @@ class NativeManagementAdapter:
detail, identity_matches=identity_matches, evidence_path=evidence)
def prepare_owned_fixture_add(job, root):
"""Create fresh transaction evidence while this thread owns the fixture."""
from .library_lock import LibraryLock, owned_snapshot, checkpoint_record, blocker_path, _guard, _owners
from .scoped_manifest import copy_verified, ManifestScope
library = validate_probe_readd(job, root)
lease = LibraryLock(library)
if owned_snapshot(lease.path) is None:
raise ValueError('Owned fixture Add requires the current thread library lease.')
guard = checkpoint_record(blocker_path(library))
with _guard:
owner = _owners.get(lease.key)
if (guard is None or guard['pid'] != os.getpid()
or guard['status'] != 'OPERATION_IN_PROGRESS' or owner is None
or guard['lease_id'] != owner['lease_id']):
raise ValueError('Owned fixture lease is not active.')
lease_handle = int(owner['handle'])
source = Path(job['source']).resolve(strict=True)
if (source.parent.is_relative_to(root.resolve()) or root.resolve().is_relative_to(source.parent)
or source.parent.is_relative_to(library.parent.resolve())):
raise ValueError('Research source must be independent of fixture and transaction evidence.')
source_manifest = copy_verified(source.parent, root/'source')
backup = copy_verified(library.parent, root/'library-before',
scope=ManifestScope.library(job['name'], library.name))
nonce = uuid4().hex
prepared = {'nonce': nonce, 'library': str(library), 'lease_id': guard['lease_id'],
'supervisor_pid': os.getpid(), 'source_name': source.name,
'source_manifest': source_manifest, 'backup_manifest': backup,
'name': job['name'], 'partition': job['partition'],
'source_identity': job['source_identity'],
'probe_token': job['probe_token'], 'lease_handle': lease_handle}
_write_json(root/'add-prepared.json', prepared)
return {**job, 'source': str(root/'source'/source.name), 'transaction_nonce': nonce}
def validate_owned_fixture_add(job, root):
"""Reject unprepared, stale or foreign Add jobs before any native activation."""
from .library_lock import checkpoint_record, blocker_path, _supervisor_alive
from .scoped_manifest import build_manifest, ManifestScope
library = validate_probe_readd(job, root)
prepared = json.loads((root/'add-prepared.json').read_text(encoding='utf-8'))
guard = checkpoint_record(blocker_path(library))
source = root/'source'/prepared['source_name']
valid = (bool(job.get('transaction_nonce'))
and prepared['nonce'] == job['transaction_nonce']
and prepared['probe_token'] == job['probe_token']
and prepared['name'] == job['name'] and prepared['partition'] == job['partition']
and prepared['source_identity'] == job['source_identity']
and Path(prepared['library']).resolve() == library.resolve()
and prepared['supervisor_pid'] == job['supervisor_pid']
and guard is not None and guard['pid'] == job['supervisor_pid']
and guard['lease_id'] == prepared['lease_id']
and guard['status'] == 'OPERATION_IN_PROGRESS'
and Path(guard['library']).resolve() == library.resolve()
and _supervisor_alive(job['supervisor_pid'])
and Path(job['source']).resolve() == source.resolve()
and source.resolve().parent == (root/'source').resolve()
and build_manifest(root/'source') == prepared['source_manifest']
and build_manifest(root/'library-before', scope=ManifestScope.library(job['name'], library.name))
== prepared['backup_manifest'])
if not valid:
raise ValueError('Owned fixture Add authority, staging or backup proof is invalid.')
# Metadata alone does not prove ownership. Duplicate the supervisor's
# still-open exclusive sidecar handle and verify its exact final path.
import win32api, win32con, win32file
process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, job['supervisor_pid'])
duplicate = None
try:
duplicate = win32api.DuplicateHandle(process, prepared['lease_handle'],
win32api.GetCurrentProcess(), 0, False, win32con.DUPLICATE_SAME_ACCESS)
final_path = win32file.GetFinalPathNameByHandle(duplicate, 0)
if final_path.startswith('\\\\?\\UNC\\'):
final_path = '\\\\' + final_path[8:]
elif final_path.startswith('\\\\?\\'):
final_path = final_path[4:]
expected_lock = library.with_name('.' + library.stem + '.cbb-upload.lock')
if Path(final_path).resolve() != expected_lock.resolve():
raise ValueError('Supervisor lease handle belongs to a different library.')
finally:
if duplicate is not None: duplicate.Close()
process.Close()
return source
def prepare_probe_library(job, root):
"""Validate a NEW fixed fixture already guarded by its supervisor."""
from .library_lock import blocker_path, checkpoint_record
@@ -348,7 +452,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
from .management import source_project
source, pcb, top = source_project(job['source'], job.get('top_level_block', ''))
source_folder = 'source-replacement' if job['operation'] == 'probe_readd' else 'source'
if not source.is_relative_to(Path(root).parent.resolve()/source_folder):
source_root = Path(root).resolve()/'source' if job['operation'] == 'add' else Path(root).parent.resolve()/source_folder
if not source.is_relative_to(source_root):
raise ValueError('隔离新增只允许使用本次复制的来源工程。')
_align_library(source, pcb, Path(job['library']))
_dispatch_diagnostics(root, 'after-source-alignment', app, library,
@@ -601,6 +706,8 @@ def _catalog_native(job, root):
def _catalog_com(job, root):
import pythoncom, win32com.client, win32con, win32gui, win32process
from .mentor_adapter import _process_details
if job['operation'] == 'add':
validate_owned_fixture_add(job, root)
desktop, name = _current_desktop()
if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
@@ -658,9 +765,9 @@ def _catalog_com(job, root):
raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。')
if library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve():
raise RuntimeError('原生返回中心库身份不一致。')
if int(library.FlowType) != 1:
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
if job['operation'] in ('add', 'probe_create_add', 'probe_readd'):
if int(library.FlowType) != 1:
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
library.Close()
library = None
+86 -7
View File
@@ -13,6 +13,82 @@ def test_installed_binary_mismatch_disables_removal(tmp_path):
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_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()
def test_add_route_readiness_is_separate_from_conservative_capability_gate(tmp_path, monkeypatch):
import hashlib
import cbb_refresh_verify.native_management as native
@@ -25,7 +101,7 @@ def test_add_route_readiness_is_separate_from_conservative_capability_gate(tmp_p
assert '身份' in adapter.capabilities()['add'].reason
def test_native_add_passes_existing_library_and_staged_source_to_worker(tmp_path, monkeypatch):
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')
@@ -42,13 +118,13 @@ def test_native_add_passes_existing_library_and_staged_source_to_worker(tmp_path
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(request, tmp_path/'evidence')
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)},
'timeout_seconds': 23, 'source_identity': {'source': str(source)}, 'probe_token': 'owned',
}
@@ -66,7 +142,8 @@ def test_native_add_identity_mismatch_is_native_success_with_evidence(tmp_path,
'detail': 'engineering identity readback mismatch',
})
original = source.read_bytes()
result = adapter.add(ManagementRequest('add', library, 'Block', source=source), tmp_path/'evidence')
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'
@@ -160,7 +237,8 @@ def test_probe_requires_owned_new_native_library_path(tmp_path):
@pytest.mark.parametrize('records', [[], [('Actual', 'Logical-Physical')]])
@pytest.mark.parametrize('mapped', [False, True])
def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records, mapped):
@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
@@ -177,7 +255,7 @@ def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path,
items = Collection([SimpleNamespace(Name=name, PartitionName=partition) for name, partition in records])
class Library:
FullName = str(library_path)
FlowType = 1
FlowType = flow
def Partitions(self, kind):
assert kind == 7
return Collection([items])
@@ -197,7 +275,7 @@ def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_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'] == 1
assert result['flow'] == flow
def test_production_caps_require_all_validated_binary_hashes(tmp_path, monkeypatch):
@@ -268,6 +346,7 @@ def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path
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)