cocoonstack-sandbox 0.1.36__tar.gz → 0.1.37__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/PKG-INFO +1 -1
  2. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/client.py +1 -4
  3. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/conn.py +17 -4
  4. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/sandbox.py +39 -28
  5. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonstack_sandbox.egg-info/PKG-INFO +1 -1
  6. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/pyproject.toml +1 -1
  7. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_hardening.py +107 -0
  8. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_stream.py +59 -5
  9. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/LICENSE +0 -0
  10. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/README.md +0 -0
  11. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/__init__.py +0 -0
  12. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/checkpoint.py +0 -0
  13. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/endpoint.py +0 -0
  14. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/errors.py +0 -0
  15. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/frames.py +0 -0
  16. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/py.typed +0 -0
  17. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/template.py +0 -0
  18. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonsandbox/volumes.py +0 -0
  19. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonstack_sandbox.egg-info/SOURCES.txt +0 -0
  20. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonstack_sandbox.egg-info/dependency_links.txt +0 -0
  21. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/cocoonstack_sandbox.egg-info/top_level.txt +0 -0
  22. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/setup.cfg +0 -0
  23. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_checkpoint.py +0 -0
  24. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_client.py +0 -0
  25. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_endpoint.py +0 -0
  26. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_fault_matrix.py +0 -0
  27. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_fixtures.py +0 -0
  28. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_frames.py +0 -0
  29. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_keepalive.py +0 -0
  30. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_packaging.py +0 -0
  31. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_proc.py +0 -0
  32. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_proxy.py +0 -0
  33. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_upgrade.py +0 -0
  34. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_volume_controller.py +0 -0
  35. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_volumes.py +0 -0
  36. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.37}/tests/test_wire_binding.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.36
3
+ Version: 0.1.37
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.10
@@ -38,10 +38,7 @@ class Client(_Closeable):
38
38
  ssl_context: ssl.SSLContext | None = None,
39
39
  keep_alive: float = 30.0,
40
40
  ) -> None:
41
- """keep_alive parks idle connections, 0 dials per call; a parked relay one holds the sandbox's idle clock.
42
-
43
- ssl_context is set to offer ALPN http/1.1, which the relay upgrade needs; pass a dedicated context.
44
- """
41
+ """keep_alive parks idle connections (0 dials per call); ssl_context is set to offer ALPN http/1.1."""
45
42
  endpoint = _endpoint_url(addr.strip())
46
43
  self.addr = endpoint.geturl().removeprefix("http://")
47
44
  self._scheme = endpoint.scheme
@@ -18,6 +18,7 @@ from .frames import MAX_FRAME, decode_response, encode_request
18
18
  _KEEP_ALIVE_CONNS = 8
19
19
  _FD_SETSIZE = 1024
20
20
  _READ_BUFFER = 64 * 1024
21
+ _SEND_SLICE = 16 * 1024
21
22
  _TCP_KEEPALIVE = {"TCP_KEEPIDLE": 15, "TCP_KEEPALIVE": 15, "TCP_KEEPINTVL": 15, "TCP_KEEPCNT": 9}
22
23
 
23
24
  _CloseableT = TypeVar("_CloseableT", bound="_Closeable")
@@ -49,18 +50,24 @@ class Conn(_Closeable):
49
50
  self._request = request
50
51
  self._upgrade_timeout = upgrade_timeout
51
52
  self._tag = tag
53
+ self._bound: tuple[float, float] | None = None
52
54
 
53
55
  def send(self, op: str, **fields: object) -> None:
54
56
  frame = encode_request(op, **fields)
55
57
  if self._request:
56
58
  frame, self._request = self._request + frame, b""
59
+ view = memoryview(frame)
57
60
  try:
58
- self._sock.sendall(frame)
61
+ while view:
62
+ if self._bound is not None:
63
+ self._sock.settimeout(remaining_timeout(*self._bound, "agent request"))
64
+ view = view[self._sock.send(view[:_SEND_SLICE]) :]
59
65
  except OSError as exc:
60
- raise ProtocolError(f"write failed: {exc}") from exc
66
+ raise _io_error("write", exc) from exc
61
67
 
62
- def settimeout(self, timeout: float | None) -> None:
68
+ def settimeout(self, timeout: float | None, deadline: float | None = None) -> None:
63
69
  self._sock.settimeout(timeout)
70
+ self._bound = None if timeout is None or deadline is None else (timeout, deadline)
64
71
 
65
72
  def abort(self) -> None:
66
73
  """Unblocks a socket operation from another thread; close() still owns the socket."""
@@ -94,7 +101,7 @@ class Conn(_Closeable):
94
101
  try:
95
102
  line = self._reader.readline(MAX_FRAME + 1)
96
103
  except (OSError, ValueError) as exc:
97
- raise ProtocolError(f"read failed: {exc}") from exc
104
+ raise _io_error("read", exc) from exc
98
105
  if not line:
99
106
  raise ProtocolError("connection closed mid-stream")
100
107
  if len(line) > MAX_FRAME:
@@ -281,6 +288,12 @@ def _handshake_error(what: str, exc: OSError) -> SandboxError:
281
288
  return ProtocolError(f"{what}: {exc}")
282
289
 
283
290
 
291
+ def _io_error(what: str, exc: Exception) -> SandboxError:
292
+ if isinstance(exc, TimeoutError) and exc.errno is None:
293
+ return SandboxTimeout("agent request timed out")
294
+ return ProtocolError(f"{what} failed: {exc}")
295
+
296
+
284
297
  def _read_upgrade(reader: BinaryIO, arm: Callable[[], None], tag: tuple[str, str]) -> None:
285
298
  arm()
286
299
  status = reader.readline(1024).decode(errors="replace")
@@ -187,7 +187,7 @@ class Sandbox:
187
187
  return cast(list[dict[str, Any]], _need(self._call("ps", "procs"), "procs"))
188
188
 
189
189
  def kill(self, pid: int, signal: int | None = None) -> None:
190
- """Signals a tracked process (default SIGKILL); killing one that already exited is a no-op success."""
190
+ """Signals the process group a tracked pid leads (default SIGKILL), even after the pid exited."""
191
191
  self._done_rpc("kill", pid=pid, signal=signal or None)
192
192
 
193
193
  def logs(
@@ -206,7 +206,7 @@ class Sandbox:
206
206
  on_stderr: Callable[[bytes], object] | None = None,
207
207
  ) -> int | None:
208
208
  """Replays then follows output until exit; a reader that falls behind misses live chunks."""
209
- return self._drain_proc("attach", pid, on_stdout, on_stderr)
209
+ return self._drain_proc("attach", pid, on_stdout, on_stderr, unbounded=True)
210
210
 
211
211
  @_follows_move
212
212
  def write_file(self, path: str, data: bytes, mode: int | None = None) -> None:
@@ -235,15 +235,16 @@ class Sandbox:
235
235
  self._done_rpc("fs_mkdir", path=path, parents=parents or None)
236
236
 
237
237
  def remove(self, path: str, recursive: bool = False) -> None:
238
- self._done_rpc("fs_rm", path=path, recursive=recursive or None)
238
+ self._done_rpc("fs_rm", unbounded=recursive, path=path, recursive=recursive or None)
239
239
 
240
240
  def rename(self, src: str, dst: str) -> None:
241
- self._done_rpc("fs_rename", **{"from": src, "to": dst})
241
+ paths: dict[str, Any] = {"from": src, "to": dst}
242
+ self._done_rpc("fs_rename", **paths)
242
243
 
243
244
  @_follows_move
244
245
  def push(self, dest: str, tar_stream: bytes) -> None:
245
246
  """Extracts a tar stream into dest; a truncated stream leaves dest untouched."""
246
- with self._lease(self._connect("fs_push", dest=dest)) as conn:
247
+ with self._lease(self._connect("fs_push", unbounded=True, dest=dest)) as conn:
247
248
  _upload(conn, tar_stream, STREAM_CHUNK)
248
249
 
249
250
  @_follows_move
@@ -271,38 +272,48 @@ class Sandbox:
271
272
 
272
273
  def git_clone(self, url: str, path: str, branch: str = "", depth: int = 0, auth: str = "") -> None:
273
274
  """Clones into path, shallow when depth is set; auth rides an in-memory header."""
274
- self._done_rpc("git_clone", url=url, path=path, branch=branch or None, depth=depth or None, auth=auth or None)
275
+ self._done_rpc(
276
+ "git_clone",
277
+ unbounded=True,
278
+ url=url,
279
+ path=path,
280
+ branch=branch or None,
281
+ depth=depth or None,
282
+ auth=auth or None,
283
+ )
275
284
 
276
285
  def git_status(self, path: str) -> dict[str, Any]:
277
- return self._call("git_status", "git_status_result", path=path)
286
+ return self._call("git_status", "git_status_result", unbounded=True, path=path)
278
287
 
279
288
  def git_add(self, path: str, files: list[str]) -> None:
280
- self._done_rpc("git_add", path=path, files=files)
289
+ self._done_rpc("git_add", unbounded=True, path=path, files=files)
281
290
 
282
291
  def git_commit(self, path: str, message: str, author: str) -> str:
283
292
  """Commits staged changes; returns the commit hash."""
284
293
  return cast(
285
294
  str,
286
- self._call("git_commit", "git_commit_result", path=path, message=message, author=author).get("hash", ""),
295
+ self._call(
296
+ "git_commit", "git_commit_result", unbounded=True, path=path, message=message, author=author
297
+ ).get("hash", ""),
287
298
  )
288
299
 
289
300
  def git_push(self, path: str, auth: str = "") -> None:
290
- self._done_rpc("git_push", path=path, auth=auth or None)
301
+ self._done_rpc("git_push", unbounded=True, path=path, auth=auth or None)
291
302
 
292
303
  def git_pull(self, path: str, auth: str = "") -> None:
293
- self._done_rpc("git_pull", path=path, auth=auth or None)
304
+ self._done_rpc("git_pull", unbounded=True, path=path, auth=auth or None)
294
305
 
295
306
  def git_branches(self, path: str) -> dict[str, Any]:
296
- return self._call("git_branch", "git_branches", path=path, action="list")
307
+ return self._call("git_branch", "git_branches", unbounded=True, path=path, action="list")
297
308
 
298
309
  def git_checkout(self, path: str, name: str) -> None:
299
- self._done_rpc("git_branch", path=path, action="checkout", name=name)
310
+ self._done_rpc("git_branch", unbounded=True, path=path, action="checkout", name=name)
300
311
 
301
312
  def git_create_branch(self, path: str, name: str) -> None:
302
- self._done_rpc("git_branch", path=path, action="create", name=name)
313
+ self._done_rpc("git_branch", unbounded=True, path=path, action="create", name=name)
303
314
 
304
315
  def git_delete_branch(self, path: str, name: str) -> None:
305
- self._done_rpc("git_branch", path=path, action="delete", name=name)
316
+ self._done_rpc("git_branch", unbounded=True, path=path, action="delete", name=name)
306
317
 
307
318
  def watch(self, path: str, recursive: bool = False) -> Watcher:
308
319
  """Streams filesystem events under path; events after the returned Watcher exists are guaranteed captured."""
@@ -326,7 +337,7 @@ class Sandbox:
326
337
  return [self._client._handle_from(addr, child, "fork") for child in reply.get("children") or []]
327
338
 
328
339
  def hibernate(self) -> None:
329
- """Snapshots and stops the VM; the next guest call restores its state."""
340
+ """Snapshots and stops the VM; the next guest call wakes it."""
330
341
  self._pool.drain()
331
342
  self._owner_request("hibernate", None, "hibernate", bearer=self.token)
332
343
 
@@ -486,15 +497,14 @@ class Sandbox:
486
497
  def _dial(self, deadline: float | None = None) -> Conn:
487
498
  return self._client._dial(self.owner, self.id, self.token, deadline)
488
499
 
489
- def _connect(self, op: str, deadline: float | None = None, /, **fields: object) -> Conn:
500
+ def _connect(self, op: str, deadline: float | None = None, /, *, unbounded: bool = False, **fields: object) -> Conn:
490
501
  conn = self._pool.take()
491
502
  if conn is None:
492
503
  conn = self._dial(deadline)
493
504
  try:
494
- if deadline is not None:
495
- conn.settimeout(remaining_timeout(self._client.timeout, deadline, "agent request"))
505
+ conn.settimeout(remaining_timeout(self._client.timeout, deadline, "agent request"), deadline)
496
506
  conn.send(op, **fields)
497
- if deadline is not None:
507
+ if unbounded or deadline is not None:
498
508
  conn.settimeout(None)
499
509
  except BaseException:
500
510
  conn.close()
@@ -515,7 +525,7 @@ class Sandbox:
515
525
 
516
526
  @_follows_move
517
527
  def _open_stream(self, op: str, expect: str = "ready", **fields: object) -> tuple[Conn, dict[str, Any]]:
518
- conn = self._connect(op, **fields)
528
+ conn = self._connect(op, unbounded=True, **fields)
519
529
  try:
520
530
  frame = _expect(conn, expect) if expect else conn.recv()
521
531
  except SilkdError:
@@ -572,12 +582,12 @@ class Sandbox:
572
582
  local.close()
573
583
 
574
584
  @_follows_move
575
- def _call(self, op: str, expect: str, **fields: object) -> dict[str, Any]:
576
- with self._lease(self._connect(op, **fields)) as conn:
585
+ def _call(self, op: str, expect: str, /, *, unbounded: bool = False, **fields: object) -> dict[str, Any]:
586
+ with self._lease(self._connect(op, unbounded=unbounded, **fields)) as conn:
577
587
  return _expect(conn, expect)
578
588
 
579
- def _done_rpc(self, op: str, **fields: object) -> None:
580
- self._call(op, "done", **fields)
589
+ def _done_rpc(self, op: str, /, *, unbounded: bool = False, **fields: object) -> None:
590
+ self._call(op, "done", unbounded=unbounded, **fields)
581
591
 
582
592
  @_follows_move
583
593
  def _drain_proc(
@@ -587,8 +597,9 @@ class Sandbox:
587
597
  on_stdout: Callable[[bytes], object] | None,
588
598
  on_stderr: Callable[[bytes], object] | None,
589
599
  trailing_done: bool = False,
600
+ unbounded: bool = False,
590
601
  ) -> int | None:
591
- with self._lease(self._connect(op, pid=pid)) as conn:
602
+ with self._lease(self._connect(op, unbounded=unbounded, pid=pid)) as conn:
592
603
  code = _pump_stdio(conn, on_stdout, on_stderr)
593
604
  if trailing_done and code is not None:
594
605
  _expect(conn, "done")
@@ -607,7 +618,7 @@ class Sandbox:
607
618
  expired = threading.Event()
608
619
  started: deque[int] = deque(maxlen=1)
609
620
  try:
610
- conn = self._connect("exec", deadline, **fields)
621
+ conn = self._connect("exec", deadline, unbounded=True, **fields)
611
622
  except (ProtocolError, TimeoutError):
612
623
  if deadline is not None and time.monotonic() >= deadline:
613
624
  raise SandboxTimeout(f"command did not finish within {timeout}s") from None
@@ -853,7 +864,7 @@ def _need(frame: dict[str, Any], key: str) -> Any:
853
864
  return frame[key]
854
865
 
855
866
 
856
- def _rpc_ignoring_not_found(sandbox: Sandbox, op: str, **fields: object) -> None:
867
+ def _rpc_ignoring_not_found(sandbox: Sandbox, op: str, **fields: Any) -> None:
857
868
  try:
858
869
  sandbox._done_rpc(op, **fields)
859
870
  except SilkdError as exc:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.36
3
+ Version: 0.1.37
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.10
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cocoonstack-sandbox"
7
- version = "0.1.36"
7
+ version = "0.1.37"
8
8
  description = "Python SDK for the cocoon sandbox control plane"
9
9
  requires-python = ">=3.10"
10
10
  license = { text = "Apache-2.0" }
@@ -1,8 +1,14 @@
1
1
  """Regression tests for the SDK error-surface hardening."""
2
2
 
3
3
  import base64
4
+ import contextlib
5
+ import errno
6
+ import io
4
7
  import json
8
+ import pathlib
9
+ import queue
5
10
  import socket
11
+ import ssl
6
12
  import threading
7
13
  import time
8
14
 
@@ -23,6 +29,8 @@ from cocoonsandbox.conn import Conn, dial_agent, remaining_timeout
23
29
  from cocoonsandbox.frames import BULK_CHUNK
24
30
  from conftest import sandbox_at, wait_until
25
31
 
32
+ TLS_PEM = pathlib.Path(__file__).with_name("tls.pem")
33
+
26
34
 
27
35
  def test_dial_agent_rejects_control_chars_in_identity():
28
36
  with pytest.raises(APIError):
@@ -221,6 +229,105 @@ def test_dial_timeout_bounds_the_whole_upgrade() -> None:
221
229
  conn.recv()
222
230
 
223
231
 
232
+ def test_a_watch_cut_by_tcp_keepalive_ends_with_a_protocol_error():
233
+ ours, theirs = socket.socketpair()
234
+ watcher = Watcher(Conn(ours, KeepaliveExpiredReader()))
235
+ assert list(watcher) == []
236
+ assert isinstance(watcher.error, ProtocolError), watcher.error
237
+ assert ours.fileno() == -1, "the ended watch kept its relay open"
238
+ theirs.close()
239
+
240
+
241
+ def test_a_send_stalled_past_the_socket_timeout_raises_sandbox_timeout():
242
+ ours, theirs = socket.socketpair()
243
+ ours.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
244
+ conn = Conn(ours, ours.makefile("rb"))
245
+ conn.settimeout(0.05)
246
+ try:
247
+ with pytest.raises(SandboxTimeout):
248
+ conn.send("data", data=bytes(4 << 20))
249
+ finally:
250
+ conn.close()
251
+ theirs.close()
252
+
253
+
254
+ @pytest.mark.parametrize("tls", [False, True], ids=["plain", "tls"])
255
+ def test_a_send_whose_bytes_keep_flowing_outlives_the_socket_timeout(tls):
256
+ ours, theirs = slow_pair()
257
+ if tls:
258
+ ours, theirs = tls_pair(ours, theirs)
259
+ conn = Conn(ours, ours.makefile("rb"))
260
+ conn.settimeout(0.2)
261
+ received = bytearray()
262
+ reader = threading.Thread(target=drain_slowly, args=(theirs, received), daemon=True)
263
+ reader.start()
264
+ try:
265
+ conn.send("data", data=bytes(2 << 20))
266
+ reader.join(10)
267
+ finally:
268
+ conn.close()
269
+ theirs.close()
270
+ assert len(base64.b64decode(json.loads(received)["data"])) == 2 << 20
271
+
272
+
273
+ def test_a_run_deadline_bounds_a_slowly_drained_request(monkeypatch):
274
+ ours, theirs = slow_pair()
275
+ sb = sandbox_at("127.0.0.1:1", keep_alive=0)
276
+ monkeypatch.setattr(sb, "_dial", lambda deadline=None: Conn(ours, ours.makefile("rb")))
277
+ threading.Thread(target=drain_slowly, args=(theirs, bytearray()), daemon=True).start()
278
+ started = time.monotonic()
279
+ try:
280
+ with pytest.raises(SandboxTimeout):
281
+ sb.run(["true"], env={"BIG": "x" * (8 << 20)}, timeout=0.3)
282
+ elapsed = time.monotonic() - started
283
+ finally:
284
+ theirs.close()
285
+ assert elapsed < 0.6, elapsed
286
+
287
+
288
+ def test_a_send_cut_by_tcp_keepalive_stays_a_protocol_error():
289
+ with pytest.raises(ProtocolError):
290
+ Conn(KeepaliveExpiredSocket(), io.BytesIO()).send("info")
291
+
292
+
293
+ class KeepaliveExpiredSocket:
294
+ def send(self, data: bytes) -> int:
295
+ raise OSError(errno.ETIMEDOUT, "connection timed out")
296
+
297
+
298
+ class KeepaliveExpiredReader:
299
+ def readline(self, limit: int) -> bytes:
300
+ raise OSError(errno.ETIMEDOUT, "connection timed out")
301
+
302
+ def close(self) -> None:
303
+ pass
304
+
305
+
306
+ def slow_pair() -> tuple[socket.socket, socket.socket]:
307
+ ours, theirs = socket.socketpair()
308
+ ours.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 64 * 1024)
309
+ theirs.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 64 * 1024)
310
+ return ours, theirs
311
+
312
+
313
+ def tls_pair(ours: socket.socket, theirs: socket.socket) -> tuple[ssl.SSLSocket, ssl.SSLSocket]:
314
+ server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
315
+ server.load_cert_chain(TLS_PEM)
316
+ client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
317
+ client.check_hostname = False
318
+ client.verify_mode = ssl.CERT_NONE
319
+ accepted: queue.Queue[ssl.SSLSocket] = queue.Queue()
320
+ threading.Thread(target=lambda: accepted.put(server.wrap_socket(theirs, server_side=True)), daemon=True).start()
321
+ return client.wrap_socket(ours), accepted.get(timeout=5)
322
+
323
+
324
+ def drain_slowly(sock: socket.socket, received: bytearray) -> None:
325
+ with contextlib.suppress(OSError):
326
+ while not received.endswith(b"\n") and (chunk := sock.recv(64 * 1024)):
327
+ received.extend(chunk)
328
+ time.sleep(0.01)
329
+
330
+
224
331
  @pytest.fixture
225
332
  def conn_pair():
226
333
  client_sock, guest_sock = socket.socketpair()
@@ -1,4 +1,4 @@
1
- """The client timeout bounds the dial and the upgrade, not the guest stream that follows."""
1
+ """The client timeout bounds the dial, the upgrade and each prompt call's wait, not a stream or a long verb."""
2
2
 
3
3
  import contextlib
4
4
  import json
@@ -14,13 +14,53 @@ from conftest import accept_upgrade, bounded, sandbox_at
14
14
  TIMEOUT = 0.2
15
15
 
16
16
 
17
- def test_port_stream_outlives_the_client_timeout(script_server):
17
+ @pytest.mark.parametrize(("keep_alive", "mkdirs"), [(0, 0), (30, 1)], ids=["fresh dial", "kept connection"])
18
+ def test_port_stream_outlives_the_client_timeout(script_server, keep_alive, mkdirs):
18
19
  ops: list[str] = []
19
- sb = short_timeout_sandbox(script_server(serve_port_forward, 3 * TIMEOUT, ops))
20
+ sb = sandbox_at(script_server(serve_port_forward, 3 * TIMEOUT, ops), timeout=TIMEOUT, keep_alive=keep_alive)
21
+ for _ in range(mkdirs):
22
+ sb.mkdir("/w")
20
23
  with sb.dial_port(5000) as port:
21
24
  assert port.recv() == b"late"
22
25
  assert port.recv() == b""
23
- assert ops == ["port_forward"]
26
+ assert ops == ["fs_mkdir"] * mkdirs + ["port_forward"]
27
+
28
+
29
+ @pytest.mark.parametrize(
30
+ "call",
31
+ [
32
+ lambda sb: sb.read_file("/f"),
33
+ lambda sb: sb.write_file("/f", b"x"),
34
+ lambda sb: sb.stat("/"),
35
+ lambda sb: sb.logs(7),
36
+ lambda sb: sb.remove("/f"),
37
+ ],
38
+ ids=["read_file", "write_file", "stat", "logs", "remove"],
39
+ )
40
+ def test_one_shot_call_to_a_silent_guest_times_out(script_server, call):
41
+ sb = short_timeout_sandbox(script_server(serve_silence, True))
42
+ with pytest.raises(SandboxTimeout):
43
+ bounded(lambda: call(sb))
44
+
45
+
46
+ @pytest.mark.parametrize(
47
+ ("op", "reply", "call"),
48
+ [
49
+ ("git_clone", "done", lambda sb: sb.git_clone("https://example.com/r.git", "/r")),
50
+ ("git_push", "done", lambda sb: sb.git_push("/r")),
51
+ ("git_pull", "done", lambda sb: sb.git_pull("/r")),
52
+ ("git_commit", "git_commit_result", lambda sb: sb.git_commit("/r", "m", "a <a@b>")),
53
+ ("git_status", "git_status_result", lambda sb: sb.git_status("/r")),
54
+ ("fs_push", "done", lambda sb: sb.push("/r", b"tar")),
55
+ ("fs_rm", "done", lambda sb: sb.remove("/r", recursive=True)),
56
+ ],
57
+ ids=["git_clone", "git_push", "git_pull", "git_commit", "git_status", "push", "recursive remove"],
58
+ )
59
+ def test_long_verb_outlives_the_client_timeout(script_server, op, reply, call):
60
+ ops: list[str] = []
61
+ sb = short_timeout_sandbox(script_server(serve_late_reply, 3 * TIMEOUT, reply, ops))
62
+ bounded(lambda: call(sb))
63
+ assert ops == [op]
24
64
 
25
65
 
26
66
  def test_run_timeout_cuts_a_silent_command_and_kills_it(script_server):
@@ -83,12 +123,24 @@ def serve_port_forward(server: socket.socket, quiet: float, ops: list[str]) -> N
83
123
  conn, _ = server.accept()
84
124
  reader = accept_upgrade(conn)
85
125
  ops.append(json.loads(reader.readline())["op"])
126
+ while ops[-1] != "port_forward":
127
+ conn.sendall(b'{"type":"done"}\n')
128
+ ops.append(json.loads(reader.readline())["op"])
86
129
  conn.sendall(b'{"type":"ready"}\n')
87
130
  time.sleep(quiet)
88
131
  conn.sendall(b'{"type":"data","data":"bGF0ZQ=="}\n{"type":"done"}\n')
89
132
  conn.close()
90
133
 
91
134
 
135
+ def serve_late_reply(server: socket.socket, quiet: float, reply: str, ops: list[str]) -> None:
136
+ conn, _ = server.accept()
137
+ reader = accept_upgrade(conn)
138
+ ops.append(json.loads(reader.readline())["op"])
139
+ time.sleep(quiet)
140
+ conn.sendall(json.dumps({"type": reply}).encode() + b"\n")
141
+ conn.close()
142
+
143
+
92
144
  def serve_started_then_hang(server: socket.socket, kills: list[dict]) -> None:
93
145
  conn, _ = server.accept()
94
146
  reader = accept_upgrade(conn)
@@ -117,8 +169,10 @@ def serve_started_then_trickle_the_kill_reply(server: socket.socket, kills: list
117
169
  conn.close()
118
170
 
119
171
 
120
- def serve_silence(server: socket.socket) -> None:
172
+ def serve_silence(server: socket.socket, upgrade: bool = False) -> None:
121
173
  conn, _ = server.accept()
174
+ if upgrade:
175
+ accept_upgrade(conn)
122
176
  with contextlib.suppress(OSError):
123
177
  while conn.recv(4096):
124
178
  pass