"""TDD tests for true chunked HTTP/1.1 streaming in HttpTransport.push_stream. Phase 8 of the MPack protocol rollout: eliminate the ``b"".join(frames)`` memory bottleneck by streaming each MPack frame as a distinct HTTP chunk via ``http.client.HTTPConnection`` with ``Transfer-Encoding: chunked``. Security upgrade: MSign Authorization is computed over H frame bytes only (not the full body). Security properties are preserved because: 1. The H frame carries its own embedded Ed25519 signature over the canonical push intent (op, branch, n_objects, n_commits, agent_id, model_id). 2. Every O frame is content-addressed — ``sha256:`` prefix means a tampered object is immediately detected on receipt. 3. The E frame integrity check cross-validates actual counts against H frame advisory counts, catching truncated or injected streams. Signing over H frame bytes is strictly better than signing the full body for chunked streaming because: - Full-body signing requires buffering all frames in memory first. - H-frame signing lets the server validate auth after reading ~500 bytes, while O frames are still in flight. Red phase guarantees -------------------- All tests in this file are intentionally written against the *desired* behaviour. They are RED against the old implementation (which: - uses ``_open_url`` / urllib (no chunked encoding) - signs over full body bytes - calls ``b"".join(frame_bytes)`` before sending ) and GREEN only after the new implementation is in place. """ from __future__ import annotations import hashlib import unittest.mock from io import BytesIO import msgpack import pytest from muse.core.mpack import ( MPACK_CONTENT_TYPE, MPACK_VERSION, MPackStreamWriter, ) from muse.core.transport import HttpTransport, SigningIdentity, TransportError from muse.core._types import long_id # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _make_signing() -> SigningIdentity: from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey return SigningIdentity(handle="testuser", private_key=Ed25519PrivateKey.generate()) def _parse_chunk(raw: bytes) -> bytes: """Parse one HTTP/1.1 chunk: ``{size_hex}\\r\\n{data}\\r\\n`` → data.""" nl = raw.index(b"\r\n") return raw[nl + 2 : -2] # strip size line and trailing \r\n def _make_r_frame(ok: bool = True) -> bytes: w = MPackStreamWriter() return w.write_result(ok=ok, msg="ok", head=long_id("a" * 64)) class MockHTTPResponse: """Minimal http.client.HTTPResponse stand-in.""" def __init__(self, body: bytes, status: int = 200) -> None: self.status = status self._buf = body self._pos = 0 def read(self, n: int = -1) -> bytes: if n == -1: chunk = self._buf[self._pos :] self._pos = len(self._buf) return chunk chunk = self._buf[self._pos : self._pos + n] self._pos += n return chunk def getheader(self, name: str, default: str | None = None) -> str | None: return default class MockHTTPConnection: """Captures all http.client interaction for assertion.""" def __init__(self, host: str = "", port: int = 80, *, timeout: int = 300) -> None: self.host = host self.port = port self.timeout = timeout self.request_method: str = "" self.request_path: str = "" self.headers: dict[str, str] = {} # lower-cased keys self.sends: list[bytes] = [] # raw bytes passed to send() self._response: MockHTTPResponse = MockHTTPResponse(_make_r_frame()) self.closed = False def putrequest( self, method: str, path: str, skip_accept_encoding: bool = True ) -> None: self.request_method = method self.request_path = path def putheader(self, key: str, value: str) -> None: self.headers[key.lower()] = value def endheaders(self, body: bytes | None = None) -> None: pass def send(self, data: bytes) -> None: self.sends.append(bytes(data)) def getresponse(self) -> MockHTTPResponse: return self._response def close(self) -> None: self.closed = True def _run_push( transport: HttpTransport, *, objects: list | None = None, commits: list | None = None, snapshots: list | None = None, branch: str = "main", force: bool = False, have: list | None = None, local_head: str | None = None, signing: SigningIdentity | None = None, conn: MockHTTPConnection | None = None, response_body: bytes | None = None, ) -> tuple[MockHTTPConnection, dict]: """Invoke push_stream, intercept ``_open_chunked_connection``, return (captured_conn, push_result_dict).""" mock_conn = conn or MockHTTPConnection() if response_body is not None: mock_conn._response = MockHTTPResponse(response_body) def factory(host, port, *, use_ssl, timeout, context=None): mock_conn.host = host mock_conn.port = port return mock_conn result: dict = {} with unittest.mock.patch( "muse.core.transport._open_chunked_connection", side_effect=factory ): try: result = transport.push_stream( url="http://localhost:10003", signing=signing, objects=objects or [], commits=commits or [], snapshots=snapshots or [], branch=branch, force=force, have=have or [], local_head=local_head, ) except TransportError: pass return mock_conn, result def _decode_sends(sends: list[bytes]) -> list[bytes]: """Decode raw chunk bytes (``{hex}\\r\\n{data}\\r\\n``) into frame payloads. Terminal chunk (``0\\r\\n\\r\\n``) is excluded.""" frames = [] for raw in sends: if raw == b"0\r\n\r\n": continue try: frames.append(_parse_chunk(raw)) except (ValueError, IndexError): pass return frames def _decode_mpack_frames(sends: list[bytes]) -> list[dict]: """Decode all send() calls into decoded MPack frame dicts.""" result = [] for payload in _decode_sends(sends): try: obj = msgpack.unpackb(payload, raw=False) if isinstance(obj, dict): result.append(obj) except Exception: # noqa: BLE001 pass return result # --------------------------------------------------------------------------- # Headers: Transfer-Encoding, no Content-Length # --------------------------------------------------------------------------- class TestChunkedHeaders: def test_transfer_encoding_chunked(self) -> None: """push_stream must set Transfer-Encoding: chunked on the connection.""" t = HttpTransport() conn, _ = _run_push(t) assert conn.headers.get("transfer-encoding") == "chunked", ( f"Expected 'Transfer-Encoding: chunked', headers: {conn.headers}" ) def test_no_content_length(self) -> None: """push_stream must NOT set Content-Length — chunked encoding owns framing.""" t = HttpTransport() conn, _ = _run_push(t) assert "content-length" not in conn.headers, ( f"Content-Length must be absent for chunked streaming, " f"found: {conn.headers.get('content-length')}" ) def test_content_type_is_mpack(self) -> None: """push_stream must set Content-Type: application/x-muse-mpack.""" t = HttpTransport() conn, _ = _run_push(t) assert conn.headers.get("content-type") == MPACK_CONTENT_TYPE def test_accept_is_mpack(self) -> None: """push_stream must set Accept: application/x-muse-mpack.""" t = HttpTransport() conn, _ = _run_push(t) assert conn.headers.get("accept") == MPACK_CONTENT_TYPE def test_uses_post_method(self) -> None: """push_stream must use POST method.""" t = HttpTransport() conn, _ = _run_push(t) assert conn.request_method == "POST" def test_path_ends_with_push_stream(self) -> None: """push_stream must POST to /push/stream.""" t = HttpTransport() conn, _ = _run_push(t) assert conn.request_path.endswith("/push/stream"), ( f"Expected path ending /push/stream, got {conn.request_path!r}" ) # --------------------------------------------------------------------------- # Signing: Authorization computed over H frame bytes only # --------------------------------------------------------------------------- class TestChunkedSigning: def test_no_auth_header_when_unsigned(self) -> None: """Without signing identity, no Authorization header is sent.""" t = HttpTransport() conn, _ = _run_push(t, signing=None) assert "authorization" not in conn.headers def test_auth_header_present_when_signed(self) -> None: """With signing identity, Authorization header is set.""" t = HttpTransport() signing = _make_signing() conn, _ = _run_push(t, signing=signing) assert "authorization" in conn.headers, ( "Authorization header missing when signing identity provided" ) def test_auth_signed_over_empty_body(self) -> None: """MSign body_bytes must be None/empty for chunked streaming push. Full-body signing is incompatible with streaming (body unknown upfront). Body integrity is provided by the H frame's embedded Ed25519, object content-addressing, and E frame counts. MSign covers identity + replay via method/host/path/ts only; body_bytes must be None → SHA256(""). """ import muse.core.msign as _msign_mod real_build = _msign_mod.build_msign_header # save before patching t = HttpTransport() signing = _make_signing() captured_body: list[bytes | None] = [] def spy_build_msign(signing_id, method, url, body_bytes=None, **kw): captured_body.append(body_bytes) return real_build(signing_id, method, url, body_bytes, **kw) with unittest.mock.patch( "muse.core.msign.build_msign_header", side_effect=spy_build_msign ): _run_push(t, signing=signing) assert captured_body, "build_msign_header was never called" # For streaming push, body_bytes must be None (→ SHA256("") in canonical msg). signed_body = captured_body[0] assert signed_body is None, ( f"Auth body_bytes must be None for streaming push, got {signed_body!r:.64}" ) def test_auth_not_signed_over_full_body(self) -> None: """Authorization must NOT cover the full concatenated frame stream. With multiple objects, the full body is much larger than H frame alone. If body_bytes signed is larger than a realistic H frame (~2KB ceiling), the old full-body signing path was NOT replaced. """ import muse.core.msign as _msign_mod real_build = _msign_mod.build_msign_header t = HttpTransport() signing = _make_signing() captured_body: list[bytes] = [] def spy_build_msign(signing_id, method, url, body_bytes=None, **kw): captured_body.append(body_bytes) return real_build(signing_id, method, url, body_bytes, **kw) # 10 objects × 4KB each = 40KB full body; H frame is <2KB objects = [] for i in range(10): content = f"object-{i}-".encode() * 400 # 4KB each oid = long_id(hashlib.sha256(content).hexdigest()) objects.append({"object_id": oid, "content": content, "path": f"{i}.bin", "encoding": "raw"}) with unittest.mock.patch( "muse.core.msign.build_msign_header", side_effect=spy_build_msign ): _run_push(t, signing=signing, objects=objects) assert captured_body signed_body = captured_body[0] # For streaming push, body_bytes must be None → SHA256("") in canonical msg. # The full 40KB body must NOT be buffered and signed. assert signed_body is None, ( f"Authorization body_bytes must be None for streaming push, " f"got {len(signed_body or b'')} bytes — full body was signed." ) # --------------------------------------------------------------------------- # Frame sequence and incremental sends # --------------------------------------------------------------------------- class TestChunkedFrameSequence: def test_h_frame_first_send(self) -> None: """H frame must be the first chunk sent on the connection.""" t = HttpTransport() conn, _ = _run_push(t) frames = _decode_mpack_frames(conn.sends) assert frames, "No MPack frames decoded from sends" assert frames[0].get("t") == "H", ( f"First frame must be H, got t={frames[0].get('t')!r}" ) def test_terminal_chunk_is_last_send(self) -> None: """Last send() call must be the terminal chunk ``0\\r\\n\\r\\n``.""" t = HttpTransport() conn, _ = _run_push(t) assert conn.sends, "No sends recorded" assert conn.sends[-1] == b"0\r\n\r\n", ( f"Last send must be terminal chunk, got {conn.sends[-1]!r}" ) def test_empty_push_has_h_c_e_terminal(self) -> None: """Empty push (no objects) must send H, C, E, terminal — 4 chunks.""" t = HttpTransport() conn, _ = _run_push(t) frames = _decode_mpack_frames(conn.sends) tags = [f.get("t") for f in frames] assert "H" in tags and "C" in tags and "E" in tags, ( f"Expected H, C, E frames; got {tags}" ) assert conn.sends[-1] == b"0\r\n\r\n" def test_o_frames_between_h_and_c(self) -> None: """O frames must appear after H and before C.""" t = HttpTransport() content = b"object for sequencing test" oid = long_id(hashlib.sha256(content).hexdigest()) objects = [{"object_id": oid, "content": content, "path": "f.bin", "encoding": "raw"}] conn, _ = _run_push(t, objects=objects) frames = _decode_mpack_frames(conn.sends) tags = [f.get("t") for f in frames] assert "O" in tags, f"No O frame sent; tags: {tags}" h_i = tags.index("H") o_i = tags.index("O") c_i = tags.index("C") assert h_i < o_i < c_i, f"Wrong order: {tags}" def test_each_object_is_separate_send(self) -> None: """Each O frame must be a separate send() call — not batched together.""" t = HttpTransport() objects = [] for i in range(5): content = f"separate-object-{i}".encode() * 50 oid = long_id(hashlib.sha256(content).hexdigest()) objects.append({"object_id": oid, "content": content, "path": f"{i}.bin", "encoding": "raw"}) conn, _ = _run_push(t, objects=objects) o_frames = [f for f in _decode_mpack_frames(conn.sends) if f.get("t") == "O"] assert len(o_frames) == 5, f"Expected 5 O frames, got {len(o_frames)}" def test_send_count_matches_frame_count(self) -> None: """Total send() calls == number of frames + 1 terminal chunk.""" t = HttpTransport() n_objects = 3 objects = [] for i in range(n_objects): content = f"count-test-{i}".encode() oid = long_id(hashlib.sha256(content).hexdigest()) objects.append({"object_id": oid, "content": content, "path": f"{i}.bin", "encoding": "raw"}) conn, _ = _run_push(t, objects=objects) # H + (N objects) + C + E + terminal expected_sends = 1 + n_objects + 1 + 1 + 1 assert len(conn.sends) == expected_sends, ( f"Expected {expected_sends} send() calls, got {len(conn.sends)}" ) # --------------------------------------------------------------------------- # Memory: no single large allocation # --------------------------------------------------------------------------- class TestChunkedMemoryBounded: def test_no_single_send_contains_all_frames(self) -> None: """No single send() call should contain more than one frame. Verifies that the implementation does NOT call b''.join(all_frames) and send the result in one shot. Each send must decode to a single valid MPack frame (or be the terminal chunk). """ t = HttpTransport() objects = [] for i in range(10): content = f"mem-test-{i}".encode() * 100 oid = long_id(hashlib.sha256(content).hexdigest()) objects.append({"object_id": oid, "content": content, "path": f"{i}.bin", "encoding": "raw"}) conn, _ = _run_push(t, objects=objects) for i, raw in enumerate(conn.sends): if raw == b"0\r\n\r\n": continue # terminal chunk is fine # Each chunk payload must decode to exactly one MPack dict payload = _parse_chunk(raw) unpacked = msgpack.unpackb(payload, raw=False) assert isinstance(unpacked, dict), ( f"send()[{i}] decoded to {type(unpacked)}, expected a single frame dict" ) def test_peak_send_size_bounded_per_object(self) -> None: """No individual send() call should exceed max(object_size) × 2. The fudge factor of ×2 accounts for compression overhead and chunk framing. If one send is enormous it means frames were concatenated. """ t = HttpTransport() max_obj_size = 8 * 1024 # 8KB per object objects = [] for i in range(20): content = (f"bounded-{i}:").encode() * (max_obj_size // 10) oid = long_id(hashlib.sha256(content).hexdigest()) objects.append({"object_id": oid, "content": content, "path": f"{i}.bin", "encoding": "raw"}) conn, _ = _run_push(t, objects=objects) for i, raw in enumerate(conn.sends): if raw == b"0\r\n\r\n": continue assert len(raw) < max_obj_size * 2 + 512, ( f"send()[{i}] is {len(raw)} bytes — looks like frames were " f"concatenated (expected < {max_obj_size * 2 + 512})" ) # --------------------------------------------------------------------------- # Connection type: HTTP vs HTTPS # --------------------------------------------------------------------------- class TestChunkedConnectionType: def _run_with_url(self, url: str) -> tuple[str, int, bool]: """Return (host, port, use_ssl) captured from _open_chunked_connection.""" captured: dict = {} class CaptureConn(MockHTTPConnection): def __init__(self, host, port, *, timeout=300, context=None): super().__init__(host, port, timeout=timeout) captured["host"] = host captured["port"] = port captured["use_ssl"] = context is not None # HTTPSConnection passes context def factory(host, port, *, use_ssl, timeout, context=None): captured["use_ssl"] = use_ssl captured["host"] = host captured["port"] = port return MockHTTPConnection(host, port, timeout=timeout) t = HttpTransport() with unittest.mock.patch( "muse.core.transport._open_chunked_connection", side_effect=factory ): try: t.push_stream( url=url, signing=None, objects=[], commits=[], snapshots=[], branch="main", force=False, have=[], ) except Exception: # noqa: BLE001 pass return captured.get("host", ""), captured.get("port", 0), captured.get("use_ssl", False) def test_http_url_uses_use_ssl_false(self) -> None: """HTTP URL must open connection with use_ssl=False.""" _, _, use_ssl = self._run_with_url("http://localhost:10003") assert use_ssl is False, f"Expected use_ssl=False for HTTP, got {use_ssl}" def test_https_url_uses_use_ssl_true(self) -> None: """HTTPS URL must open connection with use_ssl=True.""" _, _, use_ssl = self._run_with_url("https://staging.musehub.ai") assert use_ssl is True, f"Expected use_ssl=True for HTTPS, got {use_ssl}" def test_host_extracted_correctly(self) -> None: """Host must be extracted from URL netloc.""" host, _, _ = self._run_with_url("http://localhost:10003") assert host == "localhost" def test_port_extracted_correctly(self) -> None: """Port must be extracted from URL.""" _, port, _ = self._run_with_url("http://localhost:10003") assert port == 10003 def test_connection_closed_after_success(self) -> None: """Connection must be closed after a successful push.""" t = HttpTransport() conn, _ = _run_push(t) assert conn.closed, "Connection was not closed after push" def test_connection_closed_after_error(self) -> None: """Connection must be closed even when server returns an error frame.""" t = HttpTransport() w = MPackStreamWriter() error_resp = w.write_error(msg="conflict", code=409) conn, _ = _run_push(t, response_body=error_resp) assert conn.closed, "Connection was not closed after error response" # --------------------------------------------------------------------------- # Response parsing # --------------------------------------------------------------------------- class TestChunkedResponseParsing: def test_r_frame_ok_returns_push_result(self) -> None: """R frame with ok=True must return PushResult dict with ok=True.""" t = HttpTransport() tip = long_id("b" * 64) w = MPackStreamWriter() response = w.write_result(ok=True, msg="pushed", heads={"main": tip}, head=tip) conn, result = _run_push(t, response_body=response) assert result.get("ok") is True, f"Expected ok=True, got {result}" def test_r_frame_message_preserved(self) -> None: """R frame message must be in the PushResult.""" t = HttpTransport() w = MPackStreamWriter() response = w.write_result(ok=True, msg="all good", head=long_id("c" * 64)) _, result = _run_push(t, response_body=response) assert result.get("message") == "all good" def test_x_frame_raises_transport_error(self) -> None: """X frame in response must raise TransportError.""" t = HttpTransport() w = MPackStreamWriter() error_resp = w.write_error(msg="non-fast-forward", code=409) def factory(host, port, *, use_ssl, timeout, context=None): conn = MockHTTPConnection() conn._response = MockHTTPResponse(error_resp) return conn with unittest.mock.patch( "muse.core.transport._open_chunked_connection", side_effect=factory ): with pytest.raises(TransportError) as exc_info: HttpTransport().push_stream( url="http://localhost:10003", signing=None, objects=[], commits=[], snapshots=[], branch="main", force=False, have=[], ) assert exc_info.value.status_code == 409 def test_p_frame_does_not_raise(self) -> None: """P (progress) frames must be consumed silently — no exception.""" t = HttpTransport() w = MPackStreamWriter() response = ( w.write_progress(msg="resolving objects", pct=25.0) + w.write_progress(msg="writing objects", pct=75.0) + w.write_result(ok=True, msg="done", head=long_id("d" * 64)) ) conn, result = _run_push(t, response_body=response) assert result.get("ok") is True def test_http_4xx_raises_transport_error(self) -> None: """HTTP 4xx status must raise TransportError with that status code.""" t = HttpTransport() def factory(host, port, *, use_ssl, timeout, context=None): conn = MockHTTPConnection() conn._response = MockHTTPResponse(b"forbidden", status=403) return conn with unittest.mock.patch( "muse.core.transport._open_chunked_connection", side_effect=factory ): with pytest.raises(TransportError) as exc_info: HttpTransport().push_stream( url="http://localhost:10003", signing=None, objects=[], commits=[], snapshots=[], branch="main", force=False, have=[], ) assert exc_info.value.status_code == 403 def test_no_result_frame_raises_transport_error(self) -> None: """Server closing stream without R frame must raise TransportError.""" t = HttpTransport() def factory(host, port, *, use_ssl, timeout, context=None): conn = MockHTTPConnection() # Response with only a progress frame, no R frame w = MPackStreamWriter() conn._response = MockHTTPResponse( w.write_progress(msg="working...", pct=50.0) ) return conn with unittest.mock.patch( "muse.core.transport._open_chunked_connection", side_effect=factory ): with pytest.raises(TransportError): HttpTransport().push_stream( url="http://localhost:10003", signing=None, objects=[], commits=[], snapshots=[], branch="main", force=False, have=[], )