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

+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