fix: scope release proofs and bind PCB opening consent

This commit is contained in:
阿白叔 committed 2026-11-12 16:02:53 +08:00
1 parent 42d0cebc54
commit 466f400514
33 files changed
+1358 -61

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
from threading import Event,Thread
def test_normal_verify_batch_yields_after_complete_item(qtbot,tmp_path,monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
started,release,waiting=Event(),Event(),Event()
order=[]
def verify(request):
order.append(request.block_name)
if request.block_name=='Beta':started.set();release.wait(5)
return VerifyResult('FAIL',stderr='independent failed item',safe_to_continue=True)
window=load_window(qtbot,tmp_path,monkeypatch,verifier=verify)
window._run(['Beta','Gamma'])
qtbot.waitUntil(started.is_set)
other=Thread(target=lambda:window.native_queue.run(lambda:order.append('other'),waiting=waiting.set))
other.start()
try:
assert waiting.wait(1)
release.set()
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
other.join(2)
assert order==['Beta','other','Gamma']
finally:release.set();other.join(5)
def test_management_cancel_between_items_keeps_completed_results(tmp_path,monkeypatch):
from cbb_refresh_verify import management
from cbb_refresh_verify.operation_queue import QueueCancelled
from dataclasses import replace
request=management.ManagementRequest('remove',tmp_path/'lib.lmc','A')
def run(req,**kwargs):
return management.ManagementResult(req.operation,req.library,req.name,req.partition,None,False,
'complete','REMOVED',True)
monkeypatch.setattr(management,'run_management',run)
def execute(req,action):
if req.name=='B':raise QueueCancelled('cancelled waiting for native slot')
return action()
results=management.run_management_batch([request,replace(request,name='B')],item_executor=execute)
assert [r.status for r in results]==['REMOVED','CANCELLED']
assert all(r.safe_to_continue for r in results)
def test_cancelled_verify_keeps_summary_without_queueing_cancelled_refresh(qtbot,tmp_path,monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
calls=[]
def verify(req):
calls.append(req.block_name)
window.stop.set()
return VerifyResult('CANCELLED',safe_to_continue=True)
window=load_window(qtbot,tmp_path,monkeypatch,verifier=verify)
window._run(['Beta','Gamma'])
qtbot.waitUntil(lambda:not window.busy,timeout=5000)
assert calls==['Beta']
assert window.summary is not None
assert '队列未执行 1' in window.summary.detailedText()
def test_verify_failure_recheck_finishes_before_yielding_native_queue(qtbot,tmp_path,monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
from cbb_refresh_verify import operation_lifecycle
from dataclasses import replace
window=load_window(qtbot,tmp_path,monkeypatch,
verifier=lambda req:VerifyResult('FAIL',safe_to_continue=False))
active=[];seen=[]
def queued(action):
def run():
active.append(True)
try:return action()
finally:active.pop()
return run
def recheck(library,block,result):
seen.append(bool(active))
return replace(result,safe_to_continue=True)
monkeypatch.setattr(window,'_queued_action',queued)
monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck)
window._run(['Beta'])
qtbot.waitUntil(lambda:not window.busy,timeout=5000)
assert seen==[True]
def test_management_failure_recheck_finishes_before_yielding_native_queue(tmp_path,monkeypatch):
from cbb_refresh_verify import management,operation_lifecycle
from dataclasses import replace
request=management.ManagementRequest('remove',tmp_path/'lib.lmc','A')
monkeypatch.setattr(management,'run_management',lambda req,**kw:management.ManagementResult(
req.operation,req.library,req.name,req.partition,None,False,'complete','BLOCKED',False))
active=[];seen=[]
def item(req,action):
active.append(True)
try:return action()
finally:active.pop()
def recheck(library,block,result):
seen.append(bool(active))
return replace(result,safe_to_continue=True)
monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck)
management.run_management_batch([request],item_executor=item)
assert seen==[True]
+54
View File
@@ -0,0 +1,54 @@
from contextlib import nullcontext
from pathlib import Path
import pytest
import win32con,win32file
from cbb_refresh_verify import library_lock as locks, residual_sessions as sessions
from test_residual_sessions import row, OWNERSHIP
@pytest.mark.parametrize('command', ['viewdraw.exe', 'cscript.exe C:/other/QuickPartReplace.vbs'])
def test_unknown_external_owner_requires_resources_not_process_exit(tmp_path, monkeypatch, command):
library=tmp_path/'lib.lmc';library.touch()
owner=dict(pid=998877,name=command.split()[0],command=command)
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[owner])
with locks._prove_library_released(library) as proof:
assert proof['exclusive_files']==[str(library)]
assert proof['observed_owners']==[owner]
handle=win32file.CreateFile(str(library),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
try:
with pytest.raises(Exception) as denied:
with locks._prove_library_released(library):pass
assert denied.value.winerror == 32
finally:handle.Close()
def test_unknown_observation_is_never_closed_or_counted_as_target(tmp_path,monkeypatch):
library=tmp_path/'lib/lib.lmc';library.parent.mkdir();library.touch()
foreign=dict(row(20,''),name='viewdraw.exe',command='viewdraw.exe',scope_confirmed=False)
target=dict(row(10,library.parent/'A.prj'),scope_confirmed=True)
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[target,foreign])
monkeypatch.setattr(sessions,'_process_windows',lambda _: {})
closed=[]
monkeypatch.setattr(sessions,'_request_close',lambda r,**kw:closed.append(r['pid']) or
dict(release_status='RELEASED',detail='closed'))
monkeypatch.setattr(sessions,'_finish_library_release',lambda *_:dict(status='RELEASE_CONFIRMED',library=str(library)))
result=sessions.release_residual_sessions(dict(library=str(library),sessions=[target,foreign]),tmp_path/'evidence')
assert result['status']=='RELEASE_CONFIRMED',result
assert closed==[10]
assert result['sessions'][1]['release_status']=='OBSERVED'
def test_explicit_target_owner_still_blocks_proof(tmp_path,monkeypatch):
library=tmp_path/'lib.lmc';library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:
[dict(pid=998877,name='viewdraw.exe',command=f'viewdraw.exe "{library}"')])
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library):pass
def test_our_unbound_worker_still_blocks_proof(tmp_path,monkeypatch):
library=tmp_path/'lib.lmc';library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:
[dict(pid=998877,name='CbbRefreshVerify.exe',command='CbbRefreshVerify.exe --verify-worker missing.json')])
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library):pass
+28
View File
@@ -0,0 +1,28 @@
import json
from dataclasses import asdict
from pathlib import Path
import pytest
from cbb_refresh_verify.verify_runner import VerifyRequest,VerifyResult,run_batch
@pytest.mark.parametrize('released',[True,False])
def test_batch_rechecks_owned_failure_before_skipping_next_item(tmp_path,monkeypatch,released):
from cbb_refresh_verify import library_lock,session_record
library=tmp_path/'lib.lmc';library.touch()
root=tmp_path/'failure';root.mkdir()
session_record.write_session_record(root/'session.json',dict(operation_id='test',library=str(library),block='A'))
outcome=VerifyResult('FAIL',stderr='original failure',safe_to_continue=False,
evidence_path=root/'result.json',session_record_path=root/'session.json')
calls=[]
monkeypatch.setattr(session_record,'inspect_session_record',lambda *a,**k:dict(status='UNCONFIRMED'))
def proof(*a,**k):
if not released:raise library_lock.LibraryBusy('shared database still occupied')
return dict(status='RELEASE_CONFIRMED',library=str(library),data_recovery_confirmed=False)
monkeypatch.setattr(library_lock,'release_retained_library',proof)
def verify(req):
calls.append(req.block_name)
return outcome if req.block_name=='A' else VerifyResult('PASS')
results=run_batch([VerifyRequest(library,n,tmp_path/'evidence') for n in ('A','B')],verifier=verify)
assert results[0].status=='FAIL' and results[0].stderr=='original failure'
assert results[0].safe_to_continue is released
assert calls==(['A','B'] if released else ['A'])
+24 -1
View File
@@ -70,6 +70,28 @@ def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_pat
handle.Close()
@pytest.mark.parametrize('checkpoint_matches',[True,False])
def test_auto_verify_reuses_only_exact_active_parent_transaction(tmp_path,monkeypatch,checkpoint_matches):
import json
from cbb_refresh_verify import library_lock as locks,verify_runner as runner
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
calls=[]
monkeypatch.setattr(runner,'_run_verify_serialized',lambda *a,**k:
calls.append('verified') or runner.VerifyResult('PASS',library_flag='GREEN'))
with locks.LibraryLock(library,block_name='A'):
if not checkpoint_matches:
marker=locks.blocker_path(library)
value=json.loads(marker.read_text('utf-8'));value['lease_id']='b'*32
marker.write_text(json.dumps(value),'utf-8')
result=runner.run_verify(runner.VerifyRequest(library,'A',tmp_path/'evidence'))
assert (result.status=='PASS') is checkpoint_matches,result.stderr
assert calls==(['verified'] if checkpoint_matches else [])
if not checkpoint_matches:
# Restore only the fixture checkpoint so the enclosing test lease can exit.
owner=locks._owners[locks.LibraryLock(library).key]
value['lease_id']=owner['lease_id'];marker.write_text(json.dumps(value),'utf-8')
def test_unsafe_verify_records_failure_without_persistent_library_blocker(tmp_path, monkeypatch):
import json
import cbb_refresh_verify.verify_runner as runner
@@ -203,7 +225,8 @@ def test_release_rechecks_owners_after_database_handles_are_acquired(tmp_path, m
calls = []
def query(names):
calls.append(1)
return [] if len(calls) == 1 else [{'pid': 123456, 'name': 'cscript.exe', 'command': 'helper'}]
return [] if len(calls) == 1 else [{'pid': 123456, 'name': 'cscript.exe',
'command': 'cscript.exe close_failed_block.vbs'}]
monkeypatch.setattr(probe, 'query_owners', query)
with pytest.raises(locks.LibraryBusy, match='123456'):
with locks._prove_library_released(library): pass
+42
View File
@@ -221,6 +221,48 @@ def test_export_does_not_adopt_unrelated_existing_native_owner(project, tmp_path
assert len(started) == 3
def test_export_does_not_adopt_existing_child_of_reused_parent_pid(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
import win32api
source, _ = project
root = tmp_path/'exports'; root.mkdir()
# This process predates the exporter; its historical parent PID has been reused.
unrelated = dict(pid=888888, parent=987654, name='python.exe', executable='python.exe',
command='python other-tool.py', created='20261111120000.000000+480')
monkeypatch.setattr(identity, '_process_snapshot', lambda: [unrelated])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
monkeypatch.setattr(win32api, 'OpenProcess', lambda *a: pytest.fail('adopted another tool'))
class Finished:
pid = 987654
returncode = 0
def __init__(self, *a, **k): pass
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
result = identity._run_exports(source, root, tmp_path, 1)
assert result['success'] and result['safe_to_continue']
def test_export_lineage_rejects_reused_owner_and_its_new_children():
from cbb_refresh_verify.native_engineering_identity import _export_descendants, _process_birth
old = '20261112120000.000000+480'
new = '20261112120100.000000+480'
tracked = {10: _process_birth(old), 20: _process_birth(old)}
rows = [dict(pid=20, parent=10, created=new), dict(pid=30, parent=20, created=new)]
assert _export_descendants(rows, tracked, set()) == []
assert 30 not in tracked
# An orphaned real child can outlive its exact original parent.
rows = [dict(pid=40, parent=10, created=new)]
assert _export_descendants(rows, tracked, set()) == rows
def test_export_lineage_rejects_child_older_than_native_handle_birth():
from cbb_refresh_verify.native_engineering_identity import _export_descendants, _process_birth
tracked = {10: _process_birth('20261112120000.000000+480')}
rows = [dict(pid=20, parent=10, created='20261111120000.000000+480')]
assert _export_descendants(rows, tracked, set()) == []
@pytest.mark.parametrize('remains_alive,database_busy', [(False, False), (True, False), (False, True)])
def test_export_reobserves_access_denied_child_before_deciding_release(
project, tmp_path, monkeypatch, remains_alive, database_busy):
+23
View File
@@ -161,6 +161,29 @@ def test_recorded_export_pid_reuse_requires_matching_creation_identity(export_ca
with prove_export_copies_released(library): pass
@pytest.mark.parametrize('in_memory', [False, True])
def test_preexisting_process_misrecorded_as_descendant_does_not_retain_copy(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
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='other')])
(root/'ascii-process.json').write_text(json.dumps(record),'utf-8')
monkeypatch.setattr(identity, '_process_snapshot', lambda: [dict(pid=os.getpid(), name='other.exe',
parent=123456, created='20261111120000.000000+480', executable='other', 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 prove_export_copies_released(library) as copies:
assert copies == [str(root/'project')]
finally:
handle.Close()
@pytest.mark.parametrize('active', [False, True])
def test_unknown_checkpoint_requires_explicit_full_proof_and_no_native_export_owner(tmp_path, monkeypatch, active):
import cbb_refresh_verify.native_engineering_identity as identity
+114
View File
@@ -0,0 +1,114 @@
from contextlib import nullcontext
from types import SimpleNamespace
from dataclasses import replace
import pytest
from test_post_repair_consent import snapshot
@pytest.mark.parametrize('decision,control', [('continue',6),('skip',7),('cancel',7)])
def test_readwrite_requires_explicit_choice_and_consumes_once(tmp_path,monkeypatch,decision,control):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('bound-owner',))
monkeypatch.setattr(consent,'resource_guard',lambda *a:nullcontext())
job=dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),desktop='CbbVerify_test',
project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb'))
controller=consent.OpenController(job)
shown=[];sent=[]
def perform(s,p,phase):
sent.append(p);return SimpleNamespace(accepted_controls=(control,),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=perform)
first=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert not first.error_code and len(shown)==1 and not sent
shown[0].choose(decision)
result=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert len(sent)==1 and sent[0]['target']=={'control_id':control}
assert result.error_code==('' if decision=='continue' else 'PCB_OPEN_SKIPPED' if decision=='skip' else 'USER_CANCELLED')
controller.handle(snapshot(),(snapshot(),),**kwargs)
assert len(sent)==1
def test_no_consent_to_changed_window_or_database_owner(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('bound',))
def occupied(*a):raise ValueError('target database occupied')
monkeypatch.setattr(consent,'resource_guard',occupied)
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),
desktop='CbbVerify_test',project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb')))
shown=[]
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=lambda *a:pytest.fail('unsafe Yes'))
controller.handle(snapshot(),(snapshot(),),**kwargs)
shown[0].choose('continue')
result=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert result.error_code=='DATABASE_RECOVERY_REQUIRED' and 'occupied' in result.detail
def test_explicit_open_dialog_defaults_to_cancel(qtbot):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
choice=OpenChoice('A','lib.lmc')
dialog=PcbOpenDialog(choice);qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.cancel_button
dialog.skip_button.click()
assert choice.decision=='skip'
def test_normal_open_can_request_a_version_without_automatic_repair(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.pcb_restore_prompt import RestoreController
from test_pcb_version_choice import captured
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
job=dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),
desktop='CbbVerify_test',project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb'))
controller=RestoreController(job,user_open=True)
snap=captured();shown=[];sent=[]
def perform(s,p,phase):
sent.append(p);return SimpleNamespace(accepted_controls=(p['target']['control_id'],),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=snap.pid,launcher_pid=10,worker_pid=5,companion_pids=(),show=shown.append,perform=perform)
assert not controller.handle(snap,(snap,),**kwargs).error_code
assert len(shown)==1 and not sent
shown[0].choose('last_user_saved')
assert controller.handle(snap,(snap,),**kwargs).action_sent
selected=replace(snap,controls=tuple(replace(c,checked=c.control_id==6213,selected=c.control_id==6213)
if c.control_id in (6213,6206) else c for c in snap.controls))
assert controller.handle(selected,(selected,),**kwargs).action_sent
assert [p['target']['control_id'] for p in sent]==[6213,1]
def test_readwrite_choice_survives_uia_chrome_enrichment(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.dialog_models import ControlSnapshot
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
monkeypatch.setattr(consent,'resource_guard',lambda *a:nullcontext())
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file='lib.lmc',
project='A.prj',pcb='A.pcb',desktop='CbbVerify_test'))
original=snapshot();shown=[];sent=[]
original=replace(original,controls=tuple(replace(c,name='是(&Y)' if c.control_id==6 else '否(&N)')
if c.class_name=='Button' else c for c in original.controls))
def perform(s,p,phase):
sent.append(p)
return SimpleNamespace(accepted_controls=(6,),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=perform)
controller.handle(original,(original,),**kwargs)
shown[0].choose('continue')
chrome=(ControlSnapshot(original.hwnd,0,original.window_class,original.title,
control_type='Window',patterns=('Window',)),
ControlSnapshot(0,0,'','',control_type='TitleBar',patterns=('Value',)))
enriched=replace(original,controls=tuple(replace(c,name=c.name.replace('&',''))
if c.class_name=='Button' else c for c in reversed(original.controls))+chrome)
assert consent.exact_prompt(enriched)
result=controller.handle(enriched,(enriched,),**kwargs)
assert not result.error_code and len(sent)==1
def test_readwrite_choice_rejects_replaced_native_button(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file='lib.lmc'))
original=snapshot();shown=[]
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,
perform=lambda *a:pytest.fail('changed native button accepted'))
controller.handle(original,(original,),**kwargs)
shown[0].choose('continue')
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
for c in original.controls))
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
+2 -1
View File
@@ -53,7 +53,8 @@ def test_unknown_scope_is_visible_but_never_closed_even_with_force(tmp_path, mon
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: pytest.fail('ended unknown scope'))
for force in (False, True):
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=force)
assert result['status'] == 'PARTIAL'
assert result['status'] == 'RELEASE_CONFIRMED'
assert result['sessions'][0]['release_status'] == 'OBSERVED'
# A request file becoming readable must not expand the user's consent list.
monkeypatch.setattr('cbb_refresh_verify.library_lock._owner_matches_scope', lambda *a: True)
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=True)
+10
View File
@@ -38,6 +38,16 @@ def test_round_trip_and_exact_live_process(tmp_path, child):
assert child.poll() is None
@pytest.mark.parametrize('exited', [True, False])
def test_unconfirmed_journal_is_active_only_while_bound_native_is_alive(tmp_path, child, monkeypatch, exited):
path=record(tmp_path,[dict(role='native',**sessions.process_identity(child.pid))])
sessions.write_session_record(path.with_name('worker-state.json'),dict(operation_id='test-session',phase='UNCONFIRMED'))
monkeypatch.setattr(sessions,'_retained_libraries',{str(path):{sessions._library_key(tmp_path/'lib.lmc')}})
if exited:child.terminate();child.wait(5)
writes=sessions.active_write_records(tmp_path/'lib.lmc')
assert bool(writes) is not exited
@pytest.mark.parametrize('key,value', [('created_handle', 'old'), ('image', 'C:/old.exe'),
('owner_sid', 'S-1-old'), ('session_id', -1)])
def test_reused_pid_is_observed_never_acted_on(tmp_path, child, key, value):