fix: validate library and data paths at the application boundary

This commit is contained in:
阿白叔 committed 2026-11-23 18:06:17 +08:00
1 parent 47c2cfecc6
commit 6d2b6de027
10 files changed
+336 -36

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
"""Verify the Windows desktop and CLI input paths in a candidate package."""
from contextlib import contextmanager
import json
import locale
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
import ntsecuritycon
import pywintypes
import win32api
import win32con
import win32gui
import win32process
import win32security
@contextmanager
def deny_access(path, rights):
dacl_info = win32security.DACL_SECURITY_INFORMATION
original = win32security.GetFileSecurity(str(path), dacl_info)
sid, _, _ = win32security.LookupAccountName(None, win32api.GetUserName())
acl = win32security.ACL()
acl.AddAccessDeniedAce(win32security.ACL_REVISION, rights, sid)
acl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, sid)
restricted = win32security.SECURITY_DESCRIPTOR()
restricted.SetSecurityDescriptorDacl(True, acl, False)
win32security.SetFileSecurity(str(path), dacl_info, restricted)
try:
yield
finally:
win32security.SetFileSecurity(str(path), dacl_info, original)
def cli(exe, library, data_root, expected):
result = subprocess.run(
[str(exe), '--batch-lmc', str(library), '--block', 'Fixture', '--data-root', str(data_root)],
capture_output=True, timeout=15, creationflags=subprocess.CREATE_NO_WINDOW,
)
try:
detail = result.stderr.decode('utf-8')
except UnicodeDecodeError:
detail = result.stderr.decode(locale.getencoding())
assert result.returncode == 1 and expected in detail, (result.returncode, detail)
assert 'Traceback' not in detail and not (data_root / 'reports').exists()
return {'exit_code': result.returncode, 'message': detail.strip()}
def startup_dialog(exe, data_root):
from cbb_refresh_verify.desktop_worker import DesktopWorker
worker = DesktopWorker([str(exe), '--data-root', str(data_root)], 'CbbInputSmoke_' + uuid4().hex[:8])
try:
deadline = time.monotonic() + 15
while worker.poll() is None and time.monotonic() < deadline:
try:
windows = worker.desktop.EnumDesktopWindows()
except pywintypes.error as error:
if error.winerror != 0:
raise
windows = ()
for hwnd in windows:
if win32process.GetWindowThreadProcessId(hwnd)[1] != worker.pid or not win32gui.IsWindowVisible(hwnd):
continue
title = win32gui.GetWindowText(hwnd)
assert title == 'CBB 刷新校验启动失败', title
if win32gui.GetClassName(hwnd) != '#32770':
continue
children = []
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child) or True, None)
button = next((child for child in children if win32gui.GetClassName(child) == 'Button'), None)
if button is None:
continue
texts = [win32gui.GetWindowText(child) for child in children]
message = next((text for text in texts if 'DATA_ROOT_UNWRITABLE' in text), '')
assert str(data_root) in message and '无法写入数据目录' in message, texts
win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0)
code = worker.wait(5)
assert code == 1
return {'exit_code': code, 'title': title, 'message': message}
time.sleep(0.1)
raise AssertionError(f'Startup dialog did not appear, exit={worker.poll()}')
finally:
if worker.poll() is None:
win32process.TerminateProcess(worker.handle, 1)
worker.wait(5)
worker.close()
def main():
workspace, executable, evidence_dir = (Path(arg).resolve() for arg in sys.argv[1:])
sys.path.insert(0, str(workspace / 'src'))
evidence_dir.mkdir(parents=True, exist_ok=False)
assert (executable.parent / '使用说明.txt').read_bytes() == (workspace / 'packaging' / '使用说明.txt').read_bytes()
empty_library = evidence_dir / 'empty.lmc'
empty_library.touch()
unreadable_library = evidence_dir / 'unreadable.lmc'
unreadable_library.write_bytes(b'fixture')
data_root = evidence_dir / 'data'
data_root.mkdir()
blocked_root = evidence_dir / 'readonly'
blocked_root.mkdir()
results = {'guide': 'matched', 'empty_lmc': cli(executable, empty_library, data_root, 'INPUT_EMPTY')}
with deny_access(unreadable_library, ntsecuritycon.FILE_READ_DATA):
results['unreadable_lmc'] = cli(executable, unreadable_library, data_root, 'INPUT_PERMISSION')
with deny_access(blocked_root, ntsecuritycon.FILE_ADD_FILE | ntsecuritycon.FILE_ADD_SUBDIRECTORY):
results['cli_data_root'] = cli(executable, empty_library, blocked_root, 'DATA_ROOT_UNWRITABLE')
results['gui_data_root'] = startup_dialog(executable, blocked_root)
summary = json.dumps(results, ensure_ascii=False, indent=2)
(evidence_dir / 'result.json').write_text(summary + '\n', encoding='utf-8')
print(summary)
if __name__ == '__main__':
main()
+85 -1
View File
@@ -1,11 +1,94 @@
from pathlib import Path
import pytest
@pytest.mark.parametrize('filename, contents, code', [
('empty.lmc', b'', 'INPUT_EMPTY'),
('missing.lmc', None, 'INPUT_MISSING'),
('library.txt', b'library', 'INPUT_SUFFIX'),
])
def test_explicit_cli_block_validates_lmc_before_dispatch(tmp_path, monkeypatch, capsys, filename, contents, code):
from cbb_refresh_verify import application, verify_runner
path = tmp_path / filename
if contents is not None:
path.write_bytes(contents)
monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('invalid input dispatched'))
assert application.main(['--batch-lmc', str(path), '--block', 'A',
'--data-root', str(tmp_path / 'data')]) == 1
assert code in capsys.readouterr().err
def test_explicit_cli_block_reports_unreadable_lmc(tmp_path, monkeypatch, capsys):
from cbb_refresh_verify import application, verify_runner
path = tmp_path / 'library.lmc'
path.write_bytes(b'library')
original_open = Path.open
def open_path(candidate, *args, **kwargs):
if candidate == path:
raise PermissionError('denied')
return original_open(candidate, *args, **kwargs)
monkeypatch.setattr(Path, 'open', open_path)
monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('unreadable input dispatched'))
assert application.main(['--batch-lmc', str(path), '--block', 'A',
'--data-root', str(tmp_path / 'data')]) == 1
assert 'INPUT_PERMISSION' in capsys.readouterr().err
def test_cli_unwritable_data_root_returns_input_exit_code(tmp_path, capsys):
from cbb_refresh_verify import application
path = tmp_path / 'data'
path.touch()
assert application.main(['--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)]) == 1
error = capsys.readouterr().err
assert 'DATA_ROOT_UNWRITABLE' in error and str(path) in error
assert 'Traceback' not in error
def test_windowed_cli_can_write_to_redirected_windows_stderr(tmp_path):
import subprocess
import sys
path = tmp_path / 'data'
path.touch()
command = (
'import sys; from cbb_refresh_verify.application import main; '
'sys.stderr = None; raise SystemExit(main(sys.argv[1:]))'
)
result = subprocess.run([sys.executable, '-X', 'utf8', '-c', command,
'--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)],
capture_output=True, encoding='utf-8', timeout=15,
creationflags=subprocess.CREATE_NO_WINDOW)
assert result.returncode == 1
assert 'DATA_ROOT_UNWRITABLE' in result.stderr and str(path) in result.stderr
def test_desktop_unwritable_data_root_shows_chinese_startup_error(tmp_path, monkeypatch):
import win32api
from cbb_refresh_verify import application
path = tmp_path / 'data'
path.touch()
messages = []
monkeypatch.setattr(win32api, 'MessageBox', lambda parent, detail, title, flags: messages.append((title, detail)))
assert application.main(['--data-root', str(path)]) == 1
assert len(messages) == 1
assert '启动失败' in messages[0][0]
assert '无法写入数据目录' in messages[0][1] and str(path) in messages[0][1]
def test_cli_signal_requests_cooperative_batch_stop(tmp_path, monkeypatch):
import signal
from cbb_refresh_verify import application, verify_runner
library = tmp_path/'center.lmc'
library.touch()
library.write_bytes(b'library')
old = signal.getsignal(signal.SIGINT)
def run(requests, *, stop):
signal.getsignal(signal.SIGINT)(signal.SIGINT, None)
@@ -65,6 +148,7 @@ def test_batch_cli_acquires_unc_lease_before_directory_scan(tmp_path, monkeypatc
monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), {
'root': tmp_path,
'logger': type('L', (), {'info': lambda *a, **k: None,
'warning': lambda *a, **k: None,
'exception': lambda *a, **k: None,
'handlers': ()})(),
})())
+1
View File
@@ -166,6 +166,7 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
from cbb_refresh_verify import application
backend = FakeWNet()
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
(tmp_path/'lib.lmc').write_bytes(b'library')
monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease)
monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc')
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)])
+16 -3
View File
@@ -14,7 +14,20 @@ def test_spec_packages_adaptive_dialog_rules_and_uia_modules():
assert 'pywinauto' in text
def test_spec_analysis_includes_pywin32_timezone_dynamic_import():
def test_spec_analysis_includes_pywin32_timezone_dynamic_import(tmp_path):
captured = _capture_spec_analysis(tmp_path)
assert 'win32timezone' in captured['hiddenimports']
def test_spec_copies_quick_start_next_to_executable(tmp_path):
target = tmp_path / 'CbbRefreshVerify-Background'
target.mkdir()
_capture_spec_analysis(target)
guide = (target / '使用说明.txt').read_text(encoding='utf-8')
assert 'CbbRefreshVerify.exe' in guide and '--data-root' in guide
def _capture_spec_analysis(target):
from types import SimpleNamespace
captured = {}
def analysis(*args, **kwargs):
@@ -23,6 +36,6 @@ def test_spec_analysis_includes_pywin32_timezone_dynamic_import():
path = Path('packaging/CbbRefreshVerify.spec')
namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis,
'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None,
'COLLECT': lambda *a, **k: None}
'COLLECT': lambda *a, **k: SimpleNamespace(name=str(target))}
exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace)
assert 'win32timezone' in captured['hiddenimports']
return captured
+1
View File
@@ -117,6 +117,7 @@ def batch_cli(tmp_path, monkeypatch):
def __enter__(self): return self
def __exit__(self, *_): pass
def retain_for_recovery(self): retained.append(self.drive)
Lease.mentor_path.write_bytes(b'library')
monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease())
monkeypatch.setattr(network, 'select_library_file', lambda path: path)
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((