diff --git a/src/agent_env/agents/agents/codex/a2a_server.py b/src/agent_env/agents/agents/codex/a2a_server.py index c8bea369f..08ccbcb01 100644 --- a/src/agent_env/agents/agents/codex/a2a_server.py +++ b/src/agent_env/agents/agents/codex/a2a_server.py @@ -24,10 +24,11 @@ from collections.abc import Awaitable, Callable from contextlib import asynccontextmanager, suppress from datetime import datetime, timezone -from pathlib import Path +from pathlib import Path, PurePosixPath from typing import Any from a2a.types import AgentSkill +from agentenv_protocol import AgentEnvError from agentenv_protocol.a2a_agent import ( AGENT_CONFIG_V1, ATTRIBUTION_PROBE_V1, @@ -302,6 +303,34 @@ def tell(self): return self.written +def _link_restores_inside(root: Path, name: str, linkname: str) -> bool: + """Whether a restore, whichever links it has extracted so far, resolves the link inside the workspace. + + The walk stays lexical and inside the root, and never takes `..` once it has passed a link, so another + link in the tree can only move it deeper into the workspace, never out. A link in a loop is refused too, + since a restore's resolve raises on it. + """ + if linkname.startswith("/"): + return False + parts = list(PurePosixPath(name).parent.parts) + through_link = False + for part in linkname.split("/"): + if part in ("", "."): + continue + if part == "..": + if through_link or not parts: + return False + parts.pop() + continue + parts.append(part) + through_link = through_link or root.joinpath(*parts).is_symlink() + try: + root.joinpath(name).resolve() + except RuntimeError: + return False + return True + + def _build_workspace_archive(path: Path) -> None: if not WORKSPACE_DIR.is_dir(): raise FileNotFoundError(f"workspace directory does not exist: {WORKSPACE_DIR}") @@ -317,22 +346,16 @@ def safe_member(member: tarfile.TarInfo) -> tarfile.TarInfo | None: f"workspace contains unsupported entry: {member.name}" ) if member.issym(): - link = Path(member.linkname) - link_target = ( - link - if link.is_absolute() - else workspace_root / Path(member.name).parent / link - ).resolve() - if ( - link.is_absolute() - or ( - link_target != workspace_root - and workspace_root not in link_target.parents - ) + if not _link_restores_inside( + workspace_root, member.name, member.linkname ): - raise ValueError( - f"workspace contains unsafe link: {member.name}" + # A restore refuses such a link, so the snapshot leaves it out. + logger.warning( + "workspace snapshot skips a link a restore would refuse: %s -> %s", + member.name, + member.linkname, ) + return None member_count += 1 uncompressed_bytes += member.size if member_count > _MAX_SNAPSHOT_MEMBERS: @@ -906,7 +929,11 @@ async def save_snapshot(self, request: ObjectSnapshotSaveRequest) -> dict[str, A # Without a workspace directory this uploads the empty file: agent-env # requires both objects, and a load reads an empty workspace as "conversation only". if workspace_target is not None and WORKSPACE_DIR.is_dir(): - await in_thread_to_its_end(_build_workspace_archive, archive_path) + try: + await in_thread_to_its_end(_build_workspace_archive, archive_path) + except ValueError as e: + logger.warning("workspace snapshot failed: %s", e) + raise AgentEnvError("workspace_unarchivable", str(e), status=422) from e except BaseException: if archive_path is not None: archive_path.unlink(missing_ok=True) diff --git a/tst/unit/agents/codex/test_codex_snapshot_hardening.py b/tst/unit/agents/codex/test_codex_snapshot_hardening.py index 651a2689c..3de61e3ba 100644 --- a/tst/unit/agents/codex/test_codex_snapshot_hardening.py +++ b/tst/unit/agents/codex/test_codex_snapshot_hardening.py @@ -109,16 +109,18 @@ def test_workspace_archive_preserves_safe_symlink(monkeypatch, tmp_path): assert (workspace / "link.txt").readlink() == Path("target.txt") -def test_workspace_archive_rejects_unsafe_symlink(monkeypatch, tmp_path): +def test_workspace_archive_skips_unsafe_symlink(monkeypatch, tmp_path): workspace = tmp_path / "app" workspace.mkdir() (workspace / "link.txt").symlink_to("/etc/passwd") + (workspace / "kept.txt").write_text("kept") + archive = tmp_path / "workspace.tar.gz" monkeypatch.setattr(a2a_server, "WORKSPACE_DIR", workspace) - with pytest.raises(ValueError, match="unsafe link"): - a2a_server._build_workspace_archive( - tmp_path / "workspace.tar.gz" - ) + a2a_server._build_workspace_archive(archive) + + with tarfile.open(archive, "r:gz") as tar: + assert tar.getnames() == ["kept.txt"] def test_workspace_restore_rolls_back_failed_swap(monkeypatch, tmp_path): diff --git a/tst/unit/agents/codex/test_object_transfer.py b/tst/unit/agents/codex/test_object_transfer.py index e6b70c15b..c1a229266 100644 --- a/tst/unit/agents/codex/test_object_transfer.py +++ b/tst/unit/agents/codex/test_object_transfer.py @@ -21,6 +21,7 @@ ) from starlette.exceptions import HTTPException +from agent_env.a2a_agent.protocol import raise_for_extension_status from tst.unit.agents.codex.agent import a2a_server, codex_bridge ORIGIN = "https://bucket.s3.amazonaws.com" @@ -383,6 +384,80 @@ def test_a_save_without_a_workspace_grant_uploads_the_trajectory_only(codex, mon assert set(store.objects) == {"snap/trajectory"} +def _archived(store: FakeStore) -> dict[str, tarfile.TarInfo]: + with tarfile.open(fileobj=io.BytesIO(store.objects["snap/workspace"]), mode="r:gz") as archive: + return {member.name: member for member in archive.getmembers()} + + +def test_a_save_leaves_out_links_that_leave_the_workspace_and_keeps_the_rest(codex, monkeypatch, tmp_path, store): + workspace, _, _ = _codex_home(codex, monkeypatch, tmp_path) + (tmp_path / "outside-tool").write_text("tool") + (workspace / "report" / "tool").symlink_to(tmp_path / "outside-tool") + (workspace / "report" / "escape").symlink_to("../../outside-tool") + (workspace / "report" / "latest").symlink_to("answer.txt") + + saved = _call(codex, "POST", "/ext/snapshot", _save_body()) + + assert saved.status_code == 200 + archived = _archived(store) + assert "report/tool" not in archived and "report/escape" not in archived + assert archived["report/answer.txt"].isfile() + assert archived["report/latest"].issym() and archived["report/latest"].linkname == "answer.txt" + + for name in ("tool", "escape", "latest"): + (workspace / "report" / name).unlink() + loaded = _call(codex, "PUT", "/ext/snapshot", _load_body(store, "trajectory", "workspace")) + + assert loaded.status_code == 200 + assert (workspace / "report" / "latest").read_text() == "done" + assert not (workspace / "report" / "tool").is_symlink() + + +def test_a_link_that_climbs_out_of_another_link_is_left_out_so_the_snapshot_loads( + codex, monkeypatch, tmp_path, store +): + workspace, _, _ = _codex_home(codex, monkeypatch, tmp_path) + (workspace / "deep" / "nest").mkdir(parents=True) + (workspace / "deep" / "nest" / "tool").write_text("tool") + (workspace / "target").write_text("target") + (workspace / "alias").symlink_to(workspace / "deep" / "nest") + (workspace / "kept").symlink_to("alias/../../target") + (workspace / "pkg").symlink_to("deep/nest") + (workspace / "bin").symlink_to("pkg/tool") + (workspace / "loop-a").symlink_to("loop-b") + (workspace / "loop-b").symlink_to("loop-a") + + saved = _call(codex, "POST", "/ext/snapshot", _save_body()) + + assert saved.status_code == 200 + archived = _archived(store) + assert not {"alias", "kept", "loop-a", "loop-b"} & set(archived) + assert archived["pkg"].issym() and archived["bin"].issym() + + loaded = _call(codex, "PUT", "/ext/snapshot", _load_body(store, "trajectory", "workspace")) + + assert loaded.status_code == 200 + assert not (workspace / "kept").is_symlink() + assert (workspace / "bin").read_text() == "tool" + + +def test_a_workspace_over_the_archive_limits_is_refused_with_a_code_the_worker_reports( + codex, monkeypatch, tmp_path, store +): + _codex_home(codex, monkeypatch, tmp_path) + monkeypatch.setattr(a2a_server, "_MAX_SNAPSHOT_MEMBERS", 1) + + response = _call(codex, "POST", "/ext/snapshot", _save_body()) + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "workspace_unarchivable" + assert "too many entries" in response.json()["error"]["message"] + assert not store.objects + with pytest.raises(httpx.HTTPStatusError) as raised: + raise_for_extension_status(response, operation="snapshot save") + assert str(raised.value) == "snapshot save failed with HTTP 422: workspace_unarchivable" + + def test_a_load_without_a_workspace_object_restores_the_conversation_only(codex, monkeypatch, tmp_path, store): workspace, sessions, rollout_bytes = _codex_home(codex, monkeypatch, tmp_path) store.objects["snap/trajectory"] = rollout_bytes