Skip to content

Commit 2f8c9ac

Browse files
fix(sandbox): enforce grants during recursive removal (#5206)
1 parent bb7cd2e commit 2f8c9ac

4 files changed

Lines changed: 251 additions & 25 deletions

File tree

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ def authorize(self, path: Path, *, for_write: bool = False) -> Path:
4141
# Reauthorize resolved paths against captured roots without following new symlinks.
4242
return self._policy.normalize_path(path, for_write=for_write)
4343

44+
def rm(self, path: Path, *, recursive: bool) -> None:
45+
if recursive:
46+
self._policy.validate_recursive_remove(path)
47+
super().rm(path, recursive=recursive)
48+
4449
@contextmanager
4550
def parent(
4651
self, path: Path, *, for_write: bool = False, create_parents: bool = False

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -836,6 +836,7 @@ async def _validate_remote_path_access(
836836
path: Path | str,
837837
*,
838838
for_write: bool = False,
839+
recursive_remove: bool = False,
839840
) -> Path:
840841
"""Validate an SDK file path against the remote sandbox filesystem before IO.
841842
@@ -848,6 +849,7 @@ async def _validate_remote_path_access(
848849
root = path_policy.sandbox_root()
849850
workspace_path = path_policy.normalize_sandbox_path(path, for_write=for_write)
850851
original_path = coerce_posix_path(path)
852+
access_mode = "2" if recursive_remove else "1" if for_write else "0"
851853
helper_path = await self._ensure_runtime_helper_installed(RESOLVE_WORKSPACE_PATH_HELPER)
852854
extra_grant_args = tuple(
853855
arg
@@ -858,7 +860,7 @@ async def _validate_remote_path_access(
858860
str(helper_path),
859861
root.as_posix(),
860862
workspace_path.as_posix(),
861-
"1" if for_write else "0",
863+
access_mode,
862864
*extra_grant_args,
863865
)
864866
result = await self.exec(*command, shell=False)
@@ -873,7 +875,7 @@ async def _validate_remote_path_access(
873875
"resolve_workspace_path",
874876
root.as_posix(),
875877
workspace_path.as_posix(),
876-
"1" if for_write else "0",
878+
access_mode,
877879
*extra_grant_args,
878880
),
879881
context={
@@ -914,7 +916,7 @@ async def _validate_remote_path_access(
914916
"resolve_workspace_path",
915917
root.as_posix(),
916918
workspace_path.as_posix(),
917-
"1" if for_write else "0",
919+
access_mode,
918920
*extra_grant_args,
919921
),
920922
)
@@ -1189,6 +1191,8 @@ async def rm(
11891191

11901192
cmd: list[str] = ["rm"]
11911193
if recursive:
1194+
if any(grant.read_only for grant in self.state.manifest.extra_path_grants):
1195+
await self._validate_remote_path_access(path, for_write=True, recursive_remove=True)
11921196
cmd.append("-rf")
11931197
cmd.extend(["--", sandbox_path_str(path)])
11941198

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

Lines changed: 48 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
max_symlink_depth=64
2121
2222
case "$for_write" in
23-
0|1) ;;
23+
0|1|2) ;; # read, write, recursive removal
2424
*)
25-
printf 'for_write must be 0 or 1: %s\\n' "$for_write" >&2
25+
printf 'for_write must be 0, 1 or 2: %s\\n' "$for_write" >&2
2626
exit 64
2727
;;
2828
esac
@@ -83,10 +83,6 @@
8383
}
8484
8585
resolved_candidate=$(resolve_path "$candidate" 0)
86-
best_grant_root=""
87-
best_grant_original=""
88-
best_grant_read_only="0"
89-
best_grant_len=0
9086
9187
check_root() {
9288
allowed_root="$1"
@@ -134,24 +130,54 @@
134130
esac
135131
}
136132
137-
while [ "$#" -gt 0 ]; do
138-
consider_extra_grant "$1" "$2"
139-
shift 2
140-
done
141-
142-
check_root "$root"
143-
if [ -n "$best_grant_root" ]; then
144-
if [ "$for_write" = "1" ] && [ "$best_grant_read_only" = "1" ]; then
145-
printf 'read-only extra path grant: %s\\nresolved path: %s\\n' \
146-
"$best_grant_original" "$resolved_candidate" >&2
147-
exit 114
133+
authorize_candidate() (
134+
# A subshell keeps each candidate's grant selection independent.
135+
resolved_candidate="$1"
136+
shift
137+
best_grant_root=""
138+
best_grant_original=""
139+
best_grant_read_only="0"
140+
best_grant_len=0
141+
while [ "$#" -gt 0 ]; do
142+
consider_extra_grant "$1" "$2"
143+
shift 2
144+
done
145+
146+
check_root "$root"
147+
if [ -n "$best_grant_root" ]; then
148+
if [ "$for_write" != "0" ] && [ "$best_grant_read_only" = "1" ]; then
149+
printf 'read-only extra path grant: %s\\nresolved path: %s\\n' \
150+
"$best_grant_original" "$resolved_candidate" >&2
151+
exit 114
152+
fi
153+
printf '%s\\n' "$resolved_candidate"
154+
exit 0
148155
fi
149-
printf '%s\\n' "$resolved_candidate"
150-
exit 0
151-
fi
156+
printf 'workspace escape: %s\\n' "$resolved_candidate" >&2
157+
exit 111
158+
)
152159
153-
printf 'workspace escape: %s\\n' "$resolved_candidate" >&2
154-
exit 111
160+
authorize_candidate "$resolved_candidate" "$@" >/dev/null
161+
if [ "$for_write" = "2" ] && [ ! -L "$candidate" ]; then
162+
# rm unlinks a leaf symlink; only a traversed tree needs descendant checks.
163+
grant_root=""
164+
for grant_part in "$@"; do
165+
if [ -z "$grant_root" ]; then
166+
grant_root="$grant_part"
167+
continue
168+
fi
169+
if [ "$grant_part" = "1" ]; then
170+
resolved_grant=$(resolve_path "$grant_root" 0)
171+
case "$resolved_grant" in
172+
"$resolved_candidate"|"$resolved_candidate"/*)
173+
authorize_candidate "$resolved_grant" "$@" >/dev/null
174+
;;
175+
esac
176+
fi
177+
grant_root=""
178+
done
179+
fi
180+
printf '%s\\n' "$resolved_candidate"
155181
""".strip()
156182

157183
_WORKSPACE_FINGERPRINT_SCRIPT: Final[str] = """

‎tests/sandbox/test_recursive_removal_compatibility.py‎

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,204 @@
1111
import pytest
1212

1313
from agents.sandbox import Manifest, SandboxPathGrant
14+
from agents.sandbox.errors import ExecNonZeroError, WorkspaceArchiveWriteError
15+
from agents.sandbox.session import SandboxSession
1416
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
1517

1618
from . import _docker_removal_helpers as removal_helpers
1719

1820
service = removal_helpers.service
1921

2022

23+
def _removal_session(
24+
backend: str, manifest: Manifest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
25+
) -> SandboxSession:
26+
module = pytest.importorskip("agents.sandbox.sandboxes.unix_local", exc_type=ImportError)
27+
from agents.sandbox.snapshot import NoopSnapshot
28+
29+
from .test_runtime_helpers import _install_resolve_helper
30+
from .test_snapshot import _ResumeTrackingSession
31+
32+
if backend == "local":
33+
session = module.UnixLocalSandboxSession(
34+
state=module.UnixLocalSandboxSessionState(
35+
manifest=manifest, snapshot=NoopSnapshot(id="recursive-grants")
36+
)
37+
)
38+
else:
39+
session = _ResumeTrackingSession(workspace_root=Path(manifest.root))
40+
session.state.manifest = manifest
41+
# Execute the shipped resolver and real rm against disposable filesystem data.
42+
monkeypatch.setattr(
43+
session,
44+
"_ensure_runtime_helper_installed",
45+
AsyncMock(return_value=_install_resolve_helper(tmp_path)),
46+
)
47+
monkeypatch.setattr(session, "_validate_path_access", session._validate_remote_path_access)
48+
return SandboxSession(session)
49+
50+
51+
@pytest.mark.asyncio
52+
@pytest.mark.parametrize("backend", ["local", "remote"])
53+
@pytest.mark.parametrize("alias", ["none", "ancestor", "grant"])
54+
async def test_recursive_remove_preserves_nested_read_only_grant(
55+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, backend: str, alias: str
56+
) -> None:
57+
workspace = tmp_path / "workspace"
58+
workspace.mkdir()
59+
external = tmp_path / "external"
60+
target = external / "tree"
61+
protected = target / "protected"
62+
protected.mkdir(parents=True)
63+
sentinel = protected / "config"
64+
sentinel.write_bytes(b"protected")
65+
writable = target / "writable"
66+
writable.mkdir()
67+
sibling = writable / "data"
68+
sibling.write_bytes(b"allowed")
69+
grant_path = protected
70+
remove_path = target
71+
if alias == "ancestor":
72+
link = workspace / "link"
73+
link.symlink_to(external, target_is_directory=True)
74+
remove_path = link / "tree"
75+
elif alias == "grant":
76+
grant_path = tmp_path / "protected-alias"
77+
grant_path.symlink_to(protected, target_is_directory=True)
78+
session = _removal_session(
79+
backend,
80+
Manifest(
81+
root=str(workspace),
82+
extra_path_grants=(
83+
SandboxPathGrant(path=str(external)),
84+
SandboxPathGrant(path=str(grant_path), read_only=True),
85+
),
86+
),
87+
tmp_path,
88+
monkeypatch,
89+
)
90+
91+
with pytest.raises(WorkspaceArchiveWriteError) as direct:
92+
await session.rm(sentinel)
93+
assert direct.value.context["reason"] == "read_only_extra_path_grant"
94+
with pytest.raises((WorkspaceArchiveWriteError, ExecNonZeroError)):
95+
await session.rm(remove_path)
96+
assert sentinel.read_bytes() == b"protected"
97+
with pytest.raises(WorkspaceArchiveWriteError) as recursive:
98+
await session.rm(remove_path, recursive=True)
99+
assert recursive.value.context["reason"] == "read_only_extra_path_grant"
100+
assert sentinel.read_bytes() == b"protected"
101+
assert sibling.read_bytes() == b"allowed"
102+
103+
await session.rm(writable, recursive=True)
104+
assert not writable.exists()
105+
assert sentinel.read_bytes() == b"protected"
106+
107+
108+
@pytest.mark.asyncio
109+
@pytest.mark.parametrize("backend", ["local", "remote"])
110+
@pytest.mark.parametrize("precedence", ["workspace", "first-grant", "nested-writable"])
111+
async def test_recursive_remove_preserves_writable_precedence(
112+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, backend: str, precedence: str
113+
) -> None:
114+
workspace = tmp_path / "workspace"
115+
workspace.mkdir()
116+
external = tmp_path / "external"
117+
target = (workspace if precedence == "workspace" else external) / "tree"
118+
child = target / "child"
119+
child.mkdir(parents=True)
120+
(child / "data").write_bytes(b"allowed")
121+
grants = (
122+
SandboxPathGrant(path=str(external)),
123+
SandboxPathGrant(path=str(child), read_only=True),
124+
)
125+
if precedence == "first-grant":
126+
grants = (SandboxPathGrant(path=str(child)), *grants)
127+
elif precedence == "nested-writable":
128+
grants = (
129+
SandboxPathGrant(path=str(external), read_only=True),
130+
SandboxPathGrant(path=str(target)),
131+
)
132+
session = _removal_session(
133+
backend, Manifest(root=str(workspace), extra_path_grants=grants), tmp_path, monkeypatch
134+
)
135+
136+
await session.rm(target, recursive=True)
137+
138+
assert not target.exists()
139+
assert workspace.exists()
140+
141+
142+
@pytest.mark.asyncio
143+
async def test_remote_recursive_remove_unlinks_leaf_alias_only(
144+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
145+
) -> None:
146+
workspace = tmp_path / "workspace"
147+
workspace.mkdir()
148+
external = tmp_path / "external"
149+
protected = external / "protected"
150+
protected.mkdir(parents=True)
151+
sentinel = protected / "data"
152+
sentinel.write_bytes(b"protected")
153+
link = workspace / "link"
154+
link.symlink_to(external, target_is_directory=True)
155+
session = _removal_session(
156+
"remote",
157+
Manifest(
158+
root=str(workspace),
159+
extra_path_grants=(
160+
SandboxPathGrant(path=str(external)),
161+
SandboxPathGrant(path=str(protected), read_only=True),
162+
),
163+
),
164+
tmp_path,
165+
monkeypatch,
166+
)
167+
168+
await session.rm(link, recursive=True)
169+
170+
assert not link.is_symlink()
171+
assert sentinel.read_bytes() == b"protected"
172+
173+
174+
@pytest.mark.asyncio
175+
async def test_unix_local_recursive_remove_as_user_preserves_nested_grant(
176+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
177+
) -> None:
178+
from agents.sandbox.types import ExecResult
179+
180+
workspace = tmp_path / "workspace"
181+
workspace.mkdir()
182+
external = tmp_path / "external"
183+
protected = external / "protected"
184+
protected.mkdir(parents=True)
185+
sentinel = protected / "data"
186+
sentinel.write_bytes(b"protected")
187+
session = _removal_session(
188+
"local",
189+
Manifest(
190+
root=str(workspace),
191+
extra_path_grants=(
192+
SandboxPathGrant(path=str(external)),
193+
SandboxPathGrant(path=str(protected), read_only=True),
194+
),
195+
),
196+
tmp_path,
197+
monkeypatch,
198+
)
199+
# Only the OS permission probe is simulated; use the real local deletion path.
200+
permission_probe = AsyncMock(return_value=ExecResult(stdout=b"", stderr=b"", exit_code=0))
201+
monkeypatch.setattr(session._inner, "exec", permission_probe)
202+
203+
with pytest.raises(WorkspaceArchiveWriteError) as error:
204+
await session.rm(external, recursive=True, user="example-user")
205+
206+
assert error.value.context["reason"] == "read_only_extra_path_grant"
207+
assert permission_probe.await_args is not None
208+
assert permission_probe.await_args.kwargs["user"] == "example-user"
209+
assert sentinel.read_bytes() == b"protected"
210+
211+
21212
@pytest.mark.asyncio
22213
async def test_default_remote_start_restores_with_unrelated_read_only_grant(
23214
tmp_path: Path, monkeypatch: pytest.MonkeyPatch

0 commit comments

Comments
 (0)