diff --git a/src/backend/api/routes/v1/file_upload.py b/src/backend/api/routes/v1/file_upload.py index e8a35acb..41ed3c1d 100644 --- a/src/backend/api/routes/v1/file_upload.py +++ b/src/backend/api/routes/v1/file_upload.py @@ -57,17 +57,15 @@ def upload_user_file( user_id = str(user.user_id) - public_meta = {} - if user.public_chat_visitor: - from core.chat.public import prepare_visitor_upload - public_meta = prepare_visitor_upload(db, user, chat_id, folder_id) - - # Verify the chat_id already exists in the database (the session may not yet be created at upload time) + # A scoped key's chat id names its own session; create it on the first-turn upload. + upload_meta = {} db_chat_id: Optional[str] = None - if chat_id: - exists = db.query(ChatSession.chat_id).filter(ChatSession.chat_id == chat_id).first() - if exists: - db_chat_id = chat_id + if user.public_chat_visitor or (chat_id and (user.api_key_agent_id or user.api_key_project_id)): + from core.chat.public import prepare_scoped_upload + upload_meta = prepare_scoped_upload(db, user, chat_id, folder_id) + db_chat_id = chat_id + elif chat_id and db.query(ChatSession.chat_id).filter(ChatSession.chat_id == chat_id).first(): + db_chat_id = chat_id artifact_id, retry_meta, existing = prepare_upload( db, @@ -140,7 +138,7 @@ def space_path(name: str) -> str: user_folder_id=db_folder_id, source="user_upload", artifact_id=artifact_id, - extra={**retry_meta, **public_meta}, + extra={**retry_meta, **upload_meta}, ) except HTTPException: db.rollback() diff --git a/src/backend/core/capabilities/skills/publication.py b/src/backend/core/capabilities/skills/publication.py index 41370b2a..1d08fc69 100644 --- a/src/backend/core/capabilities/skills/publication.py +++ b/src/backend/core/capabilities/skills/publication.py @@ -95,6 +95,22 @@ def read_tree(root: Path) -> dict[str, bytes]: return files +def ownership_hint(paths) -> str: + """Say who owns what and how to fix it, so EACCES is actionable from the log.""" + me = f"{os.geteuid()}:{os.getegid()}" if hasattr(os, "geteuid") else "?" + parts = [] + for path in paths: + try: + st = os.lstat(path) + parts.append(f"{path} owner={st.st_uid}:{st.st_gid} mode={st.st_mode & 0o7777:o}") + except OSError as exc: + parts.append(f"{path} ({exc.strerror})") + return ( + f"backend runs as {me}; " + "; ".join(parts) + + f"; fix on the storage host: chown -R {me} (paths are under STORAGE_PATH)" + ) + + def remove_entry(path: Path) -> None: if path.is_symlink() or path.is_file(): path.unlink() @@ -135,7 +151,10 @@ def publish_tree( area = get_sandbox_skills_dir().parent / ".skill-publication" area.mkdir(parents=True, exist_ok=True) target.parent.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix="publish-", dir=area) as tmp: + # The retired tree may hold files this account cannot delete; the new + # tree is already live by then, so a leftover in the staging area + # (outside every mount) must not fail the publish. + with tempfile.TemporaryDirectory(prefix="publish-", dir=area, ignore_cleanup_errors=True) as tmp: stage = Path(tmp) / "new" stage.mkdir() for name, data in files.items(): @@ -145,14 +164,20 @@ def publish_tree( path.chmod(modes.get(name, 0o644)) backup = Path(tmp) / "old" had_old = target.exists() or target.is_symlink() - if had_old: - os.replace(target, backup) try: - os.replace(stage, target) - except BaseException: if had_old: - os.replace(backup, target) - raise + os.replace(target, backup) + try: + os.replace(stage, target) + except BaseException: + if had_old: + os.replace(backup, target) + raise + except PermissionError as exc: + raise PermissionError( + exc.errno, f"{exc.strerror}; {ownership_hint([target.parent, target])}", + str(target), + ) from exc return target diff --git a/src/backend/core/chat/public.py b/src/backend/core/chat/public.py index f429f328..7db45192 100644 --- a/src/backend/core/chat/public.py +++ b/src/backend/core/chat/public.py @@ -136,19 +136,22 @@ def set_visitor_approval_mode(db, user, mode): db.commit() -def prepare_visitor_upload(db, user, chat_id, folder_id=None): +def prepare_scoped_upload(db, user, chat_id, folder_id=None): + """Bind a scoped key's upload to its own session, creating it on the first turn.""" from core.chat.schemas import ChatRequest from core.auth.agent_api import prepare_agent_api_request from core.projects.api import prepare_project_api_request - if not chat_id or folder_id: + if user.public_chat_visitor and (not chat_id or folder_id): raise HTTPException(422, detail="A public upload requires its conversation") body = ChatRequest(chat_id=chat_id, message="Upload", agent_id=user.api_key_agent_id, project_id=user.api_key_project_id) prepare_project_api_request(db, user, body) prepare_agent_api_request(db, user, body) - return {"public_chat_visitor": user.public_chat_visitor, "public_chat_key_id": user.api_key_id, - "agent_api_key_id": user.api_key_id} + meta = {"agent_api_key_id": user.api_key_id} + if user.public_chat_visitor: + meta.update(public_chat_visitor=user.public_chat_visitor, public_chat_key_id=user.api_key_id) + return meta def validate_visitor_attachments(db, user, attachments): diff --git a/src/backend/core/sandbox/__init__.py b/src/backend/core/sandbox/__init__.py index 36033c7f..4b6898f7 100644 --- a/src/backend/core/sandbox/__init__.py +++ b/src/backend/core/sandbox/__init__.py @@ -8,6 +8,8 @@ "ProcessRequest": "protocol", "ProcessResult": "protocol", "SandboxProvider": "protocol", + "SandboxAdmin": "protocol", + "OrdinarySandboxProvider": "protocol", "SandboxCapacityExhausted": "errors", "SandboxConnectError": "errors", "SandboxError": "errors", diff --git a/src/backend/core/sandbox/factory.py b/src/backend/core/sandbox/factory.py index 7a57ccfb..496afa6a 100644 --- a/src/backend/core/sandbox/factory.py +++ b/src/backend/core/sandbox/factory.py @@ -12,12 +12,12 @@ from core.config.settings import settings -from .protocol import SandboxProvider +from .protocol import OrdinarySandboxProvider logger = logging.getLogger(__name__) -def _ordinary_provider() -> SandboxProvider: +def _ordinary_provider() -> OrdinarySandboxProvider: if process_state().provider is not None: return process_state().provider @@ -43,7 +43,7 @@ def _ordinary_provider() -> SandboxProvider: return process_state().provider -def get_sandbox_provider() -> SandboxProvider: +def get_sandbox_provider() -> OrdinarySandboxProvider: from core.sandbox.sessions.router import SessionSandboxRouter return SessionSandboxRouter(_ordinary_provider()) @@ -56,7 +56,7 @@ def reset_provider_cache() -> None: @dataclass class FactoryState: - provider: SandboxProvider | None = None + provider: OrdinarySandboxProvider | None = None _STATE = FactoryState() diff --git a/src/backend/core/sandbox/processes/interactive.py b/src/backend/core/sandbox/processes/interactive.py index ccbd5848..28ac299f 100644 --- a/src/backend/core/sandbox/processes/interactive.py +++ b/src/backend/core/sandbox/processes/interactive.py @@ -89,8 +89,7 @@ async def resolve(): async def launch(provider, installation, module, user_id, chat_id, config): config = { **config, - "_container_isolated": not getattr(provider, "runs_on_host", True) - and getattr(provider, "name", "") in {"opensandbox", "script_runner", "cube"}, + "_container_isolated": not provider.runs_on_host, } runtime = module["resource"] source = (installation.package / runtime["entry"]).resolve() diff --git a/src/backend/core/sandbox/protocol.py b/src/backend/core/sandbox/protocol.py index ddaf22cc..503b84db 100644 --- a/src/backend/core/sandbox/protocol.py +++ b/src/backend/core/sandbox/protocol.py @@ -105,8 +105,14 @@ class SandboxInfo: class SandboxProvider(Protocol): - """Sandbox driver interface. Each provider implementation must declare - ``name`` for logging and health reporting.""" + """Execution contract every sandbox provider satisfies, including the + providers a session route (``register_sandbox_route``) hands out. + + Providers do not subclass this Protocol, so it gives them nothing at + runtime: each provider declares every member itself, and members carry no + defaults here, because a default would only document a value no provider + has. ``tests/sandbox/test_provider_contract.py`` checks the real classes. + """ name: str @@ -114,7 +120,8 @@ class SandboxProvider(Protocol): # 没有别的隔离边界,命令必须带着 ``ProcessRequest.sandbox_launch`` 执行; # False 表示隔离由容器提供,OS 沙箱在那里既无处施加也无意义——调用方据此 # 决定要不要构造 launch,避免出现"构造了但没人施加"的静默失效。 - runs_on_host: bool = False + # 每个实现都要显式声明;调用方直接读,不用 getattr 兜底。 + runs_on_host: bool async def run_to_completion(self, req: ProcessRequest) -> ProcessResult: """Run once and await the final result; internal callers never manage handles.""" @@ -237,10 +244,16 @@ async def touch_session(self, session_id: str) -> bool: async def health(self) -> bool: ... - # ── Read-only admin interface (for the security admin console; all pure - # queries with zero side effects) ────────────── - # Unsupported capabilities should raise SandboxAdminNotSupported, and the - # caller degrades the display accordingly. + +class SandboxAdmin(Protocol): + """Read-only admin view for the security console; all pure queries with + zero side effects. Only the ordinary provider serves it (the console reads + ``get_sandbox_provider()``, whose router forwards these to the ordinary + provider), so session-route providers need not implement it. + + Unsupported capabilities should raise SandboxAdminNotSupported, and the + caller degrades the display accordingly. + """ def admin_capabilities(self) -> "SandboxAdminCapabilities": """Declare how far this provider supports the read-only sandbox @@ -262,3 +275,7 @@ async def admin_get_sandbox(self, sandbox_id: str) -> Optional["SandboxInfo"]: ... def admin_pool_stats(self) -> dict: ... + + +class OrdinarySandboxProvider(SandboxProvider, SandboxAdmin, Protocol): + """What ``SANDBOX_PROVIDER`` selects: execution plus the admin view.""" diff --git a/src/backend/core/sandbox/providers/opensandbox/provider.py b/src/backend/core/sandbox/providers/opensandbox/provider.py index 41acd83c..ec3112c8 100644 --- a/src/backend/core/sandbox/providers/opensandbox/provider.py +++ b/src/backend/core/sandbox/providers/opensandbox/provider.py @@ -44,6 +44,9 @@ class OpenSandboxProvider( _OpenSandboxConnectionMixin, ): name = "opensandbox" + # Commands run inside a separate container; the container is the isolation + # boundary, so there is no host OS sandbox to apply. + runs_on_host = False # 类属性兜底:有测试绕过 __init__ 直接造实例,亲和层读不到就会 AttributeError。 # None 表示未锚定服务循环,装饰器退化为就地执行。 diff --git a/src/backend/core/sandbox/sessions/router.py b/src/backend/core/sandbox/sessions/router.py index 8de0dbbb..b66d4722 100644 --- a/src/backend/core/sandbox/sessions/router.py +++ b/src/backend/core/sandbox/sessions/router.py @@ -10,6 +10,17 @@ def __init__(self, ordinary): def __getattr__(self, name): return getattr(self._ordinary, name) + # Contract data members are named here rather than left to __getattr__, + # so the router visibly carries them and a provider that lacks one fails + # with that provider's name. + @property + def name(self): + return self._ordinary.name + + @property + def runs_on_host(self): + return self._ordinary.runs_on_host + def _for(self, session_id): from core.harness.registry import sandbox_route diff --git a/src/backend/tests/api/test_agent_api_keys.py b/src/backend/tests/api/test_agent_api_keys.py index 4622a076..206c1d8c 100644 --- a/src/backend/tests/api/test_agent_api_keys.py +++ b/src/backend/tests/api/test_agent_api_keys.py @@ -29,7 +29,7 @@ from core.auth.agent_api import begin_agent_api_call, bind_agent_api_run, list_agent_api_calls, prepare_agent_api_request from tests.api.test_agent_api_scope import db, _key, _user from core.chat.schemas import ChatRequest -from tests.db_support import share_session +from tests.db_support import share_bind, share_session def _app(db, monkeypatch, *, user_id="owner", middleware=False): @@ -333,3 +333,71 @@ async def cancel(run_id: str): ) assert response.status_code == 409 assert db.query(AgentApiCallLog).count() == 0 + + +def _upload_client(db, monkeypatch, tmp_path, user): + import core.files.storage + from fastapi.testclient import TestClient + from api.routes.v1 import file_upload + from core.files.storage.factory import process_state + from core.files.storage.local import LocalStorageBackend + + monkeypatch.setenv("STORAGE_PATH", str(tmp_path / "storage")) + storage = LocalStorageBackend() + monkeypatch.setattr(process_state(), "storage_instance", storage) + monkeypatch.setattr(core.files.storage, "get_storage", lambda: storage) + app = FastAPI() + app.include_router(file_upload.router) + app.dependency_overrides[get_current_user] = lambda: user + app.dependency_overrides[get_db] = lambda: db + return TestClient(app) + + +def test_first_turn_upload_creates_the_keys_session_and_is_readable(db, monkeypatch, tmp_path): + from core.auth.agent_api import make_agent_api_scope + from core.db.models import Artifact, ChatSession + from core.llm.api_runtime.agent import artifact_in_scope, parse_api_scope + + key, _ = _key(db) + user = _user(key) + client = _upload_client(db, monkeypatch, tmp_path, user) + response = client.post( + "/v1/file/upload", data={"chat_id": "cn-first"}, + files={"file": ("table.xlsx", io.BytesIO(b"bytes"), "application/octet-stream")}, + ) + assert response.status_code == 200, response.text + file_id = response.json()["file_id"] + db.expire_all() + assert db.get(ChatSession, "cn-first").extra_data["agent_api_scope"]["api_key_id"] == key.id + artifact = db.get(Artifact, file_id) + assert artifact.chat_id == "cn-first" + assert artifact.extra_data["agent_api_key_id"] == key.id + share_bind(monkeypatch, db.bind) + scope = parse_api_scope( + make_agent_api_scope(user, "cn-first"), owner_user_id="owner", + chat_id="cn-first", agent_id=key.agent_id, + ) + assert artifact_in_scope(file_id, scope) + # The first message reuses the session the upload created. + prepare_agent_api_request( + db, user, ChatRequest(chat_id="cn-first", message="Read it", agent_id=key.agent_id) + ) + + +def test_upload_cannot_attach_to_another_scopes_chat(db, monkeypatch, tmp_path): + from core.db.models import Artifact, ChatSession + + db.add(ChatSession(chat_id="owner-chat", user_id="owner", title="Private")) + db.commit() + other, _ = _key(db, agent_id="ua_two") + prepare_agent_api_request( + db, _user(other), ChatRequest(chat_id="other-chat", message="Hi", agent_id="ua_two") + ) + client = _upload_client(db, monkeypatch, tmp_path, _user(_key(db)[0])) + for chat_id in ("owner-chat", "other-chat"): + response = client.post( + "/v1/file/upload", data={"chat_id": chat_id}, + files={"file": ("a.txt", io.BytesIO(b"x"), "text/plain")}, + ) + assert response.status_code == 403 + assert db.query(Artifact).count() == 0 diff --git a/src/backend/tests/api/test_public_chats.py b/src/backend/tests/api/test_public_chats.py index 516f6f9d..14675b51 100644 --- a/src/backend/tests/api/test_public_chats.py +++ b/src/backend/tests/api/test_public_chats.py @@ -217,13 +217,13 @@ def test_public_composer_capabilities_and_uploads(db, kind, resource): ("/v1/tool-approval", "GET"), ("/v1/tool-approval", "PUT"), ("/v1/file/upload", "POST")): assert authenticate_public_chat(request(link["token"], "a" * 48, path, method), db) - metadata = service.prepare_visitor_upload(db, user, "upload-chat") + metadata = service.prepare_scoped_upload(db, user, "upload-chat") assert metadata["public_chat_visitor"] == user.public_chat_visitor assert public_session_matches(db.get(ChatSession, "upload-chat"), user) with pytest.raises(HTTPException): - service.prepare_visitor_upload(db, other, "upload-chat") + service.prepare_scoped_upload(db, other, "upload-chat") with pytest.raises(HTTPException): - service.prepare_visitor_upload(db, user, "another", folder_id="folder") + service.prepare_scoped_upload(db, user, "another", folder_id="folder") file = Artifact(artifact_id="uploaded", user_id="owner", chat_id="upload-chat", filename="hello.txt", mime_type="text/plain", storage_key="hello", type="document", title="Hello", size_bytes=5, extra_data=metadata) diff --git a/src/backend/tests/sandbox/test_provider_contract.py b/src/backend/tests/sandbox/test_provider_contract.py new file mode 100644 index 00000000..6c92eb62 --- /dev/null +++ b/src/backend/tests/sandbox/test_provider_contract.py @@ -0,0 +1,169 @@ +"""Every real sandbox provider satisfies its contract on its own. + +The providers do not subclass the Protocols in ``core.sandbox.protocol``, so +nothing a Protocol says reaches them at runtime: a member the Protocol declares +but a provider forgets fails only at the first call site that reads it, in +production. Call-site tests hand in fake providers, which hid exactly that gap +(the agent API ``runs_on_host`` AttributeError on ``TeamOpenSandboxProvider``). +This test checks the real classes, and finds them by scanning the source, so a +new provider cannot opt out by not being listed. +""" + +from __future__ import annotations + +import ast +import functools +import importlib +from pathlib import Path + +import pytest + +from core.sandbox.protocol import OrdinarySandboxProvider, SandboxAdmin, SandboxProvider + +BACKEND = Path(__file__).resolve().parents[2] +# Packages that hold runtime code; extensions/ ships packaged resources +# (templates with .py names that are not Python) and never defines a provider. +SCANNED = ( + "api", "core", "features", "integrations", "orchestration", "personal_agent", "edition_ee", +) +# Not providers: the router forwards to one. +NOT_PROVIDERS = {("core.sandbox.sessions.router", "SessionSandboxRouter")} +# What ``SANDBOX_PROVIDER`` can select (core.sandbox.factory). These and their +# subclasses also serve the security console's admin view. +ORDINARY_ROOTS = ( + "core.sandbox.providers.opensandbox.provider.OpenSandboxProvider", + "core.sandbox.providers.cube.provider.CubeSandboxProvider", + "core.sandbox.providers.script_runner.provider.ScriptRunnerProvider", +) +# Subclasses that inherit start_process instead of defining it. The edition +# seam resolves to the EE TeamOpenSandboxProvider or the CE overlay class. +SUBCLASS_MODULES = ("core.sandbox.providers.edition", "personal_agent.computer.sandbox") + + +def _members(protocol) -> set[str]: + own = set() + for klass in protocol.__mro__: + if klass is object or klass.__name__ in {"Protocol", "Generic"}: + continue + own |= {n for n in getattr(klass, "__annotations__", {}) if not n.startswith("_")} + own |= {n for n, v in vars(klass).items() if callable(v) and not n.startswith("_")} + return own + + +def _scanned_classes() -> list[tuple[str, str]]: + """Every non-test class that defines ``start_process`` is a provider.""" + found = [] + tops = (BACKEND / top for top in SCANNED) + for path in sorted(p for top in tops if top.is_dir() for p in top.rglob("*.py")): + rel = path.relative_to(BACKEND) + if "__pycache__" in rel.parts: + continue + module = ".".join(rel.with_suffix("").parts) + for node in ast.parse(path.read_text(encoding="utf-8")).body: + if not isinstance(node, ast.ClassDef) or (module, node.name) in NOT_PROVIDERS: + continue + if isinstance(node, ast.ClassDef) and any( + isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) + and item.name == "start_process" + for item in node.body + ): + found.append((module, node.name)) + return found + + +def _subclasses(cls): + for sub in cls.__subclasses__(): + yield sub + yield from _subclasses(sub) + + +def _qualname(cls) -> str: + return f"{cls.__module__}.{cls.__qualname__}" + + +@functools.cache +def _providers() -> dict[str, type]: + roots = [ + getattr(importlib.import_module(m), n) + for m, n in _scanned_classes() + if m != "core.sandbox.protocol" + ] + for module in SUBCLASS_MODULES: + importlib.import_module(module) + found = {} + for root in roots: + for cls in (root, *_subclasses(root)): + if not cls.__module__.startswith("tests"): + found[_qualname(cls)] = cls + return found + + +def _is_ordinary(cls) -> bool: + return any(_qualname(k) in ORDINARY_ROOTS for k in cls.__mro__) + + +def test_scan_finds_the_known_providers(): + names = set(_providers()) + # CE ships without the Cube provider; require only the roots it has. + shipped = { + root for root in ORDINARY_ROOTS + if (BACKEND / (root.rsplit(".", 1)[0].replace(".", "/") + ".py")).is_file() + } + assert "core.sandbox.providers.opensandbox.provider.OpenSandboxProvider" in shipped + assert shipped <= names + from core.sandbox.providers.edition import PersistentSandboxProvider + + assert { + "features.evaluation.sandbox_provider.provider.EvaluationSandboxProvider", + "personal_agent.computer.sandbox.PersonalSandboxProvider", + _qualname(PersistentSandboxProvider), + } <= names + + +@pytest.mark.parametrize("qualname", sorted(_providers())) +def test_provider_declares_its_whole_contract(qualname): + cls = _providers()[qualname] + contract = OrdinarySandboxProvider if _is_ordinary(cls) else SandboxProvider + missing = sorted(m for m in _members(contract) if not hasattr(cls, m)) + assert not missing, f"{qualname} does not declare {missing}" + + +@pytest.mark.parametrize("qualname", sorted(_providers())) +def test_runs_on_host_is_an_explicit_bool(qualname): + # Whether a command runs without a container boundary is declared by the + # provider, never inferred from a fallback at the call site. + assert isinstance(_providers()[qualname].runs_on_host, bool) + + +def test_protocols_carry_no_defaults(): + # A Protocol default never reaches a class that does not subclass the + # Protocol, so it would only document a value no provider has. + for protocol in (SandboxProvider, SandboxAdmin, OrdinarySandboxProvider): + data = [n for n in protocol.__annotations__ if not n.startswith("_")] + assert [n for n in data if n in vars(protocol)] == [] + + +def test_router_carries_the_ordinary_data_members(): + from core.sandbox.sessions.router import SessionSandboxRouter + + class Ordinary: + name = "opensandbox" + runs_on_host = False + + router = SessionSandboxRouter(Ordinary()) + assert (router.name, router.runs_on_host) == ("opensandbox", False) + + +def test_agent_api_accepts_the_real_persistent_provider(monkeypatch): + # The production path that raised AttributeError: the agent API sandbox + # gate reads runs_on_host through the router on the real provider the + # factory builds for SANDBOX_PROVIDER=opensandbox (EE: TeamOpenSandboxProvider). + import core.sandbox as sandbox + from core.llm.api_runtime import agent_tools + from core.sandbox.providers.edition import PersistentSandboxProvider + from core.sandbox.sessions.router import SessionSandboxRouter + + router = SessionSandboxRouter(object.__new__(PersistentSandboxProvider)) + monkeypatch.setattr(sandbox, "get_sandbox_provider", lambda: router) + monkeypatch.setenv("SANDBOX_TOOLS_ENABLED", "true") + assert agent_tools._provider() is router diff --git a/src/backend/tests/skills/test_skill_publication_ownership.py b/src/backend/tests/skills/test_skill_publication_ownership.py new file mode 100644 index 00000000..8e6337a7 --- /dev/null +++ b/src/backend/tests/skills/test_skill_publication_ownership.py @@ -0,0 +1,77 @@ +"""Publication against skill directories this account cannot write. + +On a deployed storage volume a user view (``sandbox_skills_u/``) can be +created by another account, e.g. a container runtime that binds a missing +source creates it as root. That is fixed on the storage host, so publication +only has to say how; a mode without write access stands in for a foreign +owner here (the kernel answers both with EACCES). +""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.skipif( + not hasattr(os, "geteuid") or os.geteuid() == 0, + reason="root bypasses directory permissions", +) + + +@pytest.fixture +def skills(tmp_path, monkeypatch): + monkeypatch.setenv("SANDBOX_SKILLS_DIR", str(tmp_path / "sandbox_skills")) + monkeypatch.delenv("HUGAGENT_CAPS_ROOT", raising=False) + locked = [] + yield tmp_path, locked + for path in locked: # let pytest remove the tree + for p in [path, *path.rglob("*")]: + if p.is_dir() and not p.is_symlink(): + p.chmod(0o755) + + +def _lock(locked, path: Path): + path.chmod(0o555) + locked.append(path) + + +def _user_view(user_id="alice") -> Path: + from core.capabilities.skills.config import get_user_skills_dir + + view = get_user_skills_dir(user_id) + view.mkdir(parents=True, exist_ok=True) + return view + + +def test_permission_error_names_owner_and_fix(skills): + from core.capabilities.skills.publication import publish_tree + + root, locked = skills + view = _user_view() + _lock(locked, view) + + with pytest.raises(PermissionError) as info: + publish_tree(view / "sample", {"SKILL.md": b"v1"}) + + message = str(info.value) + assert f"backend runs as {os.geteuid()}:{os.getegid()}" in message + assert f"{view} owner=" in message + assert "chown -R" in message + + +def test_undeletable_retired_tree_does_not_fail_republish(skills): + from core.capabilities.skills.publication import publish_tree + + root, locked = skills + view = _user_view() + target = publish_tree(view / "sample", {"SKILL.md": b"v1", "docs/a.md": b"a"}) + # The old tree moves into the staging area, where its files cannot be removed. + _lock(locked, target / "docs") + locked.append(root / ".skill-publication") + + publish_tree(view / "sample", {"SKILL.md": b"v2"}) + + assert (view / "sample" / "SKILL.md").read_bytes() == b"v2" + assert not (view / "sample" / "docs").exists() diff --git a/src/backend/tests/test_browser_prewarm.py b/src/backend/tests/test_browser_prewarm.py index ae67c390..a083f4d7 100644 --- a/src/backend/tests/test_browser_prewarm.py +++ b/src/backend/tests/test_browser_prewarm.py @@ -203,7 +203,7 @@ async def start(req, yield_time_ms): return {"session_id": "owned-start", "output": ""} async def write(handle, **kwargs): cleaned.append((handle, kwargs["chars"])) - provider = SimpleNamespace(start_process=start, write_stdin=write) + provider = SimpleNamespace(runs_on_host=False, start_process=start, write_stdin=write) monkeypatch.setattr(confinement, "launch_policy", lambda *a: {}) task = asyncio.create_task(interactive.launch(provider, selected, module, "owner", "chat", {"token": "fixture-only"})) await entered.wait()