From 9e84c572f66776a159e19e754e9080d4348b1a36 Mon Sep 17 00:00:00 2001 From: Andrew Park Date: Mon, 23 Nov 2026 12:11:13 -0800 Subject: [PATCH 1/2] fix(codex): a snapshot leaves out links that leave the workspace, and names why an archive fails A save failed with a bare HTTP 500 whenever the workspace held a symlink that is absolute or resolves outside it, such as an agent linking a tool from elsewhere in the container into the workspace. The worker logged only the status, so the cause was invisible. The archive now skips such a link and logs a warning naming it; a restore refuses those links anyway. Links inside the workspace are kept. Every other archive failure (an unsupported entry, too many entries, a size limit) answers 422 with the code workspace_unarchivable, which the worker reports as "snapshot save failed with HTTP 422: workspace_unarchivable". --- .../agents/agents/codex/a2a_server.py | 15 ++++-- .../codex/test_codex_snapshot_hardening.py | 12 +++-- tst/unit/agents/codex/test_object_transfer.py | 47 +++++++++++++++++++ 3 files changed, 66 insertions(+), 8 deletions(-) diff --git a/src/agent_env/agents/agents/codex/a2a_server.py b/src/agent_env/agents/agents/codex/a2a_server.py index c8bea369f..8faac8e56 100644 --- a/src/agent_env/agents/agents/codex/a2a_server.py +++ b/src/agent_env/agents/agents/codex/a2a_server.py @@ -28,6 +28,7 @@ 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, @@ -330,9 +331,13 @@ def safe_member(member: tarfile.TarInfo) -> tarfile.TarInfo | None: and workspace_root not in link_target.parents ) ): - 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 that leaves the workspace: %s -> %s", + member.name, + member.linkname, ) + return None member_count += 1 uncompressed_bytes += member.size if member_count > _MAX_SNAPSHOT_MEMBERS: @@ -906,7 +911,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..a3d97f251 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,52 @@ 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_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 From 87138ba45ad20921a616f25269bff4a608742aa4 Mon Sep 17 00:00:00 2001 From: Andrew Park Date: Mon, 23 Nov 2026 12:11:13 -0800 Subject: [PATCH 2/2] fix(codex): a snapshot keeps only links a restore accepts A save decided whether to keep a relative link by resolving it in the live workspace, which still holds the links the save leaves out. A link that climbs out of another link, such as `kept -> alias/../../target` beside an absolute `alias`, was kept, and the restore then refused the whole archive. The save now walks each link's target lexically from the link's folder. It keeps the link only when the walk never leaves the workspace and never takes `..` after passing another link, so no other link, kept or left out, extracted yet or not, can move the restore's resolve outside. A link in a loop is left out too, since the restore's resolve raises on it. Links that only descend through another link, as package managers' bin links do, are still kept. --- .../agents/agents/codex/a2a_server.py | 46 +++++++++++++------ tst/unit/agents/codex/test_object_transfer.py | 28 +++++++++++ 2 files changed, 60 insertions(+), 14 deletions(-) diff --git a/src/agent_env/agents/agents/codex/a2a_server.py b/src/agent_env/agents/agents/codex/a2a_server.py index 8faac8e56..08ccbcb01 100644 --- a/src/agent_env/agents/agents/codex/a2a_server.py +++ b/src/agent_env/agents/agents/codex/a2a_server.py @@ -24,7 +24,7 @@ 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 @@ -303,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}") @@ -318,22 +346,12 @@ 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 ): # A restore refuses such a link, so the snapshot leaves it out. logger.warning( - "workspace snapshot skips a link that leaves the workspace: %s -> %s", + "workspace snapshot skips a link a restore would refuse: %s -> %s", member.name, member.linkname, ) diff --git a/tst/unit/agents/codex/test_object_transfer.py b/tst/unit/agents/codex/test_object_transfer.py index a3d97f251..c1a229266 100644 --- a/tst/unit/agents/codex/test_object_transfer.py +++ b/tst/unit/agents/codex/test_object_transfer.py @@ -413,6 +413,34 @@ def test_a_save_leaves_out_links_that_leave_the_workspace_and_keeps_the_rest(cod 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 ):