fix: address review 414 write consent and native ownership boundaries

This commit is contained in:
阿白叔 committed 2026-11-13 17:32:14 +08:00
1 parent 1572e2d8ca
commit fee4a67ff1
19 files changed
+1008 -64

No files matched your search

+2 -1
View File
@@ -83,7 +83,8 @@ def test_worker_refresh_excludes_ready_before_any_gui_result_callback(qtbot,tmp_
status_refresher=lambda names,path:{name:'READY' for name in names})
release,calls=background(window,qtbot)
try:
window._start(lambda:window._read_affected_records(('Gamma',)),lambda payload:None)
library=window.mentor_lmc_path or window.loaded_path
window._start(lambda:window._read_affected_records(('Gamma',),library=library),lambda payload:None)
qtbot.waitUntil(lambda:bool(window.native_queue.pending))
release.set()
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
+11 -10
View File
@@ -183,9 +183,9 @@ def test_idle_guard_ignores_unrelated_project_and_prefix_sibling(recovery_files,
request, original, _ = recovery_files
unrelated = original.parent.with_name(original.parent.name+'Old')/'PCB/A.pcb'
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [(123, '', str(unrelated))])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{unrelated}" -ReusableCircuit', 0)]
if name == 'ExpeditionPCB.exe' else [])
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names:[
dict(pid=123,name='ExpeditionPCB.exe',executable='ExpeditionPCB.exe',
command=f'ExpeditionPCB.exe "{unrelated}" -ReusableCircuit',parent=0)])
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
@@ -195,23 +195,23 @@ def test_idle_guard_rejects_exact_target_process(recovery_files, monkeypatch):
request, original, _ = recovery_files
target = original.parent/'PCB/A.pcb'
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{target}" -ReusableCircuit', 0)]
if name == 'ExpeditionPCB.exe' else [])
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names:[
dict(pid=123,name='ExpeditionPCB.exe',executable='ExpeditionPCB.exe',
command=f'ExpeditionPCB.exe "{target}" -ReusableCircuit',parent=0)])
with pytest.raises(ValueError, match='TARGET_NATIVE_OWNER_ACTIVE'):
_idle_check(request.lmc_file, original, target)
@pytest.mark.parametrize('target_state', ['idle', 'open_file', 'address'])
def test_pathless_external_client_uses_target_resource_proof(recovery_files, monkeypatch, target_state):
def test_pathless_external_client_requires_resource_proof_and_confirmation(recovery_files, monkeypatch, target_state):
import pywintypes
import win32con
import win32file
from cbb_refresh_verify import mentor_adapter
from cbb_refresh_verify.backup_recovery import _idle_check
request, original, _ = recovery_files
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
[(123, 'viewdraw.exe', 'viewdraw.exe', 0)] if name == 'viewdraw.exe' else [])
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names:[
dict(pid=123,name='viewdraw.exe',executable='viewdraw.exe',command='viewdraw.exe',parent=0)])
address = original.parent/'database/cdbsvr/sAddress.adr'
handle = None
try:
@@ -228,7 +228,8 @@ def test_pathless_external_client_uses_target_resource_proof(recovery_files, mon
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
assert address.read_bytes() == b'live or unconfirmed native address'
else:
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
with pytest.raises(ValueError,match='TARGET_NATIVE_OWNER_UNCONFIRMED'):
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
finally:
if handle is not None: handle.Close()
+2 -2
View File
@@ -140,7 +140,7 @@ def test_retained_export_registry_is_scoped_to_its_library(tmp_path, monkeypatch
with pytest.raises(LibraryBusy): assert_retained_exports_idle(library_a)
@pytest.mark.parametrize('created,blocked', [('new-process', False), ('original-process', True)])
@pytest.mark.parametrize('created,blocked', [('20261113120000.000000+480', False), ('20261112120000.000000+480', True)])
def test_recorded_export_pid_reuse_requires_matching_creation_identity(export_case, monkeypatch, created, blocked):
import cbb_refresh_verify.native_engineering_identity as identity
import cbb_refresh_verify.library_lock as locks
@@ -148,7 +148,7 @@ def test_recorded_export_pid_reuse_requires_matching_creation_identity(export_ca
library, root, *_ = export_case
path = root/'ascii-process.json'
record = json.loads(path.read_text('utf-8'))
record['process_identities'] = [{'pid': 123456, 'created': 'original-process', 'executable': 'native'}]
record['process_identities'] = [{'pid': 123456, 'created': '20261112120000.000000+480', 'executable': 'native'}]
path.write_text(json.dumps(record), encoding='utf-8')
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: True)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
+38
View File
@@ -0,0 +1,38 @@
import json,os
from types import SimpleNamespace
import pytest
from test_native_export_guard import export_case
@pytest.mark.parametrize('in_memory',[False,True])
def test_preexisting_exclusion_does_not_hide_a_changed_process_identity(export_case,monkeypatch,in_memory):
import win32api,win32con
from cbb_refresh_verify import native_engineering_identity as identity
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
from cbb_refresh_verify.library_lock import LibraryBusy
library,root,*_=export_case
record=dict(pid=123456,observed_pids=[123456,os.getpid()],process_identities=[
dict(pid=123456,created='20261112120000.000000+480',executable='native'),
dict(pid=os.getpid(),created='20261111120000.000000+480',executable='old-client')])
(root/'ascii-process.json').write_text(json.dumps(record),encoding='utf-8')
monkeypatch.setattr(identity,'_process_snapshot',lambda:[dict(pid=os.getpid(),name='viewdraw.exe',parent=0,
created='20261111120000.000000+480',executable='different-client',command='')])
handle=win32api.OpenProcess(win32con.SYNCHRONIZE,False,os.getpid())
try:
if in_memory:
monkeypatch.setattr(identity,'_retained_exports',[(SimpleNamespace(pid=123456,poll=lambda:0),
{os.getpid():handle},dict(library=str(library),analysis_root=str(root)))])
with pytest.raises(LibraryBusy):
with prove_export_copies_released(library):pass
finally:handle.Close()
def test_noncheckpoint_lease_still_has_a_non_authoritative_disk_audit(tmp_path):
from cbb_refresh_verify.library_lock import LibraryLock,blocker_path
library=tmp_path/'lib.lmc';library.touch()
lease=LibraryLock(library,checkpoint=False)
with lease:
assert not blocker_path(library).exists()
text=lease.path.read_text(encoding='utf-8')
assert f'pid={os.getpid()}' in text and str(library) in text and 'startedUtc=' in text
assert not blocker_path(library).exists()
+51
View File
@@ -0,0 +1,51 @@
"""Review #414: native clicks and queue binding must outlive only their proofs."""
from contextlib import contextmanager
from types import SimpleNamespace
from test_post_repair_consent import snapshot
def test_readwrite_click_can_open_files_after_exclusive_probe_closes(tmp_path, monkeypatch):
import win32con, win32file
from cbb_refresh_verify import pcb_open_consent as consent
path=tmp_path/'icdb.dat'; path.write_bytes(b'database')
monkeypatch.setattr(consent,'validate_owner',lambda *_: {'target':'owned'})
@contextmanager
def guard(*_):
handle=win32file.CreateFile(str(path),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
try:yield
finally:handle.Close()
monkeypatch.setattr(consent,'resource_guard',guard)
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file='lib.lmc',
project='A.prj',pcb='A.pcb',desktop='CbbVerify_test'))
shown=[]; accepted=[]
def perform(*_):
handle=win32file.CreateFile(str(path),win32con.GENERIC_READ|win32con.GENERIC_WRITE,
0,None,win32con.OPEN_EXISTING,0,None)
handle.Close(); accepted.append(True)
return SimpleNamespace(error_code='',accepted_controls=(6,),detail='',channel='win32_button_click')
options=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=perform)
controller.handle(snapshot(),(snapshot(),),**options)
shown[0].choose('continue')
result=controller.handle(snapshot(),(snapshot(),),**options)
assert not result.error_code,result.detail
assert accepted==[True]
def test_batch_queue_never_reads_library_widget_from_worker(qtbot, tmp_path, monkeypatch):
from threading import get_ident
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
gui_thread=get_ident(); violations=[]; calls=[]
window=load_window(qtbot,tmp_path,monkeypatch,
verifier=lambda req: calls.append(req.lmc_file) or VerifyResult('FAIL',safe_to_continue=True))
window.mentor_lmc_path=None
original=window.lmc_edit.text
def text():
if get_ident()!=gui_thread:violations.append('lmc_edit.text')
return original()
monkeypatch.setattr(window.lmc_edit,'text',text)
window._run(['Beta'])
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
assert calls
assert not violations
+181
View File
@@ -0,0 +1,181 @@
from pathlib import Path
from threading import Event
import pytest
from test_backup_recovery import recovery_files
def fixture_paths(tmp_path, monkeypatch):
from test_management import project
source=project(tmp_path/'source')
library=tmp_path/'target/lib.lmc'; library.parent.mkdir(); library.touch()
row=dict(pid=99111,name='viewdraw.exe',executable='viewdraw.exe',command='',parent=0)
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda names:[row])
return library,source,source.parent/'PCB/main.pcb'
def test_pathless_native_cannot_silently_authorize_a_write(tmp_path,monkeypatch):
from cbb_refresh_verify.backup_recovery import _idle_check
paths=fixture_paths(tmp_path,monkeypatch)
with pytest.raises(ValueError,match='TARGET_NATIVE_OWNER_UNCONFIRMED'):
_idle_check(*paths)
def test_explicit_batch_confirmation_is_bound_to_library_and_process_identity(tmp_path,monkeypatch):
from cbb_refresh_verify.write_admission import WriteAdmission
from cbb_refresh_verify.backup_recovery import _idle_check
paths=fixture_paths(tmp_path,monkeypatch)
identity={'pid':99111,'created_handle':'one','image':'viewdraw.exe','owner_sid':'user','session_id':1}
monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity',lambda pid:dict(identity))
choices=[]
def prompt(choice):choices.append(choice);choice.choose('continue')
admission=WriteAdmission(prompt=prompt,stop=Event())
check=lambda:_idle_check(*paths,confirmation=admission,evidence=tmp_path/'evidence',block='Block')
check();check()
assert len(choices)==1
identity['created_handle']='reused-pid'
check()
assert len(choices)==2
other=tmp_path/'other/lib.lmc';other.parent.mkdir();other.touch()
_idle_check(other,*paths[1:],confirmation=admission,evidence=tmp_path/'other-evidence',block='Other')
assert len(choices)==3
@pytest.mark.parametrize('decision',['skip','cancel'])
def test_decline_has_no_grant_and_only_cancel_stops_batch(tmp_path,monkeypatch,decision):
from cbb_refresh_verify.write_admission import WriteAdmission,WriteAdmissionDeclined
from cbb_refresh_verify.backup_recovery import _idle_check
paths=fixture_paths(tmp_path,monkeypatch);stop=Event()
monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity',lambda pid:
dict(pid=pid,created_handle='one',image='viewdraw.exe',owner_sid='user',session_id=1))
admission=WriteAdmission(prompt=lambda choice:choice.choose(decision),stop=stop)
with pytest.raises(WriteAdmissionDeclined):
_idle_check(*paths,confirmation=admission,evidence=tmp_path/'evidence',block='Block')
assert stop.is_set() is (decision=='cancel')
def test_confirmation_cannot_override_actual_database_occupancy(tmp_path,monkeypatch):
import win32con,win32file
from cbb_refresh_verify.write_admission import WriteAdmission
from cbb_refresh_verify.backup_recovery import _idle_check
paths=fixture_paths(tmp_path,monkeypatch);asked=[]
admission=WriteAdmission(prompt=lambda choice:asked.append(choice),stop=Event())
handle=win32file.CreateFile(str(paths[0]),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
try:
with pytest.raises(Exception):
_idle_check(*paths,confirmation=admission,evidence=tmp_path/'evidence',block='Block')
assert not asked
finally:handle.Close()
def test_write_probe_batches_native_owner_queries(tmp_path,monkeypatch):
from test_management import project
from cbb_refresh_verify.backup_recovery import _idle_check
source=project(tmp_path/'source'); library=tmp_path/'lib.lmc';library.touch();queries=[]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda names:
queries.append(tuple(names)) or [])
_idle_check(library,source,source.parent/'PCB/main.pcb')
assert len(queries)==2
assert all(len(names)==5 for names in queries)
def test_user_can_close_unknown_client_before_confirming(tmp_path,monkeypatch):
from cbb_refresh_verify import write_admission as admission_module
from cbb_refresh_verify.write_admission import WriteAdmission
from cbb_refresh_verify.backup_recovery import _idle_check
paths=fixture_paths(tmp_path,monkeypatch);ended=[]
def identity(pid):
if ended:
error=OSError('already exited');error.winerror=87;raise error
return dict(pid=pid,created_handle='one',image='viewdraw.exe',owner_sid='user',session_id=1)
monkeypatch.setattr(admission_module,'process_identity',identity)
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda names: [] if ended else
[dict(pid=99111,name='viewdraw.exe',executable='viewdraw.exe',command='',parent=0)])
def prompt(choice):ended.append(True);choice.choose('continue')
_idle_check(*paths,confirmation=WriteAdmission(prompt=prompt),evidence=tmp_path/'evidence',block='Block')
@pytest.mark.parametrize('first,expected',[('skip',['SKIPPED','UPLOADED']),('cancel',['CANCELLED'])])
def test_batch_continues_only_after_skip_or_confirmed_release(tmp_path,monkeypatch,first,expected):
from dataclasses import replace
from test_management import FileAdapter,project
from cbb_refresh_verify.management import ManagementRequest,run_management_batch
library,source,_=fixture_paths(tmp_path,monkeypatch)
monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity',lambda pid:
dict(pid=pid,created_handle='one',image='viewdraw.exe',owner_sid='user',session_id=1))
choices=[]
def prompt(choice):choices.append(choice);choice.choose(first if len(choices)==1 else 'continue')
request=ManagementRequest('add',library,'One',source=source,auto_verify=False,evidence_dir=tmp_path/'evidence')
adapter=FileAdapter();stop=Event()
results=run_management_batch([request,replace(request,name='Two')],adapter=adapter,stop=stop,version_prompt=prompt)
assert [r.status for r in results]==expected
assert all(r.safe_to_continue for r in results)
assert len(adapter.calls)==(1 if first=='skip' else 0)
def test_write_confirmation_dialog_defaults_cancel_and_cannot_overwrite_choice(qtbot):
from cbb_refresh_verify.write_admission import WriteOwnerChoice
from cbb_refresh_verify.ui.write_owner_dialog import WriteOwnerDialog
choice=WriteOwnerChoice('Block','target.lmc',[dict(pid=12,name='viewdraw.exe',image='viewdraw.exe')])
dialog=WriteOwnerDialog(choice);qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.cancel_button
dialog.skip_button.click();dialog.reject()
assert choice.decision=='skip'
def test_restore_confirmation_evidence_does_not_collide_with_owned_recovery_directory(recovery_files,monkeypatch):
from cbb_refresh_verify.backup_recovery import recover_from_backup
from cbb_refresh_verify.verify_runner import VerifyResult
request,original,source=recovery_files
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda names:[
dict(pid=99111,name='viewdraw.exe',executable='viewdraw.exe',command='',parent=0)])
monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity',lambda pid:
dict(pid=pid,created_handle='one',image='viewdraw.exe',owner_sid='user',session_id=1))
result=recover_from_backup(request,source,version_prompt=lambda c:c.choose('continue'),
verifier=lambda *_a,**_kw:VerifyResult('PASS',library_flag='GREEN'))
assert result.status=='PASS',result.stderr
assert (original.parent/'database/icdb.dat').read_bytes()==b'healthy'
assert list(result.evidence_path.parent.glob('write-owner-consent-*.json'))
def test_cancel_batch_also_stops_default_api_without_a_caller_event(tmp_path,monkeypatch):
from dataclasses import replace
from test_management import FileAdapter
from cbb_refresh_verify.management import ManagementRequest,run_management_batch
library,source,_=fixture_paths(tmp_path,monkeypatch)
monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity',lambda pid:
dict(pid=pid,created_handle='one',image='viewdraw.exe',owner_sid='user',session_id=1))
choices=[]
def prompt(choice):choices.append(choice);choice.choose('cancel' if len(choices)==1 else 'continue')
request=ManagementRequest('add',library,'One',source=source,auto_verify=False,evidence_dir=tmp_path/'evidence')
adapter=FileAdapter()
results=run_management_batch([request,replace(request,name='Two')],adapter=adapter,version_prompt=prompt)
assert [r.status for r in results]==['CANCELLED']
assert len(choices)==1 and not adapter.calls
def test_new_unknown_client_during_confirmation_requires_new_confirmation(tmp_path,monkeypatch):
from cbb_refresh_verify.write_admission import WriteAdmission
from cbb_refresh_verify.backup_recovery import _idle_check
paths=fixture_paths(tmp_path,monkeypatch);added=[]
first=dict(pid=99111,name='viewdraw.exe',executable='viewdraw.exe',command='',parent=0)
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda names:
[first,dict(first,pid=99112)] if added else [first])
monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity',lambda pid:
dict(pid=pid,created_handle='one',image='viewdraw.exe',owner_sid='user',session_id=1))
def prompt(choice):added.append(True);choice.choose('continue')
with pytest.raises(ValueError,match='出现新的未知进程'):
_idle_check(*paths,confirmation=WriteAdmission(prompt=prompt),evidence=tmp_path/'evidence',block='Block')
def test_evidence_write_failure_never_grants_future_writes(tmp_path,monkeypatch):
from cbb_refresh_verify.write_admission import WriteAdmission
paths=fixture_paths(tmp_path,monkeypatch)
owner=dict(pid=99111,name='viewdraw.exe',executable='viewdraw.exe',command='',parent=0)
monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity',lambda pid:
dict(pid=pid,created_handle='one',image='viewdraw.exe',owner_sid='user',session_id=1))
def fail(*args,**kwargs):raise OSError('disk full')
monkeypatch.setattr('cbb_refresh_verify.management._write_json',fail)
admission=WriteAdmission(prompt=lambda choice:choice.choose('continue'))
with pytest.raises(OSError,match='disk full'):
admission.confirm(paths[0],[owner],evidence=tmp_path/'evidence',block='Block')
assert not admission.confirmed(paths[0],[owner])