diff --git a/AGENTS.md b/AGENTS.md index 6f62d987d..328f7a98d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ - `helpers/socket_api.py` owns the local Unix socket transport; `helpers/ui_server.py` binds its lifetime to ASGI startup/shutdown. Core handlers live in `socket/`, plugin handlers in `/socket/`; keep root `socket/` without `__init__.py` so Python's standard library remains importable. - `run_tunnel.py` is only a native sleep compatibility shim for old images until startup migration removes their Supervisor entry; Remote Control implementation and dependencies belong to `plugins/_tunnel/`. - `pytest.ini` and root `conftest.py` own test discovery: `tests` and `plugins` testpaths with importlib import mode, `tests/` importable for sibling test imports, and handler modules named like tests kept out of collection. -- `prepare.py` migrates and loads legacy `.env` configuration before writing the root password; `helpers/migration.py` owns preservation of existing files and symlink handling. +- `prepare.py` migrates and loads legacy `.env` configuration before writing the root password through lightweight `helpers.runtime`, without importing settings or the model stack; `helpers/migration.py` owns preservation of existing files and symlink handling. - `DockerfileLocal` must remain compatible with the contracts under `docker/`. - Runtime or user state under `usr/` and `tmp/` is intentionally outside tracked DOX unless the user explicitly asks otherwise. diff --git a/docker/run/AGENTS.md b/docker/run/AGENTS.md index eefff4a3c..56a9e9b0b 100644 --- a/docker/run/AGENTS.md +++ b/docker/run/AGENTS.md @@ -41,6 +41,7 @@ - Self-update hooks come from the resolved target commit. Run `update/before/` after backup and target validation, before checkout; run `update/after/` after checkout validation, before UI startup and its health timer. Failures abort/restore the checkout; arbitrary system changes are not automatically reversible. - Critical updater replacement is explicitly staged by a before hook, validated before atomic replacement, and backed up next to the runtime updater. Hand off the prepared attempt to the replacement without repeating backup/before hooks; restore the previous updater on handled update failures. Ordinary updates do not replace the updater just because source bytes differ. - Install application requirements with `uv pip install --no-cache --python /usr/local/bin/python` in the single dependency installation pass; launch services directly with `/usr/local/bin/python`. Later overlay cache deletion cannot reclaim base layers. +- Compile dependency bytecode in the dependency layer and application bytecode after final source/asset preparation, using checked-hash invalidation so source updates cannot use stale code. Both local and published builds use these shared scripts. - Keep `PYTHONDONTWRITEBYTECODE=1` for services and their subprocesses: import-time bytecode events can expose a lock inversion between watchdog registration and event dispatch during startup. - The final asset preparation uses installed packages, prepares checksum-pinned default ONNX/tokenizer assets with a failing-on-error inference check, then runs embedding preload. Do not ship unused Torch weights or an outer training stack. Chromium, document parsing and speech assets install only in their plugin sandboxes on first use. - Patchright Python, its driver, Chromium and display runtime belong entirely to the Browser sandbox. Telegram aiogram, IMAP/Exchange packages and WhatsApp npm dependencies likewise install in their guests on demand. `install_playwright.sh` is a no-op compatibility entry point. diff --git a/docker/run/fs/ins/install_A0.sh b/docker/run/fs/ins/install_A0.sh index c5a5a1edb..13b907bca 100644 --- a/docker/run/fs/ins/install_A0.sh +++ b/docker/run/fs/ins/install_A0.sh @@ -2,3 +2,5 @@ set -eu uv pip install --no-cache --python /usr/local/bin/python -r /a0/requirements.txt + +/usr/local/bin/python -m compileall -q --invalidation-mode checked-hash /usr/local/lib/python3.12/site-packages diff --git a/docker/run/fs/ins/prepare_assets.sh b/docker/run/fs/ins/prepare_assets.sh index 2ecfb1fcc..7adc7148f 100644 --- a/docker/run/fs/ins/prepare_assets.sh +++ b/docker/run/fs/ins/prepare_assets.sh @@ -4,3 +4,5 @@ set -eu cd /a0 /usr/local/bin/python -m helpers.local_embeddings /usr/local/bin/python preload.py --dockerized=true + +/usr/local/bin/python -m compileall -q --invalidation-mode checked-hash /a0 diff --git a/helpers/migration.py b/helpers/migration.py index efc558b1a..d62da71a1 100644 --- a/helpers/migration.py +++ b/helpers/migration.py @@ -1,12 +1,12 @@ import os import json from helpers import files -from helpers import subagents, extension -from helpers import yaml as yaml_helper from helpers.print_style import PrintStyle def startup_migration() -> None: + from helpers import extension + migrate_user_data() convert_agents_json_yaml() @@ -82,6 +82,9 @@ def migrate_dotenv() -> None: def convert_agents_json_yaml() -> None: + from helpers import subagents + from helpers import yaml as yaml_helper + for root in subagents.get_agents_roots(): rel_root = files.deabsolute_path(root) for subdir in files.get_subdirectories(rel_root): diff --git a/helpers/migration.py.dox.md b/helpers/migration.py.dox.md index ef0d16fa6..f077155d1 100644 --- a/helpers/migration.py.dox.md +++ b/helpers/migration.py.dox.md @@ -23,6 +23,8 @@ ## Runtime Contracts +- Dotenv-only preparation must not load agent profiles or extensions; full startup migration imports those dependencies when it runs. + - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. - Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change. - Startup cleanup removes obsolete `memory` and `knowledge/default` directories. Legacy top-level `logs` (including symlinks) and new `usr/logs` are preserved in place on every run; no log migration, overwriting, conversion or retention cleanup occurs. Back up historical top-level logs separately from `usr` before replacing an old container. diff --git a/helpers/print_style.py b/helpers/print_style.py index 7442e804a..2d44a9884 100644 --- a/helpers/print_style.py +++ b/helpers/print_style.py @@ -96,6 +96,19 @@ class PrintStyle: self._log_text("\n") self.padding_added = True + def _get_secrets_manager(self): + if hasattr(self, "secrets_mgr"): + return self.secrets_mgr + from helpers import dotenv, secrets + + if "agent" not in sys.modules: + # Bootstrap has no agent context; keep global credential masking without loading models. + return secrets.SecretsManager( + secrets.DEFAULT_SECRETS_FILE, dotenv.get_dotenv_file_path() + ) + self.secrets_mgr = secrets.get_secrets_manager() + return self.secrets_mgr + def _log_text(self, text, *, stream=False, end=""): text = (PrintStyle._log_escape_tail if stream else "") + sanitize_string(text) text = _ANSI_ESCAPE.sub("", text) @@ -109,10 +122,7 @@ class PrintStyle: text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", text) if text.strip(): try: - if not hasattr(self, "secrets_mgr"): - from helpers.secrets import get_secrets_manager - self.secrets_mgr = get_secrets_manager() - text = sanitize_string(self.secrets_mgr.mask_values(text)) + text = sanitize_string(self._get_secrets_manager().mask_values(text)) except Exception: text = "[Application log message omitted: secret masking unavailable]\n" try: @@ -168,10 +178,7 @@ class PrintStyle: # Automatically mask secrets in all print output try: - if not hasattr(self, "secrets_mgr"): - from helpers.secrets import get_secrets_manager - self.secrets_mgr = get_secrets_manager() - text = self.secrets_mgr.mask_values(text) + text = self._get_secrets_manager().mask_values(text) except Exception: # If masking fails, proceed without masking to avoid breaking functionality pass diff --git a/helpers/print_style.py.dox.md b/helpers/print_style.py.dox.md index 3779b4af5..bc14c0cff 100644 --- a/helpers/print_style.py.dox.md +++ b/helpers/print_style.py.dox.md @@ -25,6 +25,8 @@ ## Runtime Contracts +- Before `agent` is loaded, logging masks global secrets and runtime credentials directly, without importing the agent/model stack or running context hooks. Bootstrap managers are uncached so dotenv migration/password writes are visible immediately; later logging uses the normal context-aware manager. Masking failures retain the existing file omission behavior. + - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. - Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change. - `print()` and `stream()` append UTF-8 plain text to one uniquely created `log__.log` per process under `files.get_abs_path(files.USER_DIR, "logs")`. Creation is lazy, uses owner-only file permissions, and never truncates a prior run. The directory follows the native project root or mounted Docker `/a0/usr`. diff --git a/helpers/runtime.py b/helpers/runtime.py index 5751de5f7..b311d391a 100644 --- a/helpers/runtime.py +++ b/helpers/runtime.py @@ -1,6 +1,7 @@ import argparse import inspect import secrets +import subprocess from pathlib import Path from typing import TypeVar, Callable, Awaitable, Union, overload, cast from helpers import dotenv, rfc, files @@ -60,6 +61,18 @@ def is_dockerized() -> bool: return bool(get_arg("dockerized")) +def set_root_password(password: str): + if not is_dockerized(): + raise Exception("root password can only be set in dockerized environments") + subprocess.run( + ["chpasswd"], + input=f"root:{password}".encode(), + capture_output=True, + check=True, + ) + dotenv.save_dotenv_value(dotenv.KEY_ROOT_PASSWORD, password) + + def is_development() -> bool: return not is_dockerized() diff --git a/helpers/runtime.py.dox.md b/helpers/runtime.py.dox.md index bb6d09b20..ded890e7a 100644 --- a/helpers/runtime.py.dox.md +++ b/helpers/runtime.py.dox.md @@ -15,6 +15,7 @@ - `get_arg(name: str)` - `has_arg(name: str)` - `is_dockerized() -> bool` +- `set_root_password(password: str)` - `is_development() -> bool` - `get_local_url()` - `get_runtime_id() -> str` @@ -35,12 +36,14 @@ ## Runtime Contracts +- `set_root_password(password)` requires Docker mode, runs checked `chpasswd`, then persists `ROOT_PASSWORD`; a failed command must not save credentials. Preparation calls it without loading settings/model providers. + - `call_development_function` and its sync counterpart remain legacy compatibility entry points. First-party callers invoke their target functions locally; explicit RFC handling and transports are unchanged. The sync compatibility wrapper retains its historical thread/queue behavior and is not used for normal filesystem operations. - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. - Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change. - Observed side-effect areas: filesystem reads, filesystem writes, subprocess/runtime control, settings/state persistence, secret handling, tunnel state. -- Imported dependency areas include: `argparse`, `asyncio`, `helpers`, `inspect`, `nest_asyncio`, `pathlib`, `queue`, `secrets`, `sys`, `threading`, `typing`. +- Imported dependency areas include: `argparse`, `asyncio`, `helpers`, `inspect`, `nest_asyncio`, `pathlib`, `queue`, `secrets`, `subprocess`, `sys`, `threading`, `typing`. ## Key Concepts diff --git a/helpers/settings.py b/helpers/settings.py index a7192e6b1..def64b5cc 100644 --- a/helpers/settings.py +++ b/helpers/settings.py @@ -6,12 +6,12 @@ import hashlib import json import os import re -import subprocess from typing import Any, Literal, TypedDict, cast, TypeVar import models import pytz # type: ignore from helpers import runtime, defer, git, subagents +from helpers.runtime import set_root_password from . import files, dotenv from helpers.print_style import PrintStyle from helpers.providers import get_providers, FieldOption as ProvidersFO @@ -814,18 +814,6 @@ def _dict_to_env(data_dict): return "\n".join(lines) -def set_root_password(password: str): - if not runtime.is_dockerized(): - raise Exception("root password can only be set in dockerized environments") - _result = subprocess.run( - ["chpasswd"], - input=f"root:{password}".encode(), - capture_output=True, - check=True, - ) - dotenv.save_dotenv_value(dotenv.KEY_ROOT_PASSWORD, password) - - def get_runtime_config(set: Settings): # SSH config is now managed by the code_execution plugin. # This function is kept for backward compatibility but returns an empty dict. diff --git a/helpers/settings.py.dox.md b/helpers/settings.py.dox.md index af04e158f..ff96be8a1 100644 --- a/helpers/settings.py.dox.md +++ b/helpers/settings.py.dox.md @@ -56,6 +56,8 @@ ## Runtime Contracts +- `set_root_password` remains a compatibility export of `helpers.runtime.set_root_password`; sensitive-settings writes retain the same Docker guard, checked command and dotenv persistence. + - Settings reads use `models.get_api_key_raw()` to preserve complete key lists without advancing runtime rotation or persisting keys synthesized by runtime hooks. Masking, authentication reloads, and intentional clearing retain their existing behavior. - `ui_control_visibility` accepts dynamic `canvas:` entries as well as built-in controls, normalizes device values to booleans (default shown), and preserves choices for temporarily unavailable plugins. @@ -65,7 +67,7 @@ - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. - Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change. - Observed side-effect areas: filesystem reads, filesystem writes, filesystem deletion, network calls, subprocess/runtime control, model calls, WebSocket state, plugin state, settings/state persistence, secret handling, scheduler state. -- Imported dependency areas include: `base64`, `hashlib`, `helpers`, `helpers.notification`, `helpers.print_style`, `helpers.providers`, `helpers.secrets`, `json`, `models`, `os`, `pytz`, `re`, `subprocess`, `typing`. +- Imported dependency areas include: `base64`, `hashlib`, `helpers`, `helpers.notification`, `helpers.print_style`, `helpers.providers`, `helpers.secrets`, `json`, `models`, `os`, `pytz`, `re`, `typing`. ## Key Concepts diff --git a/helpers/ui_server.py b/helpers/ui_server.py index 4435ba57d..34312cabe 100644 --- a/helpers/ui_server.py +++ b/helpers/ui_server.py @@ -3,6 +3,7 @@ from contextlib import asynccontextmanager from datetime import timedelta import asyncio import gzip +import importlib import json import logging import os @@ -29,7 +30,7 @@ from uvicorn.middleware.wsgi import WSGIMiddleware from werkzeug.wrappers.request import Request as WerkzeugRequest import socketio # type: ignore[import-untyped] -from helpers import dotenv, fasta2a_server, files, git, login, mcp_server, runtime +from helpers import dotenv, files, git, login, runtime from helpers.api import get_safe_next_url, register_api_route, requires_auth from helpers.extension import extensible, get_webui_extension_manifest from helpers.files import get_abs_path @@ -228,7 +229,7 @@ class UiServerRuntime: ) self._transport_registered = True - def build_asgi_app(self, startup_monitor: StartupMonitor): + def build_asgi_app(self, startup_monitor: StartupMonitor, extra_routes=()): @asynccontextmanager async def lifespan(app): async with startup_monitor.lifespan()(app): @@ -238,15 +239,18 @@ class UiServerRuntime: with startup_monitor.stage("wsgi.middleware.create"): wsgi_app = WSGIMiddleware(self.webapp) - with startup_monitor.stage("mcp.proxy.init"): - mcp_app = mcp_server.DynamicMcpProxy.get_instance() + async def mcp_app(scope, receive, send): + module = await asyncio.to_thread(importlib.import_module, "helpers.mcp_server") + await module.DynamicMcpProxy.get_instance()(scope, receive, send) - with startup_monitor.stage("a2a.proxy.init"): - a2a_app = fasta2a_server.DynamicA2AProxy.get_instance() + async def a2a_app(scope, receive, send): + module = await asyncio.to_thread(importlib.import_module, "helpers.fasta2a_server") + await module.DynamicA2AProxy.get_instance()(scope, receive, send) with startup_monitor.stage("starlette.app.create"): starlette_app = Starlette( routes=[ + *extra_routes, Mount("/mcp", app=mcp_app), Mount("/a2a", app=a2a_app), Mount("/", app=wsgi_app), diff --git a/helpers/ui_server.py.dox.md b/helpers/ui_server.py.dox.md index 83c33f708..14a59c254 100644 --- a/helpers/ui_server.py.dox.md +++ b/helpers/ui_server.py.dox.md @@ -16,7 +16,7 @@ - `refresh_runtime_settings(self) -> None` - `register_http_routes(self) -> None` - `register_transport_handlers(self) -> None` - - `build_asgi_app(self, startup_monitor: StartupMonitor)` + - `build_asgi_app(self, startup_monitor: StartupMonitor, extra_routes=())` - `access_log_enabled(self) -> bool` - `UiRouteHandlers` (no explicit base class) - `async login_handler(self)` @@ -36,6 +36,10 @@ ## Runtime Contracts +- `build_asgi_app(..., extra_routes=())` accepts gateway mounts before the core routes, allowing desktop/browser hooks to preserve the same core lifecycle and middleware. + +- MCP and A2A mounts import their implementations on first protocol request in a worker thread, then delegate to the existing singleton on the ASGI loop. WebUI startup does not initialize either proxy; their enabled checks, token checks and reconfiguration remain authoritative. First protocol use pays its import cost. + - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. - Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change. - Socket.IO heartbeat defaults are intentionally longer than Engine.IO's short defaults so CLI sessions survive long prompt/context work; environment overrides must remain positive integers and fall back to source defaults when invalid. diff --git a/helpers/virtual_desktop_routes.py b/helpers/virtual_desktop_routes.py index 05bf7f09e..f671894bc 100644 --- a/helpers/virtual_desktop_routes.py +++ b/helpers/virtual_desktop_routes.py @@ -405,39 +405,15 @@ def install_route_hooks() -> None: original_build_asgi_app = UiServerRuntime.build_asgi_app def build_asgi_app(self, startup_monitor): - from socketio import ASGIApp - from starlette.applications import Starlette from starlette.routing import Mount - from uvicorn.middleware.wsgi import WSGIMiddleware - - from helpers import fasta2a_server, mcp_server from plugins._desktop.helpers.gateway import TuxeeGateway from plugins._browser.helpers.viewer_gateway import BrowserVncGateway - with startup_monitor.stage("wsgi.middleware.create"): - wsgi_app = WSGIMiddleware(self.webapp) - - with startup_monitor.stage("mcp.proxy.init"): - mcp_app = mcp_server.DynamicMcpProxy.get_instance() - - with startup_monitor.stage("a2a.proxy.init"): - a2a_app = fasta2a_server.DynamicA2AProxy.get_instance() - - with startup_monitor.stage("starlette.app.create"): - starlette_app = Starlette( - routes=[ - Mount("/browser/vnc", app=BrowserVncGateway(self.webapp)), - Mount("/desktop/tuxee", app=TuxeeGateway(self.webapp)), - Mount("/desktop", app=VirtualDesktopGateway(self.webapp, "/desktop")), - Mount("/mcp", app=mcp_app), - Mount("/a2a", app=a2a_app), - Mount("/", app=wsgi_app), - ], - lifespan=startup_monitor.lifespan(), - ) - - with startup_monitor.stage("socketio.asgi.create"): - return ASGIApp(self.socketio_server, other_asgi_app=starlette_app) + return original_build_asgi_app(self, startup_monitor, extra_routes=[ + Mount("/browser/vnc", app=BrowserVncGateway(self.webapp)), + Mount("/desktop/tuxee", app=TuxeeGateway(self.webapp)), + Mount("/desktop", app=VirtualDesktopGateway(self.webapp, "/desktop")), + ]) UiServerRuntime.build_asgi_app = build_asgi_app UiServerRuntime._a0_virtual_desktop_route_hooks_installed = True diff --git a/helpers/virtual_desktop_routes.py.dox.md b/helpers/virtual_desktop_routes.py.dox.md index a47bf640a..7fb79b917 100644 --- a/helpers/virtual_desktop_routes.py.dox.md +++ b/helpers/virtual_desktop_routes.py.dox.md @@ -27,6 +27,8 @@ ## Runtime Contracts +- Route installation delegates to the original `UiServerRuntime.build_asgi_app` with the three gateway mounts prepended. Preserve the core socket lifespan, compression, Socket.IO composition and lazy MCP/A2A imports; do not rebuild a second copy of the core ASGI tree. + - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. - Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change. - Observed side-effect areas: filesystem deletion, network calls, subprocess/runtime control, WebSocket state, settings/state persistence, secret handling. diff --git a/prepare.py b/prepare.py index 907972817..f9496a97f 100644 --- a/prepare.py +++ b/prepare.py @@ -1,7 +1,6 @@ -from helpers import dotenv, migration, runtime, settings +from helpers import dotenv, migration, runtime import string import random -import sys from helpers.print_style import PrintStyle @@ -20,7 +19,7 @@ try: if not root_pass: root_pass = "".join(random.choices(string.ascii_letters + string.digits, k=32)) PrintStyle.standard("Changing root password...") - settings.set_root_password(root_pass) + runtime.set_root_password(root_pass) except Exception as e: - PrintStyle.error(f"Error in preload: {e}") + PrintStyle.error(f"Error preparing environment: {e}") diff --git a/tests/AGENTS.md b/tests/AGENTS.md index 40a0f4517..f1db3ab94 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -47,6 +47,7 @@ - Run `pytest tests/test_litellm_sdk.py -q` for LiteLLM/OpenAI upgrades. Its loopback provider exercises the installed SDK's sync/async calls, streaming, tool/state preservation, fallback, embeddings, and Anthropic cache markers without real keys or external requests. - Run `pytest tests/test_framework_dependencies.py -q` for dependency migration changes; verify stale self-update environments, process restart, and already-current image installs. - Self-update hooks and critical updater handoff: `pytest tests/test_self_update_hooks.py tests/test_self_update_runtime_sync.py tests/test_self_update_tag_filter.py`. Hook tests use isolated Git releases and real script subprocesses; they also run with `python -m unittest discover -s tests -p test_self_update_hooks.py` when pytest is unavailable. +- Run `pytest tests/test_boot_imports.py tests/test_migration_dotenv.py -q` for lightweight preparation, checked password persistence, lazy protocol imports and first-request access checks. - Run `pytest tests/test_docker_python_runtime.py -q` for global Python installation, direct service launchers, and entrypoints without import-time dependency activation. - Tuxee release integration: `test_tuxee_install.py` covers download/checksum/version failures, standard layout/locking and preservation of newer binaries; `test_tuxee_gateway.py` covers update JSON, authentication/CSRF, stale-cookie recovery and logout/reopen session renewal; `node --test tests/test_desktop_lifecycle.mjs` covers tab/canvas/modal reloads, docking and startup races. Pair with upstream's real update/restart browser fixture through the A0 gateway before shipping a release pin. - ONNX changes require `test_local_embeddings.py`, `test_onnx_migration.py`, preload/factory tests and `integration_onnx_compatibility.py`: create synthetic fixtures with the old runtime, test new queries/inserts against identical persisted indexes, then restart in a separate process. Never use private live databases. diff --git a/tests/test_boot_imports.py b/tests/test_boot_imports.py new file mode 100644 index 000000000..8bc7fb135 --- /dev/null +++ b/tests/test_boot_imports.py @@ -0,0 +1,168 @@ +"""Startup keeps preparation and unused protocol servers off the import path.""" +import subprocess +import sys +from pathlib import Path + +import pytest + +from helpers import dotenv, runtime + + +PROJECT_ROOT = Path(__file__).resolve().parents[1] + + +def test_prepare_does_not_import_model_stack(): + subprocess.run( + [sys.executable, "-c", r""" +import importlib.abc +import runpy +import sys +import tempfile +from pathlib import Path + +attempted = [] +class RejectModels(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname.split('.')[0] in {'models', 'litellm', 'onnxruntime'}: + attempted.append(fullname) + raise AssertionError(fullname) + +sys.meta_path.insert(0, RejectModels()) +from helpers import files, runtime +prepare = Path('prepare.py').resolve() +with tempfile.TemporaryDirectory() as root: + files._base_dir = root + Path(root, '.env').write_text('ROOT_PASSWORD=synthetic-root-secret\nAPI_KEY_TEST=synthetic-api-secret\n') + Path(root, 'usr').mkdir() + Path(root, 'usr/secrets.env').write_text('TOKEN=synthetic-global-secret\n') + commands = [] + runtime.subprocess.run = lambda *args, **kwargs: commands.append((args, kwargs)) + sys.argv = ['prepare.py', '--dockerized=true'] + runpy.run_path(str(prepare), run_name='__main__') + assert len(commands) == 1 and commands[0][1]['input'] == b'root:synthetic-root-secret' + from helpers.print_style import PrintStyle + printer = PrintStyle() + text = printer.get('synthetic-root-secret synthetic-api-secret synthetic-global-secret')[0] + assert 'synthetic-' not in text + assert attempted == [], attempted + assert 'models' not in sys.modules + from helpers import secrets + from types import SimpleNamespace + secrets.get_secrets_manager = lambda: SimpleNamespace(mask_values=lambda text: 'context-masked') + sys.modules['agent'] = SimpleNamespace() + assert printer.get('later context')[0] == 'context-masked' +"""], + cwd=PROJECT_ROOT, + check=True, + timeout=60, + ) + + +def test_root_password_requires_docker_and_persists_only_after_success(monkeypatch): + writes = [] + monkeypatch.setattr(dotenv, "save_dotenv_value", lambda *args: writes.append(args)) + monkeypatch.setattr(runtime, "is_dockerized", lambda: False) + with pytest.raises(Exception, match="only be set in dockerized"): + runtime.set_root_password("test-password") + + monkeypatch.setattr(runtime, "is_dockerized", lambda: True) + + def failed(*args, **kwargs): + raise subprocess.CalledProcessError(1, "chpasswd") + + monkeypatch.setattr(runtime.subprocess, "run", failed) + with pytest.raises(subprocess.CalledProcessError): + runtime.set_root_password("test-password") + assert writes == [] + + def success(command, **kwargs): + assert command == ["chpasswd"] + assert kwargs == dict(input=b"root:test-password", capture_output=True, check=True) + + monkeypatch.setattr(runtime.subprocess, "run", success) + runtime.set_root_password("test-password") + assert writes == [(dotenv.KEY_ROOT_PASSWORD, "test-password")] + from helpers.settings import set_root_password + assert set_root_password is runtime.set_root_password + + +@pytest.mark.parametrize("desktop_routes", [False, True]) +def test_protocol_imports_wait_for_request_and_preserve_access_checks(desktop_routes): + subprocess.run( + [sys.executable, "-c", r""" +import asyncio +from contextlib import nullcontext, asynccontextmanager +import importlib +import sys +import threading +from types import SimpleNamespace +import httpx +from helpers import settings +from helpers.ui_server import UiServerRuntime +if sys.argv[1] == 'desktop': + from helpers.virtual_desktop_routes import install_route_hooks + install_route_hooks() + +config = settings.get_default_settings() +config.update(mcp_server_token='test-token', mcp_server_enabled=False, a2a_server_enabled=False) +settings.get_settings = lambda: config +events = [] +@asynccontextmanager +async def monitor_lifespan(app): + events.append('monitor start') + yield + events.append('monitor end') +@asynccontextmanager +async def socket_lifespan(*args): + events.append('socket start') + yield + events.append('socket end') +from helpers import ui_server +ui_server.socket_lifespan = socket_lifespan +app = UiServerRuntime.create().build_asgi_app(SimpleNamespace( + stage=lambda name: nullcontext(), lifespan=lambda: monitor_lifespan)) +assert 'helpers.mcp_server' not in sys.modules +assert 'helpers.fasta2a_server' not in sys.modules +original_import = importlib.import_module +imports = [] +def checked_import(name, *args, **kwargs): + if name in {'helpers.mcp_server', 'helpers.fasta2a_server'}: + assert threading.current_thread() is not threading.main_thread() + imports.append(name) + return original_import(name, *args, **kwargs) +importlib.import_module = checked_import + +async def check(): + messages = [{'type': 'lifespan.startup'}, {'type': 'lifespan.shutdown'}] + replies = [] + async def receive(): + return messages.pop(0) + async def send(message): + replies.append(message['type']) + await app({'type': 'lifespan', 'asgi': {'version': '3.0'}}, receive, send) + assert replies == ['lifespan.startup.complete', 'lifespan.shutdown.complete'] + assert events == ['monitor start', 'socket start', 'socket end', 'monitor end'] + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client: + # Concurrent cold requests share Python's import lock and the existing singleton. + responses = await asyncio.gather(*(client.get('/mcp/t-wrong/http') for _ in range(2))) + assert all(response.status_code == 403 for response in responses) + from helpers.mcp_server import mcp_middleware + from starlette.exceptions import HTTPException + try: + await mcp_middleware(None, None) + except HTTPException as error: + assert error.status_code == 403 + else: + raise AssertionError('Disabled MCP server admitted a request') + response = await client.get('/a2a/t-test-token/.well-known/agent-card.json') + assert response.status_code == 403 + config.update(mcp_server_enabled=True, a2a_server_enabled=True) + assert (await client.get('/mcp/t-wrong/http')).status_code == 403 + assert (await client.get('/a2a/t-wrong/.well-known/agent-card.json')).status_code == 401 + assert set(imports) == {'helpers.mcp_server', 'helpers.fasta2a_server'} +asyncio.run(check()) +""", "desktop" if desktop_routes else "core"], + cwd=PROJECT_ROOT, + check=True, + timeout=60, + ) diff --git a/tests/test_docker_python_runtime.py b/tests/test_docker_python_runtime.py index 473154549..456e83dd4 100644 --- a/tests/test_docker_python_runtime.py +++ b/tests/test_docker_python_runtime.py @@ -173,3 +173,9 @@ def test_shared_numpy_and_filelock_bounds_remain_declared(): requirements = _read(REQUIREMENTS) assert "numpy>=1.26.4,<2" in requirements assert "filelock>=3.20.3" in requirements + + +def test_build_precompiles_with_source_validated_hashes(): + for script in ("install_A0.sh", "prepare_assets.sh"): + content = _read(PROJECT_ROOT / "docker/run/fs/ins" / script) + assert "/usr/local/bin/python -m compileall -q --invalidation-mode checked-hash" in content diff --git a/tests/test_migration_dotenv.py b/tests/test_migration_dotenv.py index 775408710..a9c406fe3 100644 --- a/tests/test_migration_dotenv.py +++ b/tests/test_migration_dotenv.py @@ -5,7 +5,7 @@ import sys import pytest -from helpers import dotenv, files, migration, runtime, settings +from helpers import dotenv, files, migration, runtime @pytest.fixture @@ -174,7 +174,7 @@ def test_prepare_migrates_and_loads_legacy_env_before_writing_root_password(env_ passwords.append(password) dotenv.save_dotenv_value(dotenv.KEY_ROOT_PASSWORD, password) - monkeypatch.setattr(settings, "set_root_password", set_root_password) + monkeypatch.setattr(runtime, "set_root_password", set_root_password) prepare = Path(__file__).resolve().parents[1] / "prepare.py" runpy.run_path(str(prepare), run_name="__main__") migration.migrate_user_data() @@ -194,7 +194,7 @@ def test_prepare_stops_before_password_writes_when_dotenv_is_invalid(env_paths, monkeypatch.setattr(sys, "argv", ["prepare.py"]) monkeypatch.setattr(runtime, "initialize", lambda: None) passwords = [] - monkeypatch.setattr(settings, "set_root_password", passwords.append) + monkeypatch.setattr(runtime, "set_root_password", passwords.append) prepare = Path(__file__).resolve().parents[1] / "prepare.py" with pytest.raises(ValueError, match=r"\.env"):