Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.

fix(upgrade): bound untrusted patch newSize to prevent pre-verification OOM - #1279

Merged
BYK merged 1 commit into
mainfrom
fix/bspatch-max-output-size
Jul 22, 2026
Merged

BYK merged 1 commit into
mainfrom
fix/bspatch-max-output-size

Conversation

@BYK

@BYK BYK commented Jul 22, 2026

Copy link
Copy Markdown
Member

What

The TRDIFF10 patch header's newSize field is attacker-controlled, and applyReaderToMemory uses it to preallocate the output buffer (new Uint8Array(newSize)) before the patch content is verified. With no upper bound, a malicious or corrupt patch declaring a huge newSize (e.g. 8 GiB) forces an out-of-memory allocation — a crash (or worse) reachable from any patch the CLI downloads or loads from cache.

Fix

Adds MAX_OUTPUT_SIZE (2 GiB) and enforces it in parsePatchHeader, rejecting any newSize above the cap before any allocation. 2 GiB is far above any realistic sentry-cli binary (~30 MB), so legitimate patched outputs never approach the cap.

This mirrors the same fix we made in the Lore gateway's ported copy of this file (where an adversarial security review flagged the identical bug).

Tests

  • A header claiming newSize = MAX_OUTPUT_SIZE + 1 is rejected ("exceeds maximum").
  • A header at newSize = MAX_OUTPUT_SIZE (boundary) is still accepted.
  • Mutation-verified: removing the guard turns the over-cap test RED while the boundary test stays GREEN (sharp boundary).

Verification

  • 17/17 test/lib/bspatch.test.ts pass, tsc --noEmit clean, biome check clean.

…on OOM

The TRDIFF10 header's `newSize` is attacker-controlled and `applyReaderToMemory`
uses it to preallocate the output buffer (`new Uint8Array(newSize)`) BEFORE the
patch content is verified. With no upper bound, a malicious or corrupt patch
declaring a huge newSize (e.g. 8 GiB) forces an out-of-memory allocation —
a crash (or worse) reachable from any patch the CLI downloads or loads.

Adds MAX_OUTPUT_SIZE (2 GiB) and enforces it in parsePatchHeader, rejecting any
newSize above the cap before any allocation. 2 GiB is far above any realistic
sentry-cli binary (~30 MB), so legitimate patched outputs never approach it.

Regression tests: a header claiming newSize = MAX_OUTPUT_SIZE + 1 is rejected
("exceeds maximum"); newSize = MAX_OUTPUT_SIZE (boundary) is still accepted.
Mutation-verified: removing the guard turns the over-cap test RED while the
boundary test stays GREEN (sharp boundary).
@github-actions

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://cli.sentry.dev/_preview/pr-1279/

Built to branch gh-pages at 2026-07-22 14:50 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@github-actions

Copy link
Copy Markdown
Contributor

Codecov Results 📊

✅ Patch coverage is 100.00%. Project has 5488 uncovered lines.
✅ Project coverage is 81.69%. Comparing base (base) to head (head).

Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
+ Coverage    81.69%    81.69%        —%
==========================================
  Files          426       426         —
  Lines        29969     29972        +3
  Branches     19496     19498        +2
==========================================
+ Hits         24483     24484        +1
- Misses        5486      5488        +2
- Partials      2045      2045         —

Generated by Codecov Action

@BYK
BYK merged commit cb2ac09 into main Jul 22, 2026
32 checks passed
@BYK
BYK deleted the fix/bspatch-max-output-size branch July 22, 2026 22:05
BYK added a commit that referenced this pull request Jul 22, 2026
…#1280)

## What

The diff-add step (`output[i] = (old[i] + diff[i]) % 256`) is the hot
inner loop of `bspatch` apply. Doing it byte-at-a-time in JS — two
typed-array property reads + a `% 256` per byte — dominates CPU time
when reconstructing a large binary.

## How

Extracts the loop into `addDiffChunk` and processes **4 bytes per
iteration** with a SWAR (SIMD-within-a-register) add on `Uint32Array`:

```
lows   = (a & 0x7f7f7f7f) + (b & 0x7f7f7f7f)   // top bit cleared → carries stay in-lane
highs  = (a ^ b) & 0x80808080                  // per-lane high-bit sum
result = lows ^ highs                          // per-byte sum mod 256
```

Carry-less: each byte lane sums independently mod 256. A short tail loop
handles the trailing `n % 4` bytes. Behavior is identical to the byte
loop it replaces.

On the Lore gateway's ported copy of this file (~310 MB binary, where
this optimization was first landed and reviewed) the diff-add dropped
from **~883 ms to ~221 ms (4×)**. sentry-cli binaries are smaller so the
absolute win is smaller, but it's free.

The code documents the load-bearing INVARIANT: the carry masks must
match the word width. A `BigUint64Array` variant must widen **both**
masks to 64-bit; pairing 64-bit words with the 32-bit mask silently
drops carries in the upper 4 bytes.

## Tests (exhaustive)

- Matches a per-byte reference implementation across all 256 byte values
and every 4-byte alignment.
- Wrap-around at `0xff` in every lane — a cross-lane carry detector.
- Tail lengths 0–3 across many window sizes.
- **Mutation-verified:** a mask/word-width mismatch turns all three SWAR
tests RED.

## Verification

- 18/18 `test/lib/bspatch.test.ts` pass, `tsc --noEmit` clean, `biome
check` clean.
- Independent of #1279 (the `MAX_OUTPUT_SIZE` security fix) — separate
file regions, no overlap.
BYK added a commit that referenced this pull request Jul 22, 2026
…1281)

## What

`sentry upgrade` gives no feedback during its slow phases. This adds two
byte-driven progress bars.

- **Apply phase** (the slow part of a delta upgrade): a determinate bar
— `Applying 3 patch(es) [███████░░░░░░░░░] 22.1 MB / 45.0 MB`. Total is
the **final binary size** (the last patch's declared `newSize`), i.e.
the real output the user gets — not the sum of intermediate hop writes.
Progress is byte-driven across the whole chain, so it advances smoothly
rather than stalling per hop.
- **Full-binary download**: an indeterminate byte counter — `Downloading
38.0 MB`. The decompressed size isn't known ahead of time
(`Content-Length` covers only the compressed stream), so it shows an
honest live byte count, not a fake fraction.

Both bars are gated on interactive output via the existing
`isPlainOutput()`, so they self-suppress under `NO_COLOR`, piped stdout,
and CI.

## How

- New `src/lib/progress.ts` — `makeByteProgress(label, totalBytes)`.
Reuses the existing `formatBytes` (`formatters/numbers`) and
`isPlainOutput` (`formatters/plain-detect`) helpers. Cosmetic-only: a
render failure never aborts the upgrade, and **both** `onProgress` and
`done()` are guarded against throwing streams.
- An optional `onBytes` callback is threaded through
`applyReaderToMemory` / `applyReaderToFile` → `applyPatchChainInMemory`
→ `applyPatchChain`, reporting bytes-written per output chunk. Purely
additive — no behavior change to the apply/verify logic.
- Apply bar created in `applyChainAndReturn`; download bar in
`streamDecompressToFile`.

## Tests

`test/lib/progress.test.ts` (7): determinate/indeterminate rendering,
plain-output and non-TTY header-only behavior, byte accumulation,
full-bar clamping, and the never-throws contract —
**mutation-verified**: an unguarded `done()` turns the never-throws test
RED.

## Verification

- 22/22 (`progress` + `bspatch`) pass, `tsc --noEmit` clean, `biome
check` clean.
- Independent of #1279 (`MAX_OUTPUT_SIZE`) and #1280 (SWAR) — separate
file regions, no overlap.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant