Add owned desktop resource diagnostics and sanitized support export

This commit is contained in:
阿白叔 committed 2026-10-23 15:29:43 +08:00
1 parent 7d5ea814ec
commit 6d0b92c515
4 files changed
+407 -1

No files matched your search

+114
View File
@@ -0,0 +1,114 @@
import json
from pathlib import Path
import zipfile
import pytest
from dx_productivity.trial_task_center import diagnostics_bundle as bundle
def test_bundle_allowlist_redacts_secrets_and_home_and_omits_inputs(tmp_path):
root = tmp_path / 'data'
session = root / 'batch-resources' / 'batch1'
session.mkdir(parents=True)
(root / 'logs').mkdir()
(root / 'logs/application.log.1').write_text('user=C:\\Users\\Alice token=super-secret password="a b"', encoding='utf-8')
(session / 'session.json').write_text(json.dumps({'pid': 123, 'api_key': 'hidden', 'input': 'C:\\Users\\Alice\\work\\bom.xlsx'}))
(session / 'source.xlsx').write_bytes(b'private BOM')
(root / 'task-center.db').write_bytes(b'private DB')
target = tmp_path / 'support.zip'
assert bundle.export_diagnostic_bundle(root, target) == target
with zipfile.ZipFile(target) as archive:
text = '\n'.join(archive.read(name).decode('utf-8') for name in archive.namelist())
assert 'super-secret' not in text and 'hidden' not in text and 'a b' not in text
assert 'Alice' not in text and 'private BOM' not in text and 'private DB' not in text
assert json.loads(archive.read('batch-resources/batch1/session.json'))['pid'] == 123
manifest = json.loads(archive.read('manifest.json'))
assert manifest['omissions'] and manifest['unknowns']
with pytest.raises(FileExistsError):
bundle.export_diagnostic_bundle(root, target)
def test_bundle_rejects_non_zip_destination(tmp_path):
with pytest.raises(ValueError):
bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'output.txt')
def test_bundle_does_not_follow_links_or_export_binary_logs(tmp_path):
root = tmp_path / 'data'
(root / 'logs').mkdir(parents=True)
(root / 'logs/binary.log').write_bytes(b'\x00\xff\x00')
external = tmp_path / 'secret.log'
external.write_text('outside data root')
try:
(root / 'logs/link.log').symlink_to(external)
except OSError:
pass
output = bundle.export_diagnostic_bundle(root, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert 'logs/binary.log' not in archive.namelist()
assert 'logs/link.log' not in archive.namelist()
def test_bundle_redacts_nested_client_secret_and_preserves_support_ids(tmp_path):
root = tmp_path / 'data'
directory = root / 'attempts'
directory.mkdir(parents=True)
(directory / 'attempt.json').write_text(json.dumps({'client_secret': 'oauth-private',
'support_id': 'DXT-123', 'username': 'ExternalUser',
'nested': {'authorization': 'Bearer a.b.c'}}))
output = bundle.export_diagnostic_bundle(root, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
text = archive.read('attempts/attempt.json').decode()
assert 'oauth-private' not in text and 'a.b.c' not in text
assert 'ExternalUser' not in text
assert 'DXT-123' in text
def test_bundle_excludes_hardlinks_and_redacts_jsonl_credentials(tmp_path):
import os
root = tmp_path / 'data'
logs = root / 'logs'
logs.mkdir(parents=True)
external = tmp_path / 'private.log'
external.write_text('private content')
os.link(external, logs / 'linked.log')
tasks = root / 'tasks' / 'task1'
tasks.mkdir(parents=True)
(tasks / 'events.jsonl').write_text(json.dumps({'token': 'private-token'}) + '\n')
output = bundle.export_diagnostic_bundle(root, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert 'logs/linked.log' not in archive.namelist()
assert 'private-token' not in archive.read('tasks/task1/events.jsonl').decode()
assert json.loads(archive.read('tasks/task1/events.jsonl'))['token'] == '<REDACTED>'
def test_bundle_size_limit_omits_oversized_files(tmp_path, monkeypatch):
(tmp_path / 'logs').mkdir()
(tmp_path / 'logs/application.log').write_text('too large for configured limit')
monkeypatch.setattr(bundle, 'MAX_FILE_BYTES', 4)
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert 'logs/application.log' not in archive.namelist()
assert any(row['reason'] == 'size_or_count_limit' for row in json.loads(archive.read('manifest.json'))['omissions'])
def test_bundle_includes_real_nested_attempt_queue_and_protection_locations(tmp_path):
names = ['batch-resources/batch1/attempts/g1/attempt1/job1.json',
'task-queues/queue1.json', 'tasks/task1/quick-run/project-checkpoint.json',
'quick-run-history/recovery1/uncertain.flag']
for name in names:
path = tmp_path / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('{}')
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert set(names).issubset(archive.namelist())
def test_plain_log_authorization_redacts_bearer_value(tmp_path):
(tmp_path / 'logs').mkdir()
(tmp_path / 'logs/application.log').write_text('Authorization=Bearer private-bearer-value\n')
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert 'private-bearer-value' not in archive.read('logs/application.log').decode()
+69
View File
@@ -68,6 +68,75 @@ def test_startup_info_always_targets_private_desktop():
assert info.lpDesktop == 'winsta0\\dx-private-test'
def test_desktop_records_native_handle_before_close_and_failed_retry():
class Desktop:
fail = True
def __int__(self):
return 761
def CloseDesktop(self):
if self.fail:
self.fail = False
raise OSError('busy')
handle = Desktop()
desktop = PrivateDesktop('private', enabled=True,
api=SimpleNamespace(create_desktop=lambda _: handle))
desktop.__enter__()
with pytest.raises(TaskCenterError):
desktop.close()
desktop.close()
history = desktop.cleanup_record['desktop_handle_history']
assert [event['operation'] for event in history] == ['create', 'close', 'close']
assert [event['success'] for event in history] == [True, False, True]
assert all(event['handle'] == 761 and event['pid'] == os.getpid() and event['thread_id'] for event in history)
def test_desktop_preserves_forgotten_worker_history_and_unknown_holder_scope():
api, _, state, *_ = native_api()
api.confirm_desktop_released = lambda _: None
desktop = PrivateDesktop('private', enabled=True, api=api)
desktop._handle = SimpleNamespace(CloseDesktop=lambda: None)
process = desktop.start_process(('python.exe',))
process.close()
desktop.forget_closed_process(process)
desktop.close()
history = desktop.cleanup_record['process_history']
assert history[0]['pid'] == 42 and history[0]['cleanup']['process_handle_closed']
assert history[0]['forgotten'] is True
assert desktop.cleanup_record['diagnostic_scope']['external_handle_holders'] == 'unknown'
def test_failed_release_reports_windowless_holder_unknown_and_owned_job_failure():
api, _, _, *_ = native_api()
api._pending_cleanup = []
def confirm(_):
api.desktop_release_check = {'released': False, 'remaining_windows': []}
raise OSError('still exists')
api.confirm_desktop_released = confirm
desktop = PrivateDesktop('private', enabled=True, api=api)
desktop._handle = SimpleNamespace(CloseDesktop=lambda: None)
process = desktop.start_process(('python.exe',))
process.close = lambda: (_ for _ in ()).throw(OSError('owned handles retained'))
with pytest.raises(TaskCenterError):
desktop.close()
report = desktop.cleanup_record['owned_resource_diagnostics']
assert report['residual_windows'] == []
assert report['external_handle_holders'] == 'unknown'
assert report['thread_desktops']['complete'] is False
assert report['owned_processes'][0]['pid'] == 42
assert report['owned_processes'][0]['job_accounting']['ActiveProcesses'] == 0
@pytest.mark.skipif(os.name != 'nt', reason='native Windows resource history')
def test_real_helper_retains_completed_lifecycle_after_forget():
with PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) as desktop:
process = desktop.start_process((sys.executable, '-c', 'pass'))
assert process.wait(timeout=5) == 0
process.close()
desktop.forget_closed_process(process)
assert desktop.cleanup_record['process_history'][0]['pid'] == process.pid
assert desktop.cleanup_record['desktop_handle_history'][0]['handle'] > 0
def test_private_desktop_never_falls_back_to_input_desktop(monkeypatch):
desktop = PrivateDesktop('dx-private-test', enabled=True)
monkeypatch.setattr(desktop, '_create', lambda: None)