|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import inspect |
| 4 | +import os |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +import pytest |
| 10 | + |
| 11 | +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="Unix only") |
| 12 | + |
| 13 | + |
| 14 | +def _fifo_probe(root: str, operation: str, replacement: str) -> None: |
| 15 | + """Run public file operations in a child so blocking-open regressions are bounded.""" |
| 16 | + import asyncio |
| 17 | + import io |
| 18 | + import os |
| 19 | + import pwd |
| 20 | + import subprocess |
| 21 | + import sys |
| 22 | + from pathlib import Path |
| 23 | + from unittest.mock import patch |
| 24 | + |
| 25 | + from agents.sandbox.apply_patch import WorkspaceEditor |
| 26 | + from agents.sandbox.errors import WorkspaceArchiveReadError, WorkspaceArchiveWriteError |
| 27 | + from agents.sandbox.manifest import Manifest |
| 28 | + from agents.sandbox.sandboxes.unix_local import ( |
| 29 | + UnixLocalSandboxSession, |
| 30 | + UnixLocalSandboxSessionState, |
| 31 | + ) |
| 32 | + from agents.sandbox.snapshot import NoopSnapshot |
| 33 | + |
| 34 | + workspace = Path(root).resolve() |
| 35 | + target = workspace / "pipe" |
| 36 | + if replacement == "swap": |
| 37 | + target.write_bytes(b"original") |
| 38 | + else: |
| 39 | + os.mkfifo(target) |
| 40 | + session = UnixLocalSandboxSession( |
| 41 | + state=UnixLocalSandboxSessionState( |
| 42 | + manifest=Manifest(root=str(workspace)), snapshot=NoopSnapshot(id="fifo-probe") |
| 43 | + ) |
| 44 | + ) |
| 45 | + real_open = os.open |
| 46 | + real_run = subprocess.run |
| 47 | + username = pwd.getpwuid(os.geteuid()).pw_name |
| 48 | + peer: int | None = None |
| 49 | + rejected_fd: int | None = None |
| 50 | + |
| 51 | + def swapping_open(path, flags, *args, **kwargs): |
| 52 | + nonlocal peer, rejected_fd |
| 53 | + if path == "pipe": |
| 54 | + target.rename(workspace / "original") |
| 55 | + os.mkfifo(target) |
| 56 | + # A peer makes the writable FIFO open succeed, so fstat must reject it |
| 57 | + # without writing any bytes. Without O_NONBLOCK, the no-peer cases hang. |
| 58 | + peer = real_open(target, os.O_RDWR | os.O_NONBLOCK) |
| 59 | + rejected_fd = real_open(path, flags, *args, **kwargs) |
| 60 | + return rejected_fd |
| 61 | + return real_open(path, flags, *args, **kwargs) |
| 62 | + |
| 63 | + def run_as_current_user(command, **kwargs): |
| 64 | + # Exercise the shipped worker and public dispatcher without requiring sudo. |
| 65 | + # The requested identity is already this process's effective identity. |
| 66 | + assert command[1:4] == ["-u", username, "--"] |
| 67 | + assert command[4:8] == ["python3", "-I", "-S", "-c"] |
| 68 | + return real_run([sys.executable, *command[5:]], timeout=5, **kwargs) |
| 69 | + |
| 70 | + async def exercise(): |
| 71 | + try: |
| 72 | + if operation == "read": |
| 73 | + with await session.read(Path("pipe")): |
| 74 | + raise AssertionError("FIFO returned as a readable file") |
| 75 | + elif operation == "delete": |
| 76 | + await WorkspaceEditor(session).apply_patch({"type": "delete_file", "path": "pipe"}) |
| 77 | + else: |
| 78 | + payload = io.BytesIO(b"payload") |
| 79 | + with ( |
| 80 | + patch("shutil.which", return_value="/usr/bin/sudo"), |
| 81 | + patch("subprocess.run", side_effect=run_as_current_user), |
| 82 | + ): |
| 83 | + await session.write( |
| 84 | + Path("pipe"), payload, user=username if operation == "user-write" else None |
| 85 | + ) |
| 86 | + assert not payload.closed |
| 87 | + except (WorkspaceArchiveReadError, WorkspaceArchiveWriteError): |
| 88 | + return |
| 89 | + raise AssertionError("FIFO operation unexpectedly succeeded") |
| 90 | + |
| 91 | + try: |
| 92 | + with patch("os.open", side_effect=swapping_open if replacement == "swap" else real_open): |
| 93 | + asyncio.run(exercise()) |
| 94 | + assert target.is_fifo() |
| 95 | + if replacement == "swap": |
| 96 | + assert (workspace / "original").read_bytes() == b"original" |
| 97 | + assert rejected_fd is not None |
| 98 | + try: |
| 99 | + os.fstat(rejected_fd) |
| 100 | + except OSError: |
| 101 | + pass |
| 102 | + else: |
| 103 | + raise AssertionError("Rejected FIFO descriptor leaked") |
| 104 | + assert peer is not None |
| 105 | + try: |
| 106 | + os.read(peer, 1) |
| 107 | + except BlockingIOError: |
| 108 | + pass |
| 109 | + else: |
| 110 | + raise AssertionError("Rejected FIFO received payload") |
| 111 | + finally: |
| 112 | + if peer is not None: |
| 113 | + os.close(peer) |
| 114 | + |
| 115 | + |
| 116 | +@pytest.mark.parametrize("operation", ["read", "write", "user-write", "delete"]) |
| 117 | +def test_public_file_operations_reject_peerless_fifo(tmp_path: Path, operation: str) -> None: |
| 118 | + source = inspect.getsource(_fifo_probe) + '\n_fifo_probe(*__import__("sys").argv[1:])' |
| 119 | + result = subprocess.run( |
| 120 | + [sys.executable, "-c", source, str(tmp_path), operation, "stable"], |
| 121 | + capture_output=True, |
| 122 | + timeout=15, |
| 123 | + ) |
| 124 | + assert result.returncode == 0, result.stderr.decode() |
| 125 | + |
| 126 | + |
| 127 | +@pytest.mark.parametrize("operation", ["read", "write"]) |
| 128 | +def test_fifo_replacement_is_rejected_before_io(tmp_path: Path, operation: str) -> None: |
| 129 | + source = inspect.getsource(_fifo_probe) + '\n_fifo_probe(*__import__("sys").argv[1:])' |
| 130 | + result = subprocess.run( |
| 131 | + [sys.executable, "-c", source, str(tmp_path), operation, "swap"], |
| 132 | + capture_output=True, |
| 133 | + timeout=15, |
| 134 | + ) |
| 135 | + assert result.returncode == 0, result.stderr.decode() |
| 136 | + |
| 137 | + |
| 138 | +@pytest.mark.asyncio |
| 139 | +async def test_regular_write_preserves_inode_permissions_and_umask(tmp_path: Path) -> None: |
| 140 | + import io |
| 141 | + |
| 142 | + from .test_unix_local_file_io import _session |
| 143 | + |
| 144 | + session = _session(tmp_path) |
| 145 | + target = tmp_path / "file" |
| 146 | + target.write_bytes(b"long original contents") |
| 147 | + alias = tmp_path / "hard-link" |
| 148 | + os.link(target, alias) |
| 149 | + target.chmod(0o200) |
| 150 | + before = target.stat() |
| 151 | + tmp_path.chmod(0o500) |
| 152 | + try: |
| 153 | + await session.write(Path("file"), io.BytesIO(b"new")) |
| 154 | + after = target.stat() |
| 155 | + assert (after.st_ino, after.st_uid, after.st_gid, after.st_mode) == ( |
| 156 | + before.st_ino, |
| 157 | + before.st_uid, |
| 158 | + before.st_gid, |
| 159 | + before.st_mode, |
| 160 | + ) |
| 161 | + finally: |
| 162 | + tmp_path.chmod(0o700) |
| 163 | + target.chmod(0o600) |
| 164 | + assert alias.read_bytes() == b"new" |
| 165 | + |
| 166 | + previous_umask = os.umask(0o077) |
| 167 | + try: |
| 168 | + await session.write(Path("new"), io.BytesIO(b"private")) |
| 169 | + finally: |
| 170 | + os.umask(previous_umask) |
| 171 | + assert (tmp_path / "new").stat().st_mode & 0o777 == 0o600 |
| 172 | + |
| 173 | + |
| 174 | +@pytest.mark.asyncio |
| 175 | +@pytest.mark.parametrize("kind", ["socket", "device"]) |
| 176 | +async def test_stable_special_files_are_rejected_without_io_open( |
| 177 | + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str |
| 178 | +) -> None: |
| 179 | + import io |
| 180 | + import socket |
| 181 | + import tempfile |
| 182 | + |
| 183 | + from agents.sandbox.errors import WorkspaceArchiveReadError, WorkspaceArchiveWriteError |
| 184 | + from agents.sandbox.manifest import SandboxPathGrant |
| 185 | + |
| 186 | + from .test_unix_local_file_io import _session |
| 187 | + |
| 188 | + with tempfile.TemporaryDirectory() as short_dir, socket.socket(socket.AF_UNIX) as sock: |
| 189 | + # Keep the Unix socket address short enough on macOS. |
| 190 | + root = Path(short_dir) |
| 191 | + target = root / "s" if kind == "socket" else Path("/dev/null") |
| 192 | + if kind == "socket": |
| 193 | + sock.bind(str(target)) |
| 194 | + session = _session(root, grants=(SandboxPathGrant(path="/dev/null"),)) |
| 195 | + real_open = os.open |
| 196 | + |
| 197 | + def guarded_open(path, flags, *args, **kwargs): |
| 198 | + assert path != target.name, "special-file leaf must not be opened" |
| 199 | + return real_open(path, flags, *args, **kwargs) |
| 200 | + |
| 201 | + monkeypatch.setattr(os, "open", guarded_open) |
| 202 | + with pytest.raises(WorkspaceArchiveReadError): |
| 203 | + await session.read(target) |
| 204 | + with pytest.raises(WorkspaceArchiveWriteError): |
| 205 | + await session.write(target, io.BytesIO(b"payload")) |
| 206 | + |
| 207 | + |
| 208 | +def _lease_client(root: str, operation: str) -> None: |
| 209 | + import asyncio |
| 210 | + import errno |
| 211 | + import io |
| 212 | + from pathlib import Path |
| 213 | + |
| 214 | + from agents.sandbox.errors import WorkspaceArchiveReadError, WorkspaceArchiveWriteError |
| 215 | + from agents.sandbox.manifest import Manifest |
| 216 | + from agents.sandbox.sandboxes.unix_local import ( |
| 217 | + UnixLocalSandboxSession, |
| 218 | + UnixLocalSandboxSessionState, |
| 219 | + ) |
| 220 | + from agents.sandbox.snapshot import NoopSnapshot |
| 221 | + |
| 222 | + session = UnixLocalSandboxSession( |
| 223 | + state=UnixLocalSandboxSessionState( |
| 224 | + manifest=Manifest(root=root), snapshot=NoopSnapshot(id="lease-probe") |
| 225 | + ) |
| 226 | + ) |
| 227 | + |
| 228 | + async def exercise(): |
| 229 | + try: |
| 230 | + if operation == "read": |
| 231 | + with await session.read(Path("file")): |
| 232 | + pass |
| 233 | + else: |
| 234 | + await session.write(Path("file"), io.BytesIO(b"updated")) |
| 235 | + except (WorkspaceArchiveReadError, WorkspaceArchiveWriteError) as exc: |
| 236 | + assert isinstance(exc.__cause__, OSError) |
| 237 | + assert exc.__cause__.errno == errno.EWOULDBLOCK |
| 238 | + return |
| 239 | + raise AssertionError("A conflicting lease must be rejected") |
| 240 | + |
| 241 | + asyncio.run(exercise()) |
| 242 | + |
| 243 | + |
| 244 | +@pytest.mark.skipif(sys.platform != "linux", reason="Linux file leases") |
| 245 | +@pytest.mark.parametrize("operation", ["read", "write"]) |
| 246 | +def test_regular_file_lease_rejected(tmp_path: Path, operation: str) -> None: |
| 247 | + import fcntl |
| 248 | + import signal |
| 249 | + |
| 250 | + target = tmp_path / "file" |
| 251 | + target.write_bytes(b"original") |
| 252 | + notified = False |
| 253 | + |
| 254 | + def on_lease_break(_signum, _frame): |
| 255 | + nonlocal notified |
| 256 | + notified = True |
| 257 | + |
| 258 | + previous_handler = signal.signal(signal.SIGIO, on_lease_break) |
| 259 | + source = inspect.getsource(_lease_client) + '\n_lease_client(*__import__("sys").argv[1:])' |
| 260 | + try: |
| 261 | + with target.open("r+b") as lease: |
| 262 | + fcntl.fcntl(lease, fcntl.F_SETLEASE, fcntl.F_WRLCK) |
| 263 | + with subprocess.Popen( |
| 264 | + [sys.executable, "-c", source, str(tmp_path), operation], |
| 265 | + stdout=subprocess.PIPE, |
| 266 | + stderr=subprocess.PIPE, |
| 267 | + ) as client: |
| 268 | + try: |
| 269 | + # Keep the lease held until the public operation has failed. An |
| 270 | + # external watchdog bounds regressions without blocking pytest. |
| 271 | + _, stderr = client.communicate(timeout=10) |
| 272 | + assert client.returncode == 0, stderr.decode() |
| 273 | + assert notified, "Client did not request a lease break" |
| 274 | + finally: |
| 275 | + if client.poll() is None: |
| 276 | + client.kill() |
| 277 | + client.wait() |
| 278 | + fcntl.fcntl(lease, fcntl.F_SETLEASE, fcntl.F_UNLCK) |
| 279 | + finally: |
| 280 | + signal.signal(signal.SIGIO, previous_handler) |
| 281 | + assert target.read_bytes() == b"original" |
| 282 | + |
| 283 | + |
| 284 | +@pytest.mark.asyncio |
| 285 | +@pytest.mark.parametrize("operation", ["read", "write"]) |
| 286 | +async def test_conflicting_lease_is_not_retried( |
| 287 | + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, operation: str |
| 288 | +) -> None: |
| 289 | + import errno |
| 290 | + import io |
| 291 | + from types import SimpleNamespace |
| 292 | + |
| 293 | + from agents.sandbox.errors import WorkspaceArchiveReadError, WorkspaceArchiveWriteError |
| 294 | + from agents.sandbox.sandboxes import _unix_local_file_ops as file_ops |
| 295 | + |
| 296 | + from .test_unix_local_file_io import _session |
| 297 | + |
| 298 | + target = tmp_path / "file" |
| 299 | + target.write_bytes(b"original") |
| 300 | + real_open = os.open |
| 301 | + attempts = 0 |
| 302 | + |
| 303 | + def leased_open(path, flags, *args, **kwargs): |
| 304 | + nonlocal attempts |
| 305 | + if path == "file": |
| 306 | + attempts += 1 |
| 307 | + assert attempts == 1, "A conflicting lease must not be retried" |
| 308 | + raise BlockingIOError(errno.EWOULDBLOCK, "Conflicting lease") |
| 309 | + return real_open(path, flags, *args, **kwargs) |
| 310 | + |
| 311 | + monkeypatch.setattr(file_ops, "sys", SimpleNamespace(platform="linux")) |
| 312 | + monkeypatch.setattr(os, "open", leased_open) |
| 313 | + payload = io.BytesIO(b"updated") |
| 314 | + error = WorkspaceArchiveReadError if operation == "read" else WorkspaceArchiveWriteError |
| 315 | + with pytest.raises(error) as caught: |
| 316 | + if operation == "read": |
| 317 | + await _session(tmp_path).read(Path("file")) |
| 318 | + else: |
| 319 | + await _session(tmp_path).write(Path("file"), payload) |
| 320 | + assert isinstance(caught.value.__cause__, OSError) |
| 321 | + assert caught.value.__cause__.errno == errno.EWOULDBLOCK |
| 322 | + assert attempts == 1 |
| 323 | + assert not payload.closed |
| 324 | + assert payload.tell() == 0 |
| 325 | + assert target.read_bytes() == b"original" |
0 commit comments