Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e230e1a46 |
No files matched your search
@@ -0,0 +1,13 @@
|
|||||||
|
# 独立审查 1:只读进程探测与原生任务准入队列
|
||||||
|
|
||||||
|
基于 main `a56fd17`,不叠加 PR #3 的历史提交。
|
||||||
|
|
||||||
|
**行为变化:** 增加有界、版本化、只读 owner-probe helper 和可取消的 FIFO 原生任务队列。应用仅新增隐藏的只读 helper 分派;现有 UI、验证和原生写操作保持原来的入口。
|
||||||
|
|
||||||
|
**失败安全:** 查询超时或协议/身份异常返回未确认;暂停或取消的队列票据不会运行其动作,也不阻止后面的可执行任务。不启动或终止 Mentor 进程。
|
||||||
|
|
||||||
|
**回滚方式:** 尚未合入下游时撤销本提交即可;下游接入后须按依赖从上层向下回退。
|
||||||
|
|
||||||
|
完整回归:491 passed,1 条既有 pywinauto STA 提示。编译和 diff 检查通过。
|
||||||
|
|
||||||
|
与原评论建议的差别:`management_transaction` 直接导入管理模型和库锁;`scoped_manifest` 的协调记录与独占快照依赖库锁协议。这两者在后端审查中一起交付,避免构造导入不完整的“纯工具”基线。
|
||||||
@@ -1,136 +1,140 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import argparse, os, sys
|
import argparse, os, sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Sequence
|
from typing import Sequence
|
||||||
from .runtime_logging import configure
|
from .runtime_logging import configure
|
||||||
|
|
||||||
|
|
||||||
def configure_qt_application(app):
|
def configure_qt_application(app):
|
||||||
"""Apply a predictable light palette across machines and Qt themes."""
|
"""Apply a predictable light palette across machines and Qt themes."""
|
||||||
from PySide6.QtGui import QColor, QPalette
|
from PySide6.QtGui import QColor, QPalette
|
||||||
|
|
||||||
app.setStyle('Fusion')
|
app.setStyle('Fusion')
|
||||||
palette = app.palette()
|
palette = app.palette()
|
||||||
colors = {
|
colors = {
|
||||||
QPalette.ColorRole.Window: '#f5f6f8',
|
QPalette.ColorRole.Window: '#f5f6f8',
|
||||||
QPalette.ColorRole.WindowText: '#202124',
|
QPalette.ColorRole.WindowText: '#202124',
|
||||||
QPalette.ColorRole.Base: '#ffffff',
|
QPalette.ColorRole.Base: '#ffffff',
|
||||||
QPalette.ColorRole.AlternateBase: '#eef1f5',
|
QPalette.ColorRole.AlternateBase: '#eef1f5',
|
||||||
QPalette.ColorRole.Text: '#202124',
|
QPalette.ColorRole.Text: '#202124',
|
||||||
QPalette.ColorRole.Button: '#eef1f5',
|
QPalette.ColorRole.Button: '#eef1f5',
|
||||||
QPalette.ColorRole.ButtonText: '#202124',
|
QPalette.ColorRole.ButtonText: '#202124',
|
||||||
QPalette.ColorRole.Highlight: '#2f6fed',
|
QPalette.ColorRole.Highlight: '#2f6fed',
|
||||||
QPalette.ColorRole.HighlightedText: '#ffffff',
|
QPalette.ColorRole.HighlightedText: '#ffffff',
|
||||||
QPalette.ColorRole.ToolTipBase: '#ffffff',
|
QPalette.ColorRole.ToolTipBase: '#ffffff',
|
||||||
QPalette.ColorRole.ToolTipText: '#202124',
|
QPalette.ColorRole.ToolTipText: '#202124',
|
||||||
QPalette.ColorRole.PlaceholderText: '#6b7280',
|
QPalette.ColorRole.PlaceholderText: '#6b7280',
|
||||||
}
|
}
|
||||||
for role, color in colors.items():
|
for role, color in colors.items():
|
||||||
palette.setColor(role, QColor(color))
|
palette.setColor(role, QColor(color))
|
||||||
app.setPalette(palette)
|
app.setPalette(palette)
|
||||||
app.setStyleSheet(
|
app.setStyleSheet(
|
||||||
'QWidget { color: #202124; }'
|
'QWidget { color: #202124; }'
|
||||||
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
|
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
|
||||||
'background: #ffffff; color: #202124; selection-color: #202124; }'
|
'background: #ffffff; color: #202124; selection-color: #202124; }'
|
||||||
'QHeaderView::section { background: #e9edf2; color: #202124; }'
|
'QHeaderView::section { background: #e9edf2; color: #202124; }'
|
||||||
'QPushButton, QToolButton { color: #202124; }'
|
'QPushButton, QToolButton { color: #202124; }'
|
||||||
)
|
)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
def resolve_data_root(cli_value: Path | None) -> Path:
|
def resolve_data_root(cli_value: Path | None) -> Path:
|
||||||
if cli_value is not None: return cli_value.expanduser().resolve()
|
if cli_value is not None: return cli_value.expanduser().resolve()
|
||||||
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
|
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
|
||||||
local = os.environ.get("LOCALAPPDATA")
|
local = os.environ.get("LOCALAPPDATA")
|
||||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||||
|
|
||||||
def main(argv: Sequence[str] | None = None) -> int:
|
def main(argv: Sequence[str] | None = None) -> int:
|
||||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||||
if args.repair_worker:
|
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||||
from .native_repair_ui import repair_worker_main
|
if args.owner_probe:
|
||||||
return repair_worker_main(args.repair_worker)
|
from .owner_probe import owner_probe_main
|
||||||
if args.collect_failure_logs:
|
return owner_probe_main(args.owner_probe)
|
||||||
from .verify_diagnostics import failure_logs_main
|
if args.repair_worker:
|
||||||
return failure_logs_main(args.collect_failure_logs)
|
from .native_repair_ui import repair_worker_main
|
||||||
if args.dialog_agent:
|
return repair_worker_main(args.repair_worker)
|
||||||
from .dialog_agent import dialog_agent_main
|
if args.collect_failure_logs:
|
||||||
return dialog_agent_main(args.dialog_agent)
|
from .verify_diagnostics import failure_logs_main
|
||||||
if args.verify_worker:
|
return failure_logs_main(args.collect_failure_logs)
|
||||||
from .mentor_adapter import worker_main
|
if args.dialog_agent:
|
||||||
import contextlib
|
from .dialog_agent import dialog_agent_main
|
||||||
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
return dialog_agent_main(args.dialog_agent)
|
||||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
if args.verify_worker:
|
||||||
return worker_main(args.verify_worker)
|
from .mentor_adapter import worker_main
|
||||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
import contextlib
|
||||||
try:
|
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||||
if args.batch_lmc:
|
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
return worker_main(args.verify_worker)
|
||||||
run_batch, write_batch_report, failure_report_path)
|
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||||
from .library_reader import read_library_fast
|
try:
|
||||||
from .batch_status import authoritative_status_map
|
if args.batch_lmc:
|
||||||
from .network_path import LibraryPathLease, select_library_file
|
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
run_batch, write_batch_report, failure_report_path)
|
||||||
mentor_path = select_library_file(lease.mentor_path)
|
from .library_reader import read_library_fast
|
||||||
logger.info(
|
from .batch_status import authoritative_status_map
|
||||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
from .network_path import LibraryPathLease, select_library_file
|
||||||
lease.display_path, mentor_path, lease.drive or '-',
|
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||||
lease.remote_root or '-', lease.created)
|
mentor_path = select_library_file(lease.mentor_path)
|
||||||
names = list(args.block)
|
logger.info(
|
||||||
if not names:
|
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||||
library = read_library_fast(
|
lease.display_path, mentor_path, lease.drive or '-',
|
||||||
mentor_path,
|
lease.remote_root or '-', lease.created)
|
||||||
status_reader=lambda path, names: authoritative_status_map(
|
names = list(args.block)
|
||||||
names, path, context.root/'status-scan.jsonl'),
|
if not names:
|
||||||
)
|
library = read_library_fast(
|
||||||
if library.error: raise RuntimeError(library.error)
|
mentor_path,
|
||||||
names = [record.name for record in library.records if record.status != 'READY']
|
status_reader=lambda path, names: authoritative_status_map(
|
||||||
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
|
names, path, context.root/'status-scan.jsonl'),
|
||||||
requests = [VerifyRequest(mentor_path, name, context.root/'evidence',
|
)
|
||||||
libspec=args.libspec, dms_login_config=args.dms_login_config,
|
if library.error: raise RuntimeError(library.error)
|
||||||
mentor_bin=args.mentor_bin, logging_context=context,
|
names = [record.name for record in library.records if record.status != 'READY']
|
||||||
mapped_drive=lease.drive,
|
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
|
||||||
mapped_remote_root=lease.remote_root,
|
requests = [VerifyRequest(mentor_path, name, context.root/'evidence',
|
||||||
native_lm_verify=native_lm_verify_enabled())
|
libspec=args.libspec, dms_login_config=args.dms_login_config,
|
||||||
for name in names]
|
mentor_bin=args.mentor_bin, logging_context=context,
|
||||||
try:
|
mapped_drive=lease.drive,
|
||||||
results = run_batch(requests)
|
mapped_remote_root=lease.remote_root,
|
||||||
except Exception:
|
native_lm_verify=native_lm_verify_enabled())
|
||||||
lease.retain_for_recovery()
|
for name in names]
|
||||||
raise
|
try:
|
||||||
if any(not result.safe_to_continue for result in results):
|
results = run_batch(requests)
|
||||||
lease.retain_for_recovery()
|
except Exception:
|
||||||
report = write_batch_report(requests, results, context.root/'reports')
|
lease.retain_for_recovery()
|
||||||
logger.info('batch_report path=%s', report)
|
raise
|
||||||
logger.info('failure_report path=%s', failure_report_path(report))
|
if any(not result.safe_to_continue for result in results):
|
||||||
code = 0 if all(result.status == 'PASS' for result in results) else 2
|
lease.retain_for_recovery()
|
||||||
logger.info('application_clean_shutdown exit_code=%s', code)
|
report = write_batch_report(requests, results, context.root/'reports')
|
||||||
return code
|
logger.info('batch_report path=%s', report)
|
||||||
from .ui.main_window import MainWindow, application_icon_path
|
logger.info('failure_report path=%s', failure_report_path(report))
|
||||||
if args.smoke_test:
|
code = 0 if all(result.status == 'PASS' for result in results) else 2
|
||||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
logger.info('application_clean_shutdown exit_code=%s', code)
|
||||||
from PySide6.QtWidgets import QApplication
|
return code
|
||||||
app = QApplication.instance() or QApplication([sys.executable])
|
from .ui.main_window import MainWindow, application_icon_path
|
||||||
configure_qt_application(app)
|
if args.smoke_test:
|
||||||
window = MainWindow(logging_context=context); window.show()
|
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||||
icon_path = application_icon_path()
|
from PySide6.QtWidgets import QApplication
|
||||||
if icon_path.is_file():
|
app = QApplication.instance() or QApplication([sys.executable])
|
||||||
from PySide6.QtGui import QIcon
|
configure_qt_application(app)
|
||||||
app.setWindowIcon(QIcon(str(icon_path)))
|
window = MainWindow(logging_context=context); window.show()
|
||||||
if args.smoke_test:
|
icon_path = application_icon_path()
|
||||||
from PySide6.QtCore import QTimer
|
if icon_path.is_file():
|
||||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
from PySide6.QtGui import QIcon
|
||||||
QTimer.singleShot(250, app.quit)
|
app.setWindowIcon(QIcon(str(icon_path)))
|
||||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
if args.smoke_test:
|
||||||
except Exception: logger.exception("application_startup_failure"); return 1
|
from PySide6.QtCore import QTimer
|
||||||
finally:
|
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||||
for handler in logger.handlers: handler.flush()
|
QTimer.singleShot(250, app.quit)
|
||||||
|
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||||
|
except Exception: logger.exception("application_startup_failure"); return 1
|
||||||
|
finally:
|
||||||
|
for handler in logger.handlers: handler.flush()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Cooperative FIFO admission for this application's native operations."""
|
||||||
|
from threading import Condition
|
||||||
|
|
||||||
|
|
||||||
|
class QueueCancelled(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class NativeQueue:
|
||||||
|
def __init__(self):
|
||||||
|
self.condition = Condition()
|
||||||
|
self.pending = []
|
||||||
|
self.active = False
|
||||||
|
|
||||||
|
def wake(self):
|
||||||
|
with self.condition: self.condition.notify_all()
|
||||||
|
|
||||||
|
def run(self, action, *, stop=None, waiting=None, ready=lambda: True):
|
||||||
|
ticket = object()
|
||||||
|
acquired, notified = False, False
|
||||||
|
with self.condition: self.pending.append((ticket, ready))
|
||||||
|
try:
|
||||||
|
while not acquired:
|
||||||
|
with self.condition:
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||||
|
first = next((token for token, available in self.pending if available()), None)
|
||||||
|
if not self.active and first is ticket:
|
||||||
|
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||||
|
self.active = acquired = True
|
||||||
|
else:
|
||||||
|
self.condition.wait(.1)
|
||||||
|
if not acquired and not notified and waiting is not None:
|
||||||
|
notified = True
|
||||||
|
try: waiting()
|
||||||
|
except Exception: pass
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||||
|
return action()
|
||||||
|
finally:
|
||||||
|
with self.condition:
|
||||||
|
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||||
|
if acquired: self.active = False
|
||||||
|
self.condition.notify_all()
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""Bound WMI enumeration in a read-only helper, never in the Qt thread."""
|
||||||
|
from pathlib import Path
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def query_owners(names, *, timeout_seconds=10):
|
||||||
|
names = tuple(names)
|
||||||
|
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
|
||||||
|
raise ValueError('OWNER_QUERY_INVALID')
|
||||||
|
return _query_processes(names, timeout_seconds=timeout_seconds)
|
||||||
|
|
||||||
|
|
||||||
|
def query_process_snapshot(*, timeout_seconds=10):
|
||||||
|
"""Bound a complete process tree; retain unknown executable descendants."""
|
||||||
|
return _query_processes(None, timeout_seconds=timeout_seconds)
|
||||||
|
|
||||||
|
|
||||||
|
def _query_processes(names, *, timeout_seconds):
|
||||||
|
full_snapshot = names is None
|
||||||
|
request = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||||
|
with tempfile.TemporaryDirectory(prefix='cbb-owner-probe-') as directory:
|
||||||
|
job = Path(directory)/'request.json'
|
||||||
|
job.write_text(json.dumps(request), encoding='utf-8')
|
||||||
|
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||||
|
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--owner-probe', str(job)]
|
||||||
|
try:
|
||||||
|
result = subprocess.run(command, timeout=max(.1, min(10, timeout_seconds)),
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||||
|
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||||
|
except subprocess.TimeoutExpired as error:
|
||||||
|
# This helper only enumerates processes; it never launches Mentor
|
||||||
|
# or acquires a native database session.
|
||||||
|
raise RuntimeError('OWNER_QUERY_TIMEOUT: 进程查询超时,占用状态无法确认') from error
|
||||||
|
try:
|
||||||
|
record = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||||
|
rows = record['owners']
|
||||||
|
identity_matches = (type(record.get('snapshot_version')) is int and record['snapshot_version'] == 1
|
||||||
|
if full_snapshot else record.get('names') == list(names))
|
||||||
|
if result.returncode != 0 or not identity_matches or not isinstance(rows, list):
|
||||||
|
raise ValueError('invalid result')
|
||||||
|
seen = set()
|
||||||
|
for row in rows:
|
||||||
|
if (type(row['pid']) is not int or row['pid'] < (0 if full_snapshot else 1)
|
||||||
|
or row['pid'] in seen or not isinstance(row['name'], str) or not row['name']
|
||||||
|
or not full_snapshot and row['name'].casefold() not in {n.casefold() for n in names}
|
||||||
|
or full_snapshot and not isinstance(row['created'], str)
|
||||||
|
or not isinstance(row['command'], str) or not isinstance(row['executable'], str)
|
||||||
|
or type(row['parent']) is not int or row['parent'] < 0):
|
||||||
|
raise ValueError('invalid owner')
|
||||||
|
seen.add(row['pid'])
|
||||||
|
return rows
|
||||||
|
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||||
|
raise RuntimeError('OWNER_QUERY_UNCONFIRMED: 进程查询未返回有效证据') from error
|
||||||
|
|
||||||
|
|
||||||
|
def owner_probe_main(job):
|
||||||
|
import pythoncom
|
||||||
|
import win32com.client
|
||||||
|
job = Path(job)
|
||||||
|
request = json.loads(job.read_text('utf-8'))
|
||||||
|
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
|
||||||
|
names = request.get('names')
|
||||||
|
if not full_snapshot:
|
||||||
|
if (not isinstance(names, list) or not names
|
||||||
|
or any(not isinstance(name, str) or not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names)):
|
||||||
|
return 1
|
||||||
|
pythoncom.CoInitialize()
|
||||||
|
try:
|
||||||
|
service = win32com.client.GetObject('winmgmts:')
|
||||||
|
query = ('SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId' +
|
||||||
|
(',CreationDate' if full_snapshot else '') + ' FROM Win32_Process')
|
||||||
|
if not full_snapshot:
|
||||||
|
query += ' WHERE ' + ' OR '.join(f"Name='{name}'" for name in names)
|
||||||
|
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||||
|
'command': str(item.CommandLine or ''), 'executable': str(item.ExecutablePath or ''),
|
||||||
|
'parent': int(item.ParentProcessId or 0),
|
||||||
|
**({'created': str(item.CreationDate or '')} if full_snapshot else {})}
|
||||||
|
for item in service.ExecQuery(query)]
|
||||||
|
service = None
|
||||||
|
response = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||||
|
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
|
||||||
|
return 0
|
||||||
|
finally:
|
||||||
|
pythoncom.CoUninitialize()
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
from threading import Event, Thread
|
||||||
|
|
||||||
|
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
|
||||||
|
|
||||||
|
|
||||||
|
def test_paused_ticket_yields_to_a_ready_native_task():
|
||||||
|
queue=NativeQueue()
|
||||||
|
ready, waiting, complete=Event(),Event(),Event()
|
||||||
|
order=[]
|
||||||
|
thread=Thread(target=lambda:queue.run(lambda:(order.append('resumed'),complete.set()),
|
||||||
|
ready=ready.is_set,waiting=waiting.set))
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
assert waiting.wait(2)
|
||||||
|
queue.run(lambda:order.append('ready'))
|
||||||
|
assert order==['ready']
|
||||||
|
ready.set();queue.wake()
|
||||||
|
assert complete.wait(2)
|
||||||
|
assert order==['ready','resumed']
|
||||||
|
finally:
|
||||||
|
ready.set();queue.wake();thread.join(2)
|
||||||
|
assert not thread.is_alive()
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancelled_paused_ticket_does_not_hold_later_work():
|
||||||
|
queue=NativeQueue()
|
||||||
|
waiting,stop=Event(),Event()
|
||||||
|
outcome=[]
|
||||||
|
def wait():
|
||||||
|
try:
|
||||||
|
queue.run(lambda:outcome.append('unexpected'),ready=lambda:False,
|
||||||
|
waiting=waiting.set,stop=stop)
|
||||||
|
except QueueCancelled:outcome.append('cancelled')
|
||||||
|
thread=Thread(target=wait);thread.start()
|
||||||
|
try:
|
||||||
|
assert waiting.wait(2)
|
||||||
|
stop.set();queue.wake();thread.join(2)
|
||||||
|
assert not thread.is_alive()
|
||||||
|
queue.run(lambda:outcome.append('next'))
|
||||||
|
assert outcome==['cancelled','next']
|
||||||
|
finally:
|
||||||
|
stop.set();queue.wake();thread.join(2)
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import subprocess
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
def test_wmi_timeout_is_unknown_not_idle(monkeypatch):
|
||||||
|
from cbb_refresh_verify.owner_probe import query_owners
|
||||||
|
def hang(command, **kw):
|
||||||
|
assert 0 < kw['timeout'] <= 10
|
||||||
|
raise subprocess.TimeoutExpired(command, kw['timeout'])
|
||||||
|
monkeypatch.setattr(subprocess, 'run', hang)
|
||||||
|
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||||
|
query_owners(['ExpeditionPCB.exe'])
|
||||||
|
|
||||||
|
|
||||||
|
def test_malformed_wmi_response_is_not_empty_owner_list(monkeypatch):
|
||||||
|
from cbb_refresh_verify.owner_probe import query_owners
|
||||||
|
from pathlib import Path
|
||||||
|
def run(command, **kw):
|
||||||
|
Path(command[-1]).with_name('result.json').write_text('{}')
|
||||||
|
return subprocess.CompletedProcess(command, 0)
|
||||||
|
monkeypatch.setattr(subprocess, 'run', run)
|
||||||
|
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
|
||||||
|
query_owners(['ExpeditionPCB.exe'])
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_snapshot_timeout_is_bounded_and_not_idle(monkeypatch):
|
||||||
|
from cbb_refresh_verify.owner_probe import query_process_snapshot
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
def hang(command, **kw):
|
||||||
|
assert json.loads(Path(command[-1]).read_text('utf-8')) == {'snapshot_version': 1}
|
||||||
|
assert 0 < kw['timeout'] <= .5
|
||||||
|
raise subprocess.TimeoutExpired(command, kw['timeout'])
|
||||||
|
monkeypatch.setattr(subprocess, 'run', hang)
|
||||||
|
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||||
|
query_process_snapshot(timeout_seconds=.5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_snapshot_keeps_unknown_processes_and_creation_identity(monkeypatch):
|
||||||
|
from cbb_refresh_verify.owner_probe import query_process_snapshot
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
rows = [{'pid': 0, 'parent': 0, 'name': 'System Idle Process',
|
||||||
|
'command': '', 'executable': '', 'created': ''},
|
||||||
|
{'pid': 999, 'parent': 100, 'name': 'unlisted-child.exe',
|
||||||
|
'command': 'unlisted-child.exe', 'executable': 'C:/native/unlisted-child.exe',
|
||||||
|
'created': '20261105123456.000000+480'}]
|
||||||
|
def run(command, **kw):
|
||||||
|
Path(command[-1]).with_name('result.json').write_text(json.dumps({
|
||||||
|
'snapshot_version': 1, 'owners': rows}), encoding='utf-8')
|
||||||
|
return subprocess.CompletedProcess(command, 0)
|
||||||
|
monkeypatch.setattr(subprocess, 'run', run)
|
||||||
|
assert query_process_snapshot() == rows
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('change', ['version', 'created', 'duplicate', 'pid'])
|
||||||
|
def test_full_snapshot_rejects_incomplete_response(monkeypatch, change):
|
||||||
|
from cbb_refresh_verify.owner_probe import query_process_snapshot
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
row = {'pid': 10, 'parent': 1, 'name': 'child.exe', 'command': '',
|
||||||
|
'executable': '', 'created': ''}
|
||||||
|
record = {'snapshot_version': 1, 'owners': [row]}
|
||||||
|
if change == 'version': record['snapshot_version'] = 2
|
||||||
|
if change == 'created': del row['created']
|
||||||
|
if change == 'duplicate': record['owners'].append(dict(row))
|
||||||
|
if change == 'pid': row['pid'] = -1
|
||||||
|
def run(command, **kw):
|
||||||
|
Path(command[-1]).with_name('result.json').write_text(json.dumps(record), encoding='utf-8')
|
||||||
|
return subprocess.CompletedProcess(command, 0)
|
||||||
|
monkeypatch.setattr(subprocess, 'run', run)
|
||||||
|
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
|
||||||
|
query_process_snapshot()
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_snapshot_helper_does_not_filter_unknown_descendants(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.owner_probe import owner_probe_main
|
||||||
|
import win32com.client
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import json
|
||||||
|
queries = []
|
||||||
|
def query(sql):
|
||||||
|
queries.append(sql)
|
||||||
|
return [SimpleNamespace(ProcessId=42, ParentProcessId=12, Name='custom-native-child.exe',
|
||||||
|
CommandLine='custom-native-child.exe', ExecutablePath='C:/custom-native-child.exe',
|
||||||
|
CreationDate='creation-time')]
|
||||||
|
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: SimpleNamespace(ExecQuery=query))
|
||||||
|
job = tmp_path/'request.json'; job.write_text('{"snapshot_version": 1}')
|
||||||
|
assert owner_probe_main(job) == 0
|
||||||
|
assert len(queries) == 1 and 'WHERE' not in queries[0]
|
||||||
|
row = json.loads(job.with_name('result.json').read_text('utf-8'))['owners'][0]
|
||||||
|
assert row['name'] == 'custom-native-child.exe' and row['created'] == 'creation-time'
|
||||||
Reference in new issue
Block a user