from __future__ import annotations import os from pathlib import Path import pytest from backend.dto.common import ApiError, ErrorCode from core import runtime_paths from core.config_service import ImageStudioConfig, StorageConfig from core.storage import VfsStorage, assert_storage_roots_contained class _StubConfigService: def __init__(self, config: ImageStudioConfig): self._config = config def load(self) -> ImageStudioConfig: return self._config def _storage_with_temp_root(temp_path: str) -> VfsStorage: config = ImageStudioConfig(storage=StorageConfig(temp_path=temp_path)) return VfsStorage(_StubConfigService(config)) def test_absolute_storage_root_outside_data_root_is_rejected() -> None: """The original chain: repoint a root at the filesystem root, then read anything. ``VfsStorage.resolve_uri`` only checks that the resolved path stays under ``resolved_root`` — which is useless when ``root`` itself is ``/``. """ storage = _storage_with_temp_root(str(Path(Path(__file__).anchor))) with pytest.raises(ApiError) as excinfo: storage.resolve_uri("storage://temp/Windows/System32/drivers/etc/hosts") assert excinfo.value.error_code == ErrorCode.FORBIDDEN assert "escapes the runtime data root" in excinfo.value.message def test_relative_default_roots_are_accepted() -> None: """The shipped defaults must keep working unchanged.""" assert_storage_roots_contained( { "images": "data/images", "temp": "data/temp", "archives": "data/archives", } ) def test_dedicated_absolute_root_is_still_allowed(tmp_path: Path) -> None: """Mounting media on an external volume is a legitimate deployment. The read-time guard only rejects roots that are too broad to be a boundary; containment against the attacker-reachable ``settings/save`` path is enforced by ``SettingsService.validate``. """ assert_storage_roots_contained({"images": str(tmp_path / "media")}) @pytest.mark.parametrize( "system_root", ["C:/Windows"] if os.name == "nt" else ["/etc", "/usr", "/boot"], ) def test_system_directory_root_is_rejected(system_root: str) -> None: """A system directory is never a legitimate media root. Parametrised per-platform because a POSIX-looking ``/etc`` resolves to the drive-relative ``C:\\etc`` on Windows, which is not a system directory. """ with pytest.raises(ApiError): assert_storage_roots_contained({"temp": system_root}) def test_external_roots_env_var_is_an_escape_hatch(monkeypatch: pytest.MonkeyPatch) -> None: """Deployments with a real external mount can opt back in, via env only.""" external = str(Path(Path(__file__).anchor)) with pytest.raises(ApiError): assert_storage_roots_contained({"temp": external}) monkeypatch.setenv(runtime_paths.EXTERNAL_ROOTS_ENV_VAR, "1") assert_storage_roots_contained({"temp": external}) def test_settings_validate_rejects_escaping_storage_path() -> None: """Block the write side too, so the config never reaches a bad state.""" from backend.services.settings_service import _storage_path_errors errors = _storage_path_errors({"temp_path": str(Path(Path(__file__).anchor))}) assert len(errors) == 1 assert errors[0]["field"] == "storage.temp_path" assert _storage_path_errors({"temp_path": "data/temp"}) == [] assert _storage_path_errors({"images_path": ""}) == [] def test_settings_validate_covers_storage_section() -> None: """Regression: validate() used to skip the storage section entirely.""" from backend.services.settings_service import SettingsService service = SettingsService.__new__(SettingsService) result = SettingsService.validate( service, {"config": {"storage": {"temp_path": str(Path(Path(__file__).anchor))}}}, ) assert result["valid"] is False assert any(error["field"] == "storage.temp_path" for error in result["errors"])