Skip to content

assistant transfer: refuse malformed bundles with TransferError, not a traceback - #740

Merged
joshuaswarren merged 1 commit into
joshuaswarren:mainfrom
only21mil:fix/assistant-transfer-malformed-bundle
Nov 23, 2026
Merged

joshuaswarren merged 1 commit into
joshuaswarren:mainfrom
only21mil:fix/assistant-transfer-malformed-bundle

Conversation

@only21mil

Copy link
Copy Markdown
Contributor

Problem

When transfer inspect or transfer install gets a damaged or hand-edited bundle, it prints a Python traceback instead of a transfer: error. main() catches only TransferError, but inspect_bundle(), stage_import() and install_bundle() raised BadZipFile, KeyError, TypeError, OSError and others.

Change

Contract: a malformed bundle raises TransferError (UnsafeArchive for archive damage), so the CLI exits 1 with transfer: <reason>.

  • zipfile errors map to UnsafeArchive only at archive open and member reads.
  • Encrypted, out-of-range and non-stored/deflated members are refused.
  • Manifest, lock and receipt fields are type-checked, ids unique, JSON depth capped.
  • Payload paths must be canonical, bounded and collision-free.
  • A runtime spawn broken by bundle arguments raises TransferError.

Scope

Crash fix. No issue: small and obvious.

Verification

Tested by: AI agent.

  • Setup: Linux x86_64, Python 3.14.4 and 3.11.18; bundles derived from the test fixtures.
  • Steps: python -m mlx_omarchy_assistant.transfer inspect --bundle <file> → stage_import() with the bundle's platform.

Before, c4fe1ad0a (newest green main):

not-a-zip.zip        inspect rc=1 traceback  stage BadZipFile (uncaught)
crc-damaged.zip      inspect rc=0            stage BadZipFile (uncaught)
bz2-damaged.zip      inspect rc=0            stage OSError (uncaught)
manifest-nested.zip  inspect rc=1 traceback  stage RecursionError (uncaught)
no-created-at.zip    inspect rc=1 traceback  stage ok
file-and-dir.zip     inspect rc=0            stage FileExistsError (uncaught)

After, 2fc5a9c99:

not-a-zip.zip        inspect rc=1 clean      stage UnsafeArchive
crc-damaged.zip      inspect rc=0            stage UnsafeArchive
bz2-damaged.zip      inspect rc=1 clean      stage UnsafeArchive
manifest-nested.zip  inspect rc=1 clean      stage UnsafeArchive
no-created-at.zip    inspect rc=1 clean      stage TransferError
file-and-dir.zip     inspect rc=1 clean      stage UnsafeArchive

inspect reads no payload bytes, so it passes the CRC-damaged bundle; install refuses it. Python 3.11 and the local merge with c4fe1ad0a print the same. Nine of ten new test methods fail on c4fe1ad0a; one guards caller errors.

Links

Not shown

  • The macos-15 legs of collectors.yml; tests/ runs on Linux only.
  • A full offline install on Apple Silicon.
Checks run by AI agent

collectors.yml Linux steps, plus mlx_provenance.py --self-test, on 2fc5a9c99:

Step Python 3.14.4 Python 3.11.18
scripts/test_collect.py 189 OK 189 OK
scripts/test_collect_macos.py 50 OK 50 OK
unittest discover -s tests -p test_mlx_provenance.py 6 OK 6 OK
scripts/mlx_provenance.py --self-test OK OK
scripts/bench_matrix.py --self-test OK OK
pytest -q qualification-kit/... 49 passed 49 passed
pytest tests -q 1,829 passed, 179 skipped 1,829 passed, 179 skipped
pytest -q tests/coreml/test_import_contract.py 1 passed 1 passed
--no-deps closure (3.14 leg only) ok n/a
Installer-backed CPU regressions (3.11 leg only) n/a 42 passed, count check 42/0 skipped
provenance: mlx-omarchy None mx=None verified=no-mlx harness=2fc5a9c99 files=unresolved

Six more bundles split the same way: bad-utf8-name, no-manifest, manifest-list and int-sha256 (traceback before, clean after); dict-license (TypeError in stage_import() before, refused after); bom-lock (JSONDecodeError in stage_import() before, installs after). A local fuzz found no other escape on 2fc5a9c99: 5,000 byte-level, zip-header-field and ZIP64 mutations (5,439 escapes on c4fe1ad0a, 0 after), and every JSON path in the manifest, a lock and a receipt set to 13 wrong-typed values or deleted (172 before, 0 after). On Python 3.14, json.loads accepts a lock, license, probe list or arch nested 40,000 to 55,000 levels deep, which later raised RecursionError from json.dumps or repr in inspect or stage_import(); the 32-level cap refuses all five. A payload path 1,200 directories deep (RecursionError), one over 4,096 bytes (ENAMETOOLONG) and a duplicate pair_id (one lock activated twice) are refused too. A 606 KB bundle whose manifest alone declares 199,990 paths 60 levels deep is refused at about 300 MB peak RSS, as on c4fe1ad0a, in about 4 s against 1.6 s (19 s and 2.1 GB before this fix).

Generated with Claude Opus 5.5 in T3 Code Nightly

…a traceback

inspect_bundle(), stage_import() and install_bundle() let damaged or
hand-edited bundles escape as BadZipFile, UnicodeDecodeError, OSError,
KeyError, AttributeError, TypeError, RecursionError, ValueError,
JSONDecodeError, FileExistsError, NotImplementedError or RuntimeError.
The CLI catches only TransferError, so these printed a traceback.

Map zipfile's errors to UnsafeArchive only where the archive is opened
or a member is read, so a caller's own errors keep their type. Refuse
encrypted members, members whose offset is not before the central
directory, and compression other than stored or deflated. Parse member
JSON through one helper that caps nesting at 32 levels (json.loads on
3.12+ accepts depths json.dumps and repr cannot walk), and parse the
extracted lock the same way. Type-check created_at, sha256 strings, int
(not bool) sizes, string ids and pair licenses, the lock chip object and
the voice receipt, and refuse duplicate pair and voice pack ids. Check
the file count before any per-path work, then refuse payload paths that
are not canonical, have more than 64 parts, a part longer than 255
bytes or more than 2,048 bytes in all, collide with another path or a
generated transfer-lock.json or transfer-receipt.json, or sit outside a
payload directory; the collision check tests each path's ancestors
against the declared names rather than collecting every ancestor.
Report a runtime spawn that cannot start (a NUL byte or an oversized
argument from the bundle) as TransferError, and decode child output
with replacement so a failing child keeps its exit code and stderr in
the error.
@kilo-code-bot

kilo-code-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Files Reviewed (2 files)
  • serve/mlx_omarchy_assistant/transfer.py
  • tests/test_assistant_transfer.py

Reviewed by free · Input: 83.2K · Output: 3K · Cached: 240.6K

@joshuaswarren

Copy link
Copy Markdown
Owner

GREEN at 2fc5a9c
Model: devin/swe-2-high

Verified on main, not just read: transfer inspect on a non-zip file exits with a BadZipFile traceback today. At this head the same file exits 1 with transfer: bundle archive unreadable: File is not a zip file.

  • All 82 tests + 34 subtests pass in tests/test_assistant_transfer.py at the head.
  • The new tests are real regression tests: the MalformedBundles class fails 36 times against main's transfer.py (boolean size passes isinstance(int) on main — the type() is int change is what catches it).
  • CI green at the head: all four test legs + Kilo.
  • The boundary is drawn correctly: archive damage maps to UnsafeArchive only at archive open and member reads, so caller bugs still surface as caller bugs (covered by test_caller_errors_are_not_reported_as_archive_damage). Path checks now split on raw parts, so a//b and a/./b can't slip past PurePosixPath normalization, and payload paths can't collide with the generated transfer-lock.json/transfer-receipt.json names.

@joshuaswarren
joshuaswarren merged commit 7eea7f1 into joshuaswarren:main Nov 23, 2026
5 checks passed
@joshuaswarren

Copy link
Copy Markdown
Owner

Independent second read, done on the head 2fc5a9c (the merge landed at 13:27 UTC as 7eea7f1 while this review was running; main carries the tree).

The change is correct and does not weaken any existing check. Verified by hand:

  • Every raw-exception path a malformed bundle could take now ends in TransferError or UnsafeArchive: damaged archive data (BadZipFile, zlib.error, EOFError, UnicodeDecodeError), a missing manifest (was a KeyError traceback), deep or oversized JSON (RecursionError, the int digit cap), a non-dict chip in the lock (was an AttributeError), and a NUL byte in bundle-derived pip argv (was a ValueError from subprocess).
  • The new member checks are real: the encryption flag, member offsets against the central directory start, unsupported compression (the bz2 case), and the ZIP64 offset case are all refused before any read.
  • Strict types close the boolean holes: size: true with a one-byte payload no longer passes, total_bytes and wheel sizes use type() is int, and _safe_name type-checks instead of coercing.
  • The generated-name collision check is right: a payload path that is also a generated transfer-lock/receipt path, or a directory prefix of another payload path, is refused before extraction starts.
  • The caller-error boundary holds: an exception from the progress callback is raised at the consumer, outside the generator's try, so a caller bug is not reported as archive damage (test pinned).

Tests here: the transfer suite passes at this head except 7 app-transfer cases that need a repo checkout (install.sh / portable app bytes) - an artifact of running from a serve-only archive; CI runs the full checkout and is green on all four jobs. The new tests fail on main's pre-#740 code by construction (main had none of the wrappers these tests exercise).

One follow-up, pre-existing and unchanged by this PR: the lock and receipt member reads in _json_member are bounded by the member's own declared size field, not a hard cap, so a crafted size field can still balloon one read before the hash check catches it. A streamed per-member cap would close that; not a blocker here.

@joshuaswarren

Copy link
Copy Markdown
Owner

Independent second read of #740 at head 2fc5a9c - GREEN for the merge call (model: zai/glm-5.3-flash; same-model-family check: the author posts as only21mil, an outside machine account, so the reviewer-identity rule is met on my side).

What I verified on a clean tree of this exact head (serve + scripts + tests), not a partial extract:

  • tests/test_assistant_transfer.py: 82/82 pass, including all 8 new MalformedBundles cases (unreadable archive, missing/unparseable manifest, wrong-typed fields, boolean sizes, wrong-typed lock, missing voice receipt, payload path collisions, BOM lock parse parity, NUL argv, caller-error boundary) plus the CLI no-traceback cases.
  • tests/test_wheel_pins.py: 8/8 pass. tests/test_serve_catalog.py: 33/33 pass. These are outside assistant transfer: refuse malformed bundles with TransferError, not a traceback #740's four files and they pass green here, contradicting the earlier 7-failure lines I reported from a partial archive (my setup error: the archive lacked scripts/ and serve/, which those tests need; I have corrected that and re-run).
  • CI green on all four jobs at the head.
  • The new tests fail against main's pre-assistant transfer: refuse malformed bundles with TransferError, not a traceback #740 code by construction. I checked the two representative paths directly: json.loads(zf.read(...)) on main raises UnicodeDecodeError/JSONDecodeError for the BOM/polluted lock cases, and _safe_members on main accepts the corrupted-CRC payload read that _member_chunks now converts to UnsafeArchive with a message; the NUL-argv and progress-callback cases also fail on main with raw OSError/NotImplementedError.

Findings that would block the merge: none.

Two follow-ups, both pre-existing and both now covered by follow-up PRs already open by the same author (out of scope here, listed for the queue only):

I recommend the merge. Model: zai/glm-5.3-flash.

joshuaswarren pushed a commit that referenced this pull request Nov 23, 2026
…ming (#746)

## Problem

When a bundle's pair lock or voice receipt declares a large size, import
reads the whole member into memory before checking its size or hash.

This follows up the review note on #740. `_json_member` joins every
chunk of a member, then parses it. The only bound is the member's
declared size in the zip's central directory, and nothing checks that
size before this read. Deflate compresses a run of whitespace about a
thousandfold, so a 520 KB bundle can carry a 512 MiB lock.
`stage_import` buffers all of it while deriving the bundle's licenses,
before the size and hash checks.

## Fix

- `_member_chunks` takes an optional byte limit and raises
`UnsafeArchive` as soon as the decompressed stream passes it, reading at
most one byte past the limit. The count comes from bytes actually read,
so neither header size field can raise the limit.
- `_json_member` now requires `max_bytes`: 1 MiB for pair locks and
voice receipts (real ones are a few KB), and 64 MiB for the manifest,
the same limit its declared-size check already uses.
- Payload extraction keeps the unlimited stream: each member's declared
size must equal the manifest's before it starts, and the size and hash
are checked after.

## Verification

A new test, `test_oversized_lock_or_receipt_stops_at_the_byte_cap`,
first checks that a normal bundle with a voice pack inspects and
imports. Then, for both the lock and the receipt, it builds a member
padded to 32 MiB and deflated to under 1 MiB, with the local header
claiming 16 bytes. It expects `UnsafeArchive` with traced memory rising
less than 8 MiB.

| | base `2aef87273` | head |
|---|---|---|
| new test, Python 3.14 and 3.11 | 2 subtests fail (bundle accepted) |
pass |
| 512 MiB lock in a 520 KB bundle, peak RSS added during the license
check | +1025 MiB, 1.6 s, accepted | +2 MiB, 3 ms, `UnsafeArchive` |

All the Linux steps of `collectors.yml` pass on Python 3.14 and on 3.11,
run one after the other. `privacy_check.py` reports clean.

<details><summary>Repro output</summary>

```
== base (2aef872) py3.14
bundle 530922 bytes; everyday/lock.json: compressed 522256, central-directory size 536871775, local header size 16
provenance: mlx-omarchy None mx=None verified=no-mlx harness=2aef87273 files=unresolved
outcome: accepted (whole lock read into memory)
lock read: 1.580 s; peak RSS 1048 MiB (+1025 MiB over pre-read)
== base (2aef872) py3.11
bundle 530921 bytes; everyday/lock.json: compressed 522255, central-directory size 536871775, local header size 16
provenance: mlx-omarchy None mx=None verified=no-mlx harness=2aef87273 files=unresolved
outcome: accepted (whole lock read into memory)
lock read: 1.547 s; peak RSS 1049 MiB (+1026 MiB over pre-read)
== head (b707d094a) py3.14
bundle 530923 bytes; everyday/lock.json: compressed 522257, central-directory size 536871775, local header size 16
provenance: mlx-omarchy None mx=None verified=no-mlx harness=b707d094a files=unresolved
outcome: UnsafeArchive: bundle member everyday/lock.json exceeds 1048576 bytes
lock read: 0.003 s; peak RSS 24 MiB (+2 MiB over pre-read)
== head (b707d094a) py3.11
bundle 530920 bytes; everyday/lock.json: compressed 522254, central-directory size 536871775, local header size 16
provenance: mlx-omarchy None mx=None verified=no-mlx harness=b707d094a files=unresolved
outcome: UnsafeArchive: bundle member everyday/lock.json exceeds 1048576 bytes
lock read: 0.003 s; peak RSS 25 MiB (+2 MiB over pre-read)
```

</details>

Generated with Claude Opus 5.5 in T3 Code Nightly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants