Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions serve/mlx_omarchy_assistant/transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1200,7 +1200,8 @@ def _bundle_required_licenses(zf: zipfile.ZipFile, manifest: dict) -> set[str]:
lock_rel = f"{pair_id}/lock.json"
if lock_rel not in manifest["files"]:
raise UnsafeArchive(f"pair {pair_id} has no lock payload")
lock = _json_member(zf, lock_rel, f"pair {pair_id} lock")
lock = _json_member(zf, lock_rel, f"pair {pair_id} lock",
max_bytes=_PAYLOAD_JSON_MAX_BYTES)
_validate_lock(lock)
if lock.get("pair_id") != pair_id:
raise TransferError(
Expand All @@ -1227,7 +1228,8 @@ def _bundle_required_licenses(zf: zipfile.ZipFile, manifest: dict) -> set[str]:
receipt_rel = f"voice/{pack_id}/manifest.json"
if receipt_rel not in manifest["files"]:
raise UnsafeArchive(f"voice pack {pack_id} has no receipt payload")
receipt = _json_member(zf, receipt_rel, f"voice pack {pack_id} receipt")
receipt = _json_member(zf, receipt_rel, f"voice pack {pack_id} receipt",
max_bytes=_PAYLOAD_JSON_MAX_BYTES)
if not isinstance(receipt, dict):
raise UnsafeArchive(f"voice pack {pack_id} receipt is not a JSON object")
if receipt.get("pack_id") != pack_id:
Expand Down Expand Up @@ -1575,11 +1577,17 @@ def _open_bundle(bundle_path: Path) -> zipfile.ZipFile:
raise UnsafeArchive(f"bundle archive unreadable: {exc}") from exc


def _member_chunks(zf: zipfile.ZipFile, name: str):
"""Yield a member's bytes; damaged data raises UnsafeArchive, caller errors do not."""
def _member_chunks(zf: zipfile.ZipFile, name: str, limit: int | None = None):
"""Yield a member's bytes; damaged data, or more than limit bytes, raises
UnsafeArchive, caller errors do not."""
try:
with zf.open(name) as src:
while chunk := src.read(_CHUNK):
size = 0
while chunk := src.read(_CHUNK if limit is None
else min(_CHUNK, limit - size + 1)):
size += len(chunk)
if limit is not None and size > limit:
raise UnsafeArchive(f"bundle member {name} exceeds {limit} bytes")
yield chunk
except _ZIP_ERRORS as exc:
raise UnsafeArchive(f"bundle member {name} unreadable: {exc}") from exc
Expand All @@ -1588,10 +1596,15 @@ def _member_chunks(zf: zipfile.ZipFile, name: str):
# Bundle JSON nests a few levels. json.loads can accept far deeper input than
# json.dumps or repr can later walk (Python 3.12+), so cap the depth up front.
_JSON_MAX_DEPTH = 32
# JSON members are read whole into memory, so the read stops at a byte cap. The
# member's declared size is no bound: zipfile reads up to it, and deflate can
# expand a member about a thousand times.
_MANIFEST_MAX_BYTES = 64 << 20
_PAYLOAD_JSON_MAX_BYTES = 1 << 20 # a pair lock or voice receipt is a few KB


def _json_member(zf: zipfile.ZipFile, name: str, what: str) -> object:
data = b"".join(_member_chunks(zf, name))
def _json_member(zf: zipfile.ZipFile, name: str, what: str, *, max_bytes: int) -> object:
data = b"".join(_member_chunks(zf, name, max_bytes))
try:
value = json.loads(data)
except (ValueError, RecursionError) as exc: # bad JSON or UTF-8, int digit cap, nesting
Expand Down Expand Up @@ -1637,9 +1650,9 @@ def _read_manifest(zf: zipfile.ZipFile, max_total_bytes: int) -> dict:
info = zf.getinfo(MANIFEST_NAME)
except KeyError:
raise UnsafeArchive(f"bundle has no {MANIFEST_NAME}") from None
if info.file_size > 64 << 20:
if info.file_size > _MANIFEST_MAX_BYTES:
raise UnsafeArchive("manifest too large")
manifest = _json_member(zf, MANIFEST_NAME, "manifest")
manifest = _json_member(zf, MANIFEST_NAME, "manifest", max_bytes=_MANIFEST_MAX_BYTES)
if not isinstance(manifest, dict):
raise UnsafeArchive("manifest is not a JSON object")

Expand Down
45 changes: 45 additions & 0 deletions tests/test_assistant_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import sys
import tempfile
import threading
import tracemalloc
import unittest
import zipfile
from pathlib import Path
Expand Down Expand Up @@ -561,6 +562,50 @@ def test_lock_parsed_the_same_before_and_after_extraction(self) -> None:
/ "transfer-lock.json").read_text())
self.assertEqual(localized["licenses"], self.lock["licenses"])

def test_oversized_lock_or_receipt_stops_at_the_byte_cap(self) -> None:
self.export(voice=[self._voice_dir()])
members = self._members()
transfer.inspect_bundle(self.bundle_path())
self.import_() # normal-sized lock and receipt stage cleanly
shutil.rmtree(self.dst_home)
receipt_rel = "voice/qwen3-tts-0.6b-customvoice-4bit/manifest.json"
pad = b" " * (32 << 20) # deflates about a thousandfold
for rel in ("everyday/lock.json", receipt_rel):
with self.subTest(rel):
big = members[rel] + pad
manifest = json.loads(members[transfer.MANIFEST_NAME])
manifest["files"][rel] = {"sha256": hashlib.sha256(big).hexdigest(),
"size": len(big)}
manifest["total_bytes"] = sum(e["size"] for e in manifest["files"].values())
bomb = {**members, rel: big,
transfer.MANIFEST_NAME: json.dumps(manifest).encode()}
out = self.bundle_path("big.zip")
with zipfile.ZipFile(out, "w", zipfile.ZIP_STORED) as zf:
for name, data in sorted(bomb.items()):
kind = zipfile.ZIP_DEFLATED if name == rel else zipfile.ZIP_STORED
zf.writestr(name, data, compress_type=kind)
raw = bytearray(out.read_bytes())
with zipfile.ZipFile(out) as zf:
local = zf.getinfo(rel).header_offset
struct.pack_into("<I", raw, local + 22, 16) # local header claims 16 bytes
out.write_bytes(bytes(raw))
self.assertLess(out.stat().st_size, 1 << 20)
transfer.inspect_bundle(out) # inspect never reads payload JSON
tracing = tracemalloc.is_tracing()
if not tracing:
tracemalloc.start()
tracemalloc.reset_peak()
before = tracemalloc.get_traced_memory()[0]
try:
with self.assertRaisesRegex(transfer.UnsafeArchive, "exceeds"):
self.import_(bundle="big.zip")
peak = tracemalloc.get_traced_memory()[1]
finally:
if not tracing:
tracemalloc.stop()
self.assertLess(peak - before, 8 << 20)
self.assertFalse(self.dst_home.exists())

def test_runtime_argv_from_the_bundle_cannot_crash_staging(self) -> None:
# `true` stands in for venv creation, so the bundle's pins reach the pip spawn.
with self.assertRaisesRegex(transfer.TransferError,
Expand Down
Loading