Skip to content

Commit bd47f64

Browse files
committed
fix(sandbox): classify a visible collision before staging the payload
The staging write ran before the link script could classify the target, so a target inside an executable but non-writable parent failed on the staging write and the caller saw WorkspaceArchiveWriteError instead of the ApplyPatchDiffError that points it at update_file. It also meant an Add File onto an occupied name uploaded a payload that was then discarded. Probe the target first in both paths, then keep the atomic claim to decide real races. A creator that wins between the probe and the link still loses the name, and its staging entry is still cleaned up. Reported by Codex and by fscfede-beep in #4930.
1 parent 8049c24 commit bd47f64

3 files changed

Lines changed: 76 additions & 8 deletions

File tree

‎src/agents/sandbox/sandboxes/unix_local.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,6 +1035,12 @@ async def write_new_file(
10351035
parent_path = self.normalize_path(requested.parent, for_write=True)
10361036
workspace_path = parent_path / requested.name
10371037
staging_path = parent_path / f".apply-patch-create-{uuid.uuid4().hex}"
1038+
# Classify a visible collision before staging, so a target inside a non-writable
1039+
# parent reports the collision rather than a permission failure from the staging
1040+
# write. os.path.lexists does not follow a symlink at the target name.
1041+
if os.path.lexists(workspace_path):
1042+
raise FileExistsError(str(workspace_path))
1043+
10381044
try:
10391045
# Only the link may report a collision. A parent that is a regular file also
10401046
# raises FileExistsError from mkdir, and reporting that as "the target already

‎src/agents/sandbox/session/base_sandbox_session.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,12 @@
152152
done
153153
""".strip()
154154
_EXCLUSIVE_CREATE_EXISTS_CODE = 13
155+
# Classify an already-visible target before any payload is staged. Without this the
156+
# staging write runs first, so a target inside an executable but non-writable parent
157+
# fails on permissions and the caller sees a write error instead of the collision error
158+
# that tells it to use update_file. The atomic claim below still decides real races.
159+
_TARGET_EXISTS_SCRIPT = 'target="$1"\nif [ -e "$target" ] || [ -L "$target" ]; then exit 13; fi\n'
160+
155161
# ``ln`` claims the target name and fails when that name is already taken. Linking a
156162
# fully written staging file means the content is complete before the name exists, so a
157163
# failed or cancelled upload cannot leave a file behind that holds the name. The leading
@@ -999,6 +1005,12 @@ async def write_new_file(
9991005
staging_path = parent_path / f".apply-patch-create-{uuid.uuid4().hex}"
10001006
staging_arg = sandbox_path_str(staging_path)
10011007

1008+
preflight = await self.exec(
1009+
"sh", "-c", _TARGET_EXISTS_SCRIPT, "sh", path_arg, shell=False, user=user
1010+
)
1011+
if preflight.exit_code == _EXCLUSIVE_CREATE_EXISTS_CODE:
1012+
raise FileExistsError(path_arg)
1013+
10021014
try:
10031015
# Create the parent as the bound user so a fresh nested path is owned the same
10041016
# way the ordinary write path owned it.

‎tests/sandbox/test_unix_local.py‎

Lines changed: 58 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import asyncio
44
import io
5+
import os
56
import shutil
67
import signal
78
import subprocess
@@ -671,14 +672,15 @@ async def test_write_new_file_creates_a_file_and_its_parents(tmp_path: Path) ->
671672
class _ExitCodeUnixLocalSession(UnixLocalSandboxSession):
672673
"""Drives the shared exec-based exclusive create with a chosen exit code."""
673674

674-
def __init__(self, root: Path, exit_code: int) -> None:
675+
def __init__(self, root: Path, exit_code: int, *, preflight_exit_code: int = 0) -> None:
675676
super().__init__(
676677
state=UnixLocalSandboxSessionState(
677678
manifest=Manifest(root=str(root)),
678679
snapshot=NoopSnapshot(id="noop"),
679680
)
680681
)
681682
self._exit_code = exit_code
683+
self._preflight_exit_code = preflight_exit_code
682684
self.exec_commands: list[tuple[str, ...]] = []
683685
self.writes: list[Path] = []
684686
self.removed: list[Path] = []
@@ -690,8 +692,12 @@ async def _exec_internal(
690692
timeout: float | None = None,
691693
) -> ExecResult:
692694
_ = timeout
693-
self.exec_commands.append(tuple(str(part) for part in command))
694-
return ExecResult(stdout=b"", stderr=b"", exit_code=self._exit_code)
695+
parts = tuple(str(part) for part in command)
696+
self.exec_commands.append(parts)
697+
# The collision preflight is the invocation that receives only the target.
698+
is_preflight = not any("ln " in part for part in parts)
699+
code = self._preflight_exit_code if is_preflight else self._exit_code
700+
return ExecResult(stdout=b"", stderr=b"", exit_code=code)
695701

696702
async def write(self, path: Path, data: io.IOBase, *, user: object = None) -> None:
697703
_ = (data, user)
@@ -720,17 +726,32 @@ async def mkdir(
720726

721727
@pytest.mark.asyncio
722728
async def test_write_new_file_with_a_bound_user_reports_an_existing_name(tmp_path: Path) -> None:
723-
"""Exit 13 from the exclusive-create script means the name was already taken."""
724-
session = _ExitCodeUnixLocalSession(tmp_path, exit_code=13)
729+
"""A target that is already visible is rejected before any payload is staged."""
730+
session = _ExitCodeUnixLocalSession(tmp_path, exit_code=0, preflight_exit_code=13)
731+
732+
with pytest.raises(FileExistsError):
733+
await session.write_new_file(
734+
Path("notes.txt"), io.BytesIO(b"payload"), user=User(name="sandbox-user")
735+
)
736+
737+
# No payload bytes were uploaded, so a create onto an occupied name costs one probe
738+
# rather than a full staged write that is then discarded.
739+
assert session.writes == []
740+
assert session.removed == []
741+
742+
743+
@pytest.mark.asyncio
744+
async def test_write_new_file_with_a_bound_user_reports_a_racing_creator(tmp_path: Path) -> None:
745+
"""A creator that wins between the preflight and the link still loses the name."""
746+
session = _ExitCodeUnixLocalSession(tmp_path, exit_code=13, preflight_exit_code=0)
725747

726748
with pytest.raises(FileExistsError):
727749
await session.write_new_file(
728750
Path("notes.txt"), io.BytesIO(b"payload"), user=User(name="sandbox-user")
729751
)
730752

731-
# The payload only ever reached a staging name, and that staging entry is cleaned up,
732-
# so a rejected create leaves nothing behind at the requested name.
733-
assert [path.name for path in session.writes] != ["notes.txt"]
753+
# Here the payload was staged before the race was detected, and the staging entry is
754+
# still cleaned up rather than left in the workspace.
734755
assert all(path.name.startswith(".apply-patch-create-") for path in session.writes)
735756
assert session.removed == session.writes
736757
assert session.made_dirs != []
@@ -927,3 +948,32 @@ async def test_apply_patch_create_accepts_a_destination_at_the_component_limit(
927948
)
928949

929950
assert (tmp_path / long_name).read_text() == "hello"
951+
952+
953+
@pytest.mark.skipif(os.geteuid() == 0, reason="root bypasses directory write permissions")
954+
@pytest.mark.asyncio
955+
async def test_apply_patch_create_reports_collision_inside_a_read_only_parent(
956+
tmp_path: Path,
957+
) -> None:
958+
"""A visible collision must classify as a collision, not as a permission failure.
959+
960+
Staging before classifying meant a target inside an executable but non-writable
961+
parent failed on the staging write, so the caller was told the write failed instead
962+
of being told to use update_file.
963+
"""
964+
session = _exclusive_write_session(tmp_path)
965+
parent = tmp_path / "locked"
966+
parent.mkdir()
967+
target = parent / "notes.txt"
968+
target.write_bytes(b"important\n")
969+
parent.chmod(0o555)
970+
try:
971+
with pytest.raises(ApplyPatchDiffError):
972+
await session.apply_patch(
973+
ApplyPatchOperation(
974+
type="create_file", path="locked/notes.txt", diff="+clobbered\n"
975+
)
976+
)
977+
assert target.read_bytes() == b"important\n"
978+
finally:
979+
parent.chmod(0o755)

0 commit comments

Comments
 (0)