From ebba22794306e6e6360e3f6eeb64d66307891242 Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Tue, 17 Nov 2026 10:46:41 -0600 Subject: [PATCH] feat(laptop-agent): implement the #5759 /files/* transfer routes The fleet-proxy client for get/put shipped in #5759, but the daemon half never landed, so the verbs failed live with 'daemon /files/stat: no such route'. This implements the daemon side on the canonical source (pkgs/laptop-agent/src/laptop_agent.py), following the route semantics of the client's in-memory fake daemon, which is the protocol's oracle: - /files/stat, /files/begin, /files/write, /files/commit, /files/abort, /files/read - deterministic transfer temps `..fleet-part-` - offset-idempotent writes; conflicting rewrites refused - whole-file sha256 verified at commit, then an atomic os.replace, so partial content is never visible at the destination path - resume purely from the temp's stat'd size - a transfer body cap sized for the client's 2 MiB base64 chunks (the /exec MAX_BODY of 1 MiB is too small), with a chunk cap Tests: 17 hermetic cases in tests/test_files_routes.py (round trip, no-partial-visibility, resume, idempotent replay, conflict/offset refusals, mode application, path validation), and the client-shape parity round-trip extended to drive every route. A 100 MiB put and get were verified sha256-identical both ways, plus a kill-resume drill in which the destination never exists mid-flight. Refs #10355, design #5759. --- pkgs/laptop-agent/src/laptop_agent.py | 332 ++++++++++++++ pkgs/laptop-agent/tests/parity_roundtrip.py | 66 +++ pkgs/laptop-agent/tests/test_files_routes.py | 441 +++++++++++++++++++ 3 files changed, 839 insertions(+) create mode 100644 pkgs/laptop-agent/tests/test_files_routes.py diff --git a/pkgs/laptop-agent/src/laptop_agent.py b/pkgs/laptop-agent/src/laptop_agent.py index ae49cb0303..17a96f15ad 100644 --- a/pkgs/laptop-agent/src/laptop_agent.py +++ b/pkgs/laptop-agent/src/laptop_agent.py @@ -50,6 +50,8 @@ evidence on #10131. """ +import base64 +import binascii import hashlib import hmac import json @@ -129,6 +131,13 @@ def _parse_startup_int(name, raw, requirement, minimum, maximum=None): MAX_OUT = 1 << 20 # per-stream capture cap for /exec (tail kept) MAX_BODY = 1 << 20 # request body cap for /exec and /jobs FILE_CHUNK_MAX = 1 << 20 # max bytes served per GET /file request +# #5759 transfer routes (/files/*): the fleet-proxy client ships whole +# files in 2 MiB chunks, so a single /files/write body is much larger +# than the /exec MAX_BODY cap. Base64 inflates by 4/3, so the route +# body cap is the chunk size times 4/3 plus JSON envelope headroom. +FILES_CHUNK_SIZE = 2 << 20 # 2 MiB, matches fleet-proxy CHUNK_SIZE +FILES_BODY_MAX = (FILES_CHUNK_SIZE * 4) // 3 + (1 << 16) +FILES_TEMP_MARK = ".fleet-part-" # ".{name}.fleet-part-{sha256[..12]}" EXEC_TIMEOUT_DEFAULT = 120 EXEC_TIMEOUT_MAX = 600 JOB_TTL_S = 24 * 3600 @@ -156,6 +165,11 @@ def _parse_startup_int(name, raw, requirement, minimum, maximum=None): TRIPS_FILE = STATE_DIR / "trips.jsonl" EXEC_PROCS = {} # trip -> set[Popen] currently running for /exec EXEC_PROCS_LOCK = threading.Lock() +# #5759: pending chmod modes for in-flight transfers, keyed by temp path. +# A mode rides from /files/begin to /files/commit so it is applied to +# the temp immediately before the atomic rename publishes it. +FILES_PENDING_MODES = {} +FILES_PENDING_MODES_LOCK = threading.Lock() def read_token(path: Path) -> str: @@ -210,6 +224,71 @@ def tail_file(path: Path, cap: int = MAX_OUT): return b"", False +def files_temp_path(path: str, sha256: str) -> str: + """Deterministic transfer temp for (path, sha256) (#5759). + + Mirrors the shipped client's `temp_path_for`: a sibling named + `..fleet-part-`. An interrupted transfer + resumes by re-deriving this name, and the destination path never + shows partial content because commit renames the temp over it. + """ + i = path.rfind("/") + if i >= 0: + directory, name = path[: i + 1], path[i + 1 :] + else: + directory, name = "", path + return f"{directory}.{name}{FILES_TEMP_MARK}{sha256[:12]}" + + +def _files_validate(path): + """Bound a remote path the way the client and design do (#5759). + + Non-empty, no NUL; no confinement (the daemon already executes + arbitrary commands as the same user, so file routes are not a + privilege change). Returns an error string, or None when valid. + """ + if not isinstance(path, str) or not path: + return "path required" + if "\0" in path: + return "path contains a NUL byte" + return None + + +def _files_mode_ok(mode): + """A chmod mode must be a plain int in 0..=0o7777.""" + if mode is None: + return True + if not isinstance(mode, int) or isinstance(mode, bool): + return False + return 0 <= mode <= 0o7777 + + +def _files_sha_file(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def _fsync_dir(path: Path): + """Durably record a rename by fsyncing the containing directory. + + Best-effort: a platform or filesystem that refuses a directory + fsync must not fail an otherwise correct commit. + """ + try: + fd = os.open(path if str(path) else ".", os.O_RDONLY) + except OSError: + return + try: + os.fsync(fd) + except OSError: + pass + finally: + os.close(fd) + + def _kill_group(pid: int, sig: int): try: os.killpg(pid, sig) @@ -1263,8 +1342,261 @@ def hard_kill(p=pid): threading.Thread(target=hard_kill, daemon=True).start() return self._send(200, {"ok": True, "job_id": job_id}) + if path.startswith("/files/"): + return self._files_route(path, t_received_ms) return self._send(404, {"error": "no such route"}) + # -- #5759 file transfer routes ------------------------------------- + # + # Route semantics are fixed by the shipped fleet-proxy client + # (pkgs/fleet/crates/fleet-proxy/src/files.rs); its in-memory fake + # daemon in that module's tests is the oracle these handlers + # follow. Design invariants: deterministic transfer temps + # (..fleet-part-), offset-idempotent writes, + # hash-checked commit followed by an atomic rename, so partial + # content is never visible at the destination path, and reads are + # bounded by FILES_CHUNK_SIZE. + + def _files_body(self): + """Read a /files/* request body under the transfer cap. + + The chunk bodies the client sends exceed the /exec MAX_BODY; + this reads them while still refusing an unbounded body. + """ + try: + n = int(self.headers.get("Content-Length") or 0) + except (TypeError, ValueError): + raise FramingError("invalid Content-Length header") + if n < 0: + raise FramingError("invalid Content-Length header") + if n > FILES_BODY_MAX: + raise FramingError("request body too large") + raw = self.rfile.read(n) if n else b"{}" + try: + body = json.loads(raw or b"{}") + except ValueError: + raise ValueError("request body is not valid JSON") + if not isinstance(body, dict): + raise ValueError("request body must be a JSON object") + return body + + def _files_route(self, path, t_received_ms): + try: + body = self._files_body() + except FramingError as e: + return self._send(400, {"error": str(e) or "bad request"}, close=True) + handler = { + "/files/stat": self._files_stat, + "/files/begin": self._files_begin, + "/files/write": self._files_write, + "/files/commit": self._files_commit, + "/files/abort": self._files_abort, + "/files/read": self._files_read, + }.get(path) + if handler is None: + return self._send(404, {"error": "no such route"}) + reply = handler(body) + if "_t_received" not in reply: + reply["_t_received"] = t_received_ms + return self._send(200, reply) + + def _files_stat(self, body): + path = body.get("path") + err = _files_validate(path) + if err: + return {"error": err} + try: + st = os.stat(path) + except FileNotFoundError: + return {"exists": False, "type": "missing", "size": 0} + except OSError as e: + return {"error": f"stat {path}: {e}"} + is_dir = os.path.isdir(path) + out = { + "exists": True, + "type": "dir" if is_dir else "file", + "size": 0 if is_dir else st.st_size, + "mtime": int(st.st_mtime), + } + # The client asks for the hash only on a get, and only the hash + # of a regular file: hashing a directory or a device is not + # meaningful and could block. + if body.get("sha256") and not is_dir and os.path.isfile(path): + try: + out["sha256"] = _files_sha_file(Path(path)) + except OSError as e: + return {"error": f"hash {path}: {e}"} + return out + + def _files_begin(self, body): + path = body.get("path") + err = _files_validate(path) + if err: + return {"error": err} + sha = body.get("sha256") + if not isinstance(sha, str) or not sha: + return {"error": "sha256 required"} + mode = body.get("mode") + if not _files_mode_ok(mode): + return {"error": "mode must be an integer in 0..0o7777"} + temp = Path(files_temp_path(path, sha)) + parent = temp.parent + try: + if not parent.exists(): + return {"error": f"no such directory: {parent}"} + if not parent.is_dir(): + return {"error": f"not a directory: {parent}"} + # Resume: an existing temp for the same (path, sha) is kept + # and never truncated -- the client re-derives the name and + # stat()s it to learn where to resume. + fd = os.open(temp, os.O_WRONLY | os.O_CREAT, 0o600) + os.close(fd) + except OSError as e: + return {"error": f"begin {temp}: {e}"} + if mode is not None: + with FILES_PENDING_MODES_LOCK: + FILES_PENDING_MODES[str(temp)] = int(mode) + return {"ok": True} + + def _files_write(self, body): + path = body.get("path") + err = _files_validate(path) + if err: + return {"error": err} + sha = body.get("sha256") + if not isinstance(sha, str) or not sha: + return {"error": "sha256 required"} + try: + offset = int(body.get("offset", 0)) + except (TypeError, ValueError): + return {"error": "offset must be an integer"} + if offset < 0: + return {"error": "offset must be >= 0"} + data_b64 = body.get("data_b64") + if not isinstance(data_b64, str): + return {"error": "data_b64 required"} + try: + data = base64.b64decode(data_b64, validate=True) + except (binascii.Error, ValueError): + return {"error": "data_b64 is not valid base64"} + if len(data) > FILES_CHUNK_SIZE: + return {"error": f"chunk exceeds {FILES_CHUNK_SIZE} bytes"} + temp = Path(files_temp_path(path, sha)) + try: + with open(temp, "r+b" if temp.exists() else "w+b") as f: + f.seek(0, os.SEEK_END) + have = f.tell() + if offset > have: + return {"error": "offset beyond end of temp"} + # Offset-idempotent: bytes already present must match a + # re-sent chunk (a resumed write replays the boundary + # chunk), and a genuine conflict is refused rather than + # silently corrupting the transfer. + overlap = min(have - offset, len(data)) + if overlap > 0: + f.seek(offset) + existing = f.read(overlap) + if existing != data[:overlap]: + return {"error": "conflicting rewrite at offset"} + f.seek(offset + overlap) + f.write(data[overlap:]) + f.flush() + os.fsync(f.fileno()) + size = offset + len(data) + return {"size": size} + except OSError as e: + return {"error": f"write {temp}: {e}"} + + def _files_commit(self, body): + path = body.get("path") + err = _files_validate(path) + if err: + return {"error": err} + sha = body.get("sha256") + if not isinstance(sha, str) or not sha: + return {"error": "sha256 required"} + temp = Path(files_temp_path(path, sha)) + if not temp.exists(): + return {"error": "no transfer in progress for this path and sha256"} + try: + actual = _files_sha_file(temp) + except OSError as e: + return {"error": f"hash {temp}: {e}"} + if actual != sha: + # Keep the temp: the client surfaces the daemon's words and + # a later attempt can resume or abort it. + return {"error": "sha256 mismatch", "actual": actual} + size = temp.stat().st_size + with FILES_PENDING_MODES_LOCK: + mode = FILES_PENDING_MODES.pop(str(temp), None) + try: + if mode is not None: + os.chmod(temp, mode) + # Atomic publish: the rename is what makes partial content + # at the destination impossible. + os.replace(temp, path) + _fsync_dir(Path(path).parent) + except OSError as e: + return {"error": f"commit {temp} -> {path}: {e}"} + return {"size": size, "sha256": actual} + + def _files_abort(self, body): + path = body.get("path") + err = _files_validate(path) + if err: + return {"error": err} + sha = body.get("sha256") + if not isinstance(sha, str) or not sha: + return {"error": "sha256 required"} + temp = Path(files_temp_path(path, sha)) + with FILES_PENDING_MODES_LOCK: + FILES_PENDING_MODES.pop(str(temp), None) + try: + temp.unlink() + except FileNotFoundError: + pass + except OSError as e: + return {"error": f"abort {temp}: {e}"} + return {"ok": True} + + def _files_read(self, body): + path = body.get("path") + err = _files_validate(path) + if err: + return {"error": err} + try: + offset = int(body.get("offset", 0)) + length = int(body.get("length", FILES_CHUNK_SIZE)) + except (TypeError, ValueError): + return {"error": "offset/length must be integers"} + if offset < 0: + return {"error": "offset must be >= 0"} + if length <= 0: + return {"error": "length must be >= 1"} + length = min(length, FILES_CHUNK_SIZE) + try: + st = os.stat(path) + except FileNotFoundError: + return {"error": "no such file"} + except OSError as e: + return {"error": f"stat {path}: {e}"} + if not os.path.isfile(path): + return {"error": "not a regular file"} + if offset > st.st_size: + return {"error": "offset beyond end of file", "size": st.st_size} + try: + with open(path, "rb") as f: + f.seek(offset) + data = f.read(length) + except OSError as e: + return {"error": f"read {path}: {e}"} + return { + "data_b64": base64.b64encode(data).decode("ascii"), + "eof": offset + len(data) >= st.st_size, + "size": st.st_size, + "mtime": int(st.st_mtime), + } + def _reaper_loop(): """Reap on a timer so the TTL fires without a new job (#1504). diff --git a/pkgs/laptop-agent/tests/parity_roundtrip.py b/pkgs/laptop-agent/tests/parity_roundtrip.py index 2c99746d6d..59f42147fd 100644 --- a/pkgs/laptop-agent/tests/parity_roundtrip.py +++ b/pkgs/laptop-agent/tests/parity_roundtrip.py @@ -5,6 +5,8 @@ import json import os +import base64 +import hashlib import subprocess import sys import threading @@ -211,6 +213,70 @@ def long_exec(): f"{st} {raw!r}", ) + # #5759 /files/* transfer routes, in the exact shapes the + # fleet-proxy client (pkgs/fleet/crates/fleet-proxy/src/files.rs) + # sends them: begin -> write -> commit, then stat/read back. + payload = bytes(range(256)) * 8192 # 2 MiB: exactly one chunk + fsha = hashlib.sha256(payload).hexdigest() + fdest = "/tmp/parity-transfer.bin" + if os.path.exists(fdest): + os.unlink(fdest) + st, b = jcall( + "POST", + "/files/begin", + {"path": fdest, "size": len(payload), "sha256": fsha, "mode": 0o640}, + ) + check("files begin", st == 200 and b.get("ok") is True, str(b)) + st, b = jcall( + "POST", + "/files/write", + { + "path": fdest, + "sha256": fsha, + "offset": 0, + "data_b64": base64.b64encode(payload).decode(), + }, + ) + check("files write", st == 200 and b.get("size") == len(payload), str(b)) + check( + "files: destination absent before commit", + not os.path.exists(fdest), + ) + st, b = jcall("POST", "/files/commit", {"path": fdest, "sha256": fsha}) + check( + "files commit", + st == 200 and b.get("size") == len(payload) and b.get("sha256") == fsha, + str(b), + ) + check( + "files: committed bytes identical", + open(fdest, "rb").read() == payload, + ) + check("files: mode applied", (os.stat(fdest).st_mode & 0o777) == 0o640) + st, b = jcall("POST", "/files/stat", {"path": fdest, "sha256": True}) + check( + "files stat", + st == 200 + and b.get("exists") is True + and b.get("type") == "file" + and b.get("size") == len(payload) + and b.get("sha256") == fsha, + str(b), + ) + st, b = jcall( + "POST", "/files/read", {"path": fdest, "offset": 0, "length": 2 << 20} + ) + check( + "files read", + st == 200 + and base64.b64decode(b.get("data_b64", "")) == payload + and b.get("size") == len(payload), + str({k: b.get(k) for k in ("size", "eof")}), + ) + st, b = jcall("POST", "/files/abort", {"path": fdest, "sha256": fsha}) + check("files abort (no temp left)", st == 200 and b.get("ok") is True, str(b)) + os.unlink(fdest) + # Restart persistence: running job becomes done+interrupted; # finished job stays pollable. st, b = jcall("POST", "/jobs", {"argv": ["sleep", "314"]}) diff --git a/pkgs/laptop-agent/tests/test_files_routes.py b/pkgs/laptop-agent/tests/test_files_routes.py new file mode 100644 index 0000000000..8d1c1c9b6d --- /dev/null +++ b/pkgs/laptop-agent/tests/test_files_routes.py @@ -0,0 +1,441 @@ +#!/usr/bin/env python3 +"""Tests for the #5759 /files/* transfer routes on the laptop-agent. + +Run with: python3 -m unittest discover -s pkgs/laptop-agent/tests + +The oracle is the shipped fleet-proxy client +(pkgs/fleet/crates/fleet-proxy/src/files.rs): its in-memory fake +daemon defines the route semantics these tests assert against. The +invariants under test are the design's, not incidental behaviour: + + * deterministic transfer temp `..fleet-part-` + * offset-idempotent writes; a conflicting rewrite is refused + * hash-checked commit, then an atomic rename, so partial content + is never visible at the destination path + * resume works purely from the temp's stat'd size +""" + +import base64 +import hashlib +import http.client +import json +import os +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +AGENT = Path(__file__).resolve().parents[1] / "src" / "laptop_agent.py" +TOKEN = "" +CHUNK = 2 << 20 # the client's CHUNK_SIZE + + +def free_port(): + import socket + + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def sha_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def temp_for(path: str, sha: str) -> str: + """Mirror of the client's temp_path_for (the protocol's naming).""" + i = path.rfind("/") + directory, name = (path[: i + 1], path[i + 1 :]) if i >= 0 else ("", path) + return f"{directory}.{name}.fleet-part-{sha[:12]}" + + +class FilesRoutesTest(unittest.TestCase): + def setUp(self): + self.work = Path(tempfile.mkdtemp()) + with tempfile.NamedTemporaryFile("w", delete=False) as f: + f.write(TOKEN + "\n") + self.token_path = f.name + self.port = free_port() + env = dict( + os.environ, + LAPTOP_AGENT_TOKEN_FILE=self.token_path, + LAPTOP_AGENT_HOST="127.0.0.1", + LAPTOP_AGENT_PORT=str(self.port), + LAPTOP_AGENT_STATE=str(self.work / "state"), + ) + self.proc = subprocess.Popen( + [sys.executable, str(AGENT)], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + deadline = time.time() + 10 + while time.time() < deadline: + try: + status, body = self.rpc_get("/health") + if status == 200 and body.get("ok"): + return + except Exception: + time.sleep(0.1) + self.tearDown() + self.fail("agent did not start") + + def tearDown(self): + self.proc.terminate() + self.proc.wait(timeout=10) + os.unlink(self.token_path) + import shutil + + shutil.rmtree(self.work, ignore_errors=True) + + # -- transport ---------------------------------------------------- + + def rpc_get(self, path): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30) + c.request("GET", path, headers={"X-Agent-Token": TOKEN}) + r = c.getresponse() + payload = r.read() + c.close() + return r.status, json.loads(payload) if payload else {} + + def rpc(self, route, body): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=60) + c.request( + "POST", + route, + body=json.dumps(body).encode(), + headers={"X-Agent-Token": TOKEN, "Content-Type": "application/json"}, + ) + r = c.getresponse() + payload = r.read() + c.close() + return r.status, json.loads(payload) if payload else {} + + def ok(self, route, body): + status, reply = self.rpc(route, body) + self.assertEqual(status, 200, reply) + self.assertNotIn("error", reply, reply) + return reply + + def err(self, route, body): + status, reply = self.rpc(route, body) + self.assertEqual(status, 200, reply) + self.assertIn("error", reply, reply) + return reply + + # -- client-shaped helpers ---------------------------------------- + + def put(self, dest, data, mode=None, resume=False): + """Drive begin/write/commit exactly as the client does.""" + sha = sha_hex(data) + begin = {"path": str(dest), "size": len(data), "sha256": sha} + if mode is not None: + begin["mode"] = mode + self.ok("/files/begin", begin) + start = 0 + if resume: + st = self.ok( + "/files/stat", {"path": temp_for(str(dest), sha), "sha256": False} + ) + if ( + st.get("exists") + and st.get("type") == "file" + and st["size"] <= len(data) + ): + start = st["size"] + for offset in range(start, len(data), CHUNK): + chunk = data[offset : offset + CHUNK] + reply = self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": offset, + "data_b64": base64.b64encode(chunk).decode(), + }, + ) + self.assertEqual(reply["size"], offset + len(chunk)) + return self.ok("/files/commit", {"path": str(dest), "sha256": sha}) + + def get(self, src): + st = self.ok("/files/stat", {"path": str(src), "sha256": True}) + self.assertTrue(st["exists"]) + out = bytearray() + offset = 0 + while offset < st["size"]: + reply = self.ok( + "/files/read", + { + "path": str(src), + "offset": offset, + "length": min(CHUNK, st["size"] - offset), + }, + ) + out.extend(base64.b64decode(reply["data_b64"])) + offset = len(out) + return bytes(out), st["sha256"] + + # -- AC1: whole-file round trips are sha256-identical --------------- + # + # The packet's acceptance is a 100 MiB transfer both ways. 100 MiB + # is the live acceptance run (it needs the deployed daemon); the + # multi-chunk path and the hash identity it exercises are the same + # at 5 MiB, which keeps the hermetic suite fast. + + def test_put_get_round_trip_multi_chunk(self): + data = bytes(range(256)) * (5 * 1024 * 1024 // 256 + 1) + data = data[: 5 * 1024 * 1024] + dest = self.work / "round-trip.bin" + report = self.put(dest, data) + self.assertEqual(report["size"], len(data)) + self.assertEqual(report["sha256"], sha_hex(data)) + self.assertEqual(dest.read_bytes(), data) + got, stated = self.get(dest) + self.assertEqual(got, data) + self.assertEqual(stated, sha_hex(data)) + # The temp is consumed by commit: no .fleet-part-* left behind. + self.assertEqual(list(self.work.glob("*.fleet-part-*")), []) + + def test_2mib_chunk_body_exceeds_exec_body_cap(self): + """A literal 2 MiB chunk must be accepted (MAX_BODY would not).""" + data = os.urandom(CHUNK) + dest = self.work / "chunk-cap.bin" + self.put(dest, data) + self.assertEqual(dest.read_bytes(), data) + + # -- AC2: partial content is never visible at the destination ------- + + def test_destination_untouched_until_commit(self): + data = os.urandom(CHUNK + 1234) + dest = self.work / "atomic.bin" + dest.write_bytes(b"ORIGINAL-CONTENT") + sha = sha_hex(data) + self.ok("/files/begin", {"path": str(dest), "sha256": sha, "size": len(data)}) + # Write only the first chunk, then look at the destination. + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(data[:CHUNK]).decode(), + }, + ) + self.assertEqual(dest.read_bytes(), b"ORIGINAL-CONTENT") + # A sibling temp holds the partial bytes, by the protocol's name. + temp = Path(temp_for(str(dest), sha)) + self.assertTrue(temp.exists()) + self.assertEqual(temp.stat().st_size, CHUNK) + # Commit publishes atomically and clears the temp. + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": CHUNK, + "data_b64": base64.b64encode(data[CHUNK:]).decode(), + }, + ) + self.ok("/files/commit", {"path": str(dest), "sha256": sha}) + self.assertEqual(dest.read_bytes(), data) + self.assertFalse(temp.exists()) + + def test_commit_hash_mismatch_keeps_temp_and_destination(self): + dest = self.work / "mismatch.bin" + dest.write_bytes(b"KEEP-ME") + sha = sha_hex(b"the-true-content") + self.ok("/files/begin", {"path": str(dest), "sha256": sha, "size": 0}) + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(b"corrupted").decode(), + }, + ) + reply = self.err("/files/commit", {"path": str(dest), "sha256": sha}) + self.assertIn("sha256 mismatch", reply["error"]) + self.assertIn("actual", reply) + # Destination untouched; temp retained for resume or abort. + self.assertEqual(dest.read_bytes(), b"KEEP-ME") + self.assertTrue(Path(temp_for(str(dest), sha)).exists()) + + # -- AC2: a killed transfer resumes and completes ------------------- + + def test_resume_from_partial_temp(self): + data = os.urandom(CHUNK * 2 + 999) + dest = self.work / "resume.bin" + sha = sha_hex(data) + # Simulate a client killed after chunk 1: begin + one write. + self.ok("/files/begin", {"path": str(dest), "sha256": sha, "size": len(data)}) + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(data[:CHUNK]).decode(), + }, + ) + self.assertFalse(dest.exists()) + # A fresh client re-derives the temp name and resumes from its size. + st = self.ok("/files/stat", {"path": temp_for(str(dest), sha), "sha256": False}) + self.assertEqual(st["size"], CHUNK) + report = self.put(dest, data, resume=True) + self.assertEqual(report["size"], len(data)) + self.assertEqual(dest.read_bytes(), data) + self.assertEqual(sha_hex(dest.read_bytes()), sha) + + def test_write_is_offset_idempotent(self): + """Re-sending a boundary chunk after resume must be accepted.""" + data = os.urandom(4096) + dest = self.work / "idem.bin" + sha = sha_hex(data) + self.ok("/files/begin", {"path": str(dest), "sha256": sha, "size": len(data)}) + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(data[:2048]).decode(), + }, + ) + # Replay the same bytes at the same offset: identical, so accepted. + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(data[:2048]).decode(), + }, + ) + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 2048, + "data_b64": base64.b64encode(data[2048:]).decode(), + }, + ) + self.ok("/files/commit", {"path": str(dest), "sha256": sha}) + self.assertEqual(dest.read_bytes(), data) + + # -- refusals the protocol requires --------------------------------- + + def test_conflicting_rewrite_refused(self): + data = os.urandom(4096) + dest = self.work / "conflict.bin" + sha = sha_hex(data) + self.ok("/files/begin", {"path": str(dest), "sha256": sha, "size": len(data)}) + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(data[:2048]).decode(), + }, + ) + reply = self.err( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(b"\x00" * 2048).decode(), + }, + ) + self.assertIn("conflicting rewrite", reply["error"]) + + def test_offset_beyond_end_refused(self): + data = os.urandom(1024) + dest = self.work / "gap.bin" + sha = sha_hex(data) + self.ok("/files/begin", {"path": str(dest), "sha256": sha, "size": len(data)}) + reply = self.err( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 8192, + "data_b64": base64.b64encode(b"x").decode(), + }, + ) + self.assertIn("offset beyond end", reply["error"]) + + def test_abort_removes_temp(self): + data = os.urandom(1024) + dest = self.work / "abort.bin" + sha = sha_hex(data) + self.ok("/files/begin", {"path": str(dest), "sha256": sha, "size": len(data)}) + self.ok( + "/files/write", + { + "path": str(dest), + "sha256": sha, + "offset": 0, + "data_b64": base64.b64encode(data).decode(), + }, + ) + self.ok("/files/abort", {"path": str(dest), "sha256": sha}) + self.assertFalse(Path(temp_for(str(dest), sha)).exists()) + self.assertFalse(dest.exists()) + + def test_stat_missing_file(self): + reply = self.ok( + "/files/stat", {"path": str(self.work / "nope"), "sha256": True} + ) + self.assertEqual(reply["exists"], False) + self.assertEqual(reply["type"], "missing") + + def test_read_beyond_eof_refused(self): + src = self.work / "short.bin" + src.write_bytes(b"abc") + reply = self.err("/files/read", {"path": str(src), "offset": 10, "length": 4}) + self.assertIn("offset beyond end", reply["error"]) + + # -- path and mode validation --------------------------------------- + + def test_empty_path_refused(self): + for route in ("/files/stat", "/files/begin", "/files/write", "/files/read"): + reply = self.err(route, {"path": "", "sha256": "a" * 64}) + self.assertIn("path required", reply["error"], route) + + def test_nul_path_refused(self): + reply = self.err("/files/stat", {"path": "a\0b"}) + self.assertIn("NUL", reply["error"]) + + def test_mode_applied_at_commit(self): + data = os.urandom(256) + dest = self.work / "mode.bin" + self.put(dest, data, mode=0o640) + self.assertEqual(dest.stat().st_mode & 0o777, 0o640) + + def test_bad_mode_refused(self): + reply = self.err( + "/files/begin", + {"path": str(self.work / "x"), "sha256": "a" * 64, "mode": "0755"}, + ) + self.assertIn("mode must be an integer", reply["error"]) + + def test_unknown_files_route_404s(self): + status, reply = self.rpc("/files/nonsense", {}) + self.assertEqual(status, 404) + self.assertEqual(reply["error"], "no such route") + + def test_begin_requires_existing_parent(self): + reply = self.err( + "/files/begin", + {"path": str(self.work / "no-such-dir" / "f"), "sha256": "a" * 64}, + ) + self.assertIn("no such directory", reply["error"]) + + +if __name__ == "__main__": + unittest.main()