Files
AstrBot/tests/unit/test_event_loop_diagnostics.py
SoulterandRuochenPan 06261c532a feat: add role-based Local computer permissions (#9472)
* feat: sandbox local member execution on Linux

* feat: add macOS Seatbelt local sandbox

* feat: Implement race-resistant file access for local tools

- Added `open_file_in_allowed_roots` function in `local_file_security.py` to securely open files within specified directories, preventing path traversal attacks.
- Updated file reading functions in `file_read_utils.py` to accept file descriptors, allowing for safer file operations.
- Enhanced `FileReadTool`, `FileWriteTool`, and `FileEditTool` to utilize the new secure file access method.
- Added tests to ensure restricted access works correctly, including scenarios with symlinked directories and ancestor swaps.
- Improved error handling for file operations to provide clearer feedback on permission issues.

* feat: add role-based Local computer permissions

* fix: clarify Windows Local permission behavior

* style: use neutral permission matrix border

* fix: clarify Local runtime permission labels

* fix: localize computer runtime options

* fix: tighten default Local permission policy

* fix: allow macOS sandboxed shell forks

* refactor: extract platform process sandboxes

* refactor: expose cross-platform sandbox limits

* refactor: unify sandbox process lifecycle

* refactor: seal local sandbox abstractions

* test: align local sandbox tests with Windows support

* fix: improve local permission settings layout

* fix: initialize workspace for restricted file writes

* feat: expose runtime and sandbox dependency information

* feat: add disabled local access and platform-aware permission controls

* feat: display runtime information in local permission controls

* fix: validate local permission support before saving config

* fix: use supported local permission defaults on Windows

* fix: restrict local file sending and align Windows permission tests

* chore: remove redundant local permission hint

* fix: restore local sandbox DNS and approved file access

* ci: enable bubblewrap user namespaces on Ubuntu runners

* fix: report local sandbox startup failures

* fix: use a portable sandbox startup probe

* fix: preserve read-only Python virtualenv access in local sandboxes

* fix: revoke local shell sessions when permissions change

* fix: block shared-path attacks on local runtime file exchange

Sandboxed processes can write to shared temp roots, so a named session
log there could be replaced with a symlink to a host file that host-side
reads and appends would follow. Keep managed shell output on an anonymous
temporary file handle instead of a named path.

Also stop _resolve_path_from_sandbox from consulting a booter under the
local runtime: workspace and local-file checks already enforce caller
permissions, and the fallback branch probed the host shell without them.
Reject such paths with FileNotFoundError instead.

* fix: revoke local shell sessions when admin access is removed

* fix: skip missing default roots in local grep

* test: check sandbox file readability across platforms

* test: wait for watchdog retry without fixed sleeps

* test: synchronize watchdog log rotation assertions

---------

Co-authored-by: RuochenPan <badbatch0x01@gmail.com>
2026-09-15 15:48:01 +08:00

125 lines
4.0 KiB
Python

import asyncio
import threading
import pytest
from astrbot.core.utils import event_loop_diagnostics as diagnostics
def test_load_event_loop_diagnostic_settings_defaults():
"""Default settings enable lag monitoring and the stack dump watchdog."""
settings = diagnostics.load_event_loop_diagnostic_settings()
assert settings.lag_monitor_enabled is True
assert settings.lag_monitor_interval == diagnostics.DEFAULT_LAG_MONITOR_INTERVAL
assert settings.lag_monitor_threshold == diagnostics.DEFAULT_LAG_MONITOR_THRESHOLD
assert settings.watchdog_enabled is True
assert settings.watchdog_interval == diagnostics.DEFAULT_WATCHDOG_INTERVAL
assert settings.watchdog_timeout == diagnostics.DEFAULT_WATCHDOG_TIMEOUT
assert settings.watchdog_log_max_bytes == diagnostics.DEFAULT_WATCHDOG_LOG_MAX_BYTES
@pytest.mark.asyncio
async def test_create_event_loop_diagnostic_tasks_defaults():
"""Default diagnostics should create both event loop diagnostic tasks."""
tasks = diagnostics.create_event_loop_diagnostic_tasks()
try:
assert [task.get_name() for task in tasks] == [
"event_loop_lag_monitor",
"event_loop_watchdog",
]
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
@pytest.mark.asyncio
async def test_event_loop_watchdog_stops_worker_thread():
"""The event loop watchdog should stop its worker thread on shutdown."""
task = asyncio.create_task(
diagnostics.event_loop_watchdog(timeout=10, interval=0.01)
)
await asyncio.sleep(0.02)
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert not any(
thread.name == "event_loop_watchdog" for thread in threading.enumerate()
)
@pytest.mark.asyncio
async def test_event_loop_watchdog_writes_rotating_log(tmp_path, monkeypatch):
"""The watchdog should write to and rotate its log file."""
log_path = tmp_path / "logs" / "event_loop_watchdog.log"
log_path.parent.mkdir()
log_path.write_text("x" * 8, encoding="utf-8")
stack_written = threading.Event()
print_stack = diagnostics.traceback.print_stack
monkeypatch.setattr(
diagnostics.traceback,
"print_stack",
lambda *args, **kwargs: (print_stack(*args, **kwargs), stack_written.set()),
)
task = asyncio.create_task(
diagnostics.event_loop_watchdog(
timeout=0.02,
interval=0.005,
dump_path=log_path,
max_bytes=4,
)
)
try:
await asyncio.sleep(0)
# Keep the test frame on the stack until the watchdog writes it.
assert stack_written.wait(timeout=2)
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
log_content = log_path.read_text(encoding="utf-8")
assert "Event loop stalled for" in log_content
assert "test_event_loop_diagnostics.py" in log_content
assert (
log_path.with_name("event_loop_watchdog.log.1").read_text(encoding="utf-8")
== "x" * 8
)
@pytest.mark.asyncio
async def test_event_loop_watchdog_survives_dump_failure(tmp_path, monkeypatch):
"""The watchdog should keep running after stack dump failures."""
log_path = tmp_path / "event_loop_watchdog.log"
dumped = threading.Event()
attempts = 0
def flaky_open(path, max_bytes):
nonlocal attempts
attempts += 1
if attempts == 1:
raise OSError("boom")
dumped.set()
return path.open("a", encoding="utf-8")
monkeypatch.setattr(diagnostics, "_open_watchdog_log_file", flaky_open)
task = asyncio.create_task(
diagnostics.event_loop_watchdog(
timeout=0.02,
interval=0.005,
dump_path=log_path,
)
)
try:
await asyncio.sleep(0)
# Keep the event loop stalled until the watchdog retries the dump.
assert dumped.wait(timeout=2)
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
assert attempts >= 2