Skip to content

Fix unreachable-code panic in semver range parser on dangling '-' chunks - #31234

Merged
Jarred-Sumner merged 2 commits into
mainfrom
farm/8d415568/fix-semver-dangling-hyphen-panic
May 23, 2026
Merged

Jarred-Sumner merged 2 commits into
mainfrom
farm/8d415568/fix-semver-dangling-hyphen-panic

Conversation

@robobun

@robobun robobun commented May 22, 2026

Copy link
Copy Markdown
Collaborator

Problem

Bun.semver.satisfies() panics with internal error: entered unreachable code and crashes the process on certain malformed range strings (found by parser fuzzing):

Bun.semver.satisfies("", atob("PiA+ID4gPiA+ID4gPiBge2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Akey0gLSAtIDFlLTMyMy1hbHBoYS4x"))

Minimized repro:

Bun.semver.satisfies("1.0.0", "1 || -")   // panic
Bun.semver.satisfies("1.0.0", "1 a - b")  // panic

The empty first argument in the original report is incidental — any version string that isn't rejected earlier (e.g. "1.2.3" or "") reaches the same panic, because the crash is in range parsing, not in the comparison. The same Query::parse path is used by bun install's resolver, so a malformed range in a dependency specifier could hit it too.

Cause

In src/semver/SemverQuery.rs parse(), a garbage token (or ||) resets the pending token tag to TokenTag::None and skips the round. If the next chunk starts with - (the - arm doesn't set a tag and doesn't skip the round) and the hyphen-range lookahead fails, the parser emits a comparator via Token::to_range() with the tag still None. to_range()'s TokenTag::None arm is unreachable!().

The count == 0 branch already guarded against this (leading --foo handling) and skipped the chunk, but the count > 0 branches (or_range/and_range) did not, so the invariant only held for the first chunk.

Fix

Hoist the token.tag == TokenTag::None check out of the count == 0 branch so it applies to every chunk: when there is no pending comparator token, skip the chunk instead of emitting a comparator. This matches how the parser already ignores garbage chunks like "1 || boop", and makes the TokenTag::None => unreachable!() arm genuinely unreachable (all to_range() call sites now guarantee a real tag).

Verification

New test in test/cli/install/semver.test.ts runs the fuzzed range plus minimized variants in a subprocess and checks the results:

  • without the fix: the subprocess panics with internal error: entered unreachable code → test fails
  • with the fix: bun bd test test/cli/install/semver.test.ts → 24 pass, 0 fail

The fuzzed range evaluates to true against ""/"1.0.0" because the parser is intentionally lenient with garbage comparators (same as the existing behavior for Bun.semver.satisfies("1.0.0", "garbage")); "1 || -" keeps the valid 1 comparator and ignores the dangling - chunk, matching how "1 || boop" is handled today.

A '-' chunk that follows a skipped tag (garbage or '||') leaves the pending
token tag as None. When at least one comparator had already been parsed, the
range parser still called Token::to_range(), whose TokenTag::None arm is
unreachable!(), crashing the process (e.g. Bun.semver.satisfies("1.0.0", "1 || -")).

Skip such chunks the same way the count == 0 path already did.
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5c555bbb-b9ba-41ca-ae58-fe0cf5ce0af2

📥 Commits

Reviewing files that changed from the base of the PR and between 82cf7dc and c36f774.

📒 Files selected for processing (2)
  • src/semver/SemverQuery.rs
  • test/cli/install/semver.test.ts

Walkthrough

This PR fixes the Bun semver range parser to handle edge cases where a dangling - or other tokens follow skipped input chunks. The parser now explicitly skips chunks with no pending comparator token while preserving OR-state, and a regression test validates the fix using a subprocess that checks satisfaction results with fuzzed ranges.

Changes

Semver Parser Edge Case Fix

Layer / File(s) Summary
Parser comparator skipping
src/semver/SemverQuery.rs
The parse function now detects chunks with no pending comparator token (token.tag == TokenTag::None), clears the wildcard, and skips range emission while preserving any pending || behavior. The prior special-case that incorrectly reset is_or and cleared the wildcard before the range emission logic is removed, shifting responsibility to the new dedicated skip branch.
Regression test for dangling dash
test/cli/install/semver.test.ts
A new async test spawns a Bun subprocess, evaluates Bun.semver.satisfies() with fuzzed ranges containing a dangling -, asserts successful exit with empty stderr, and verifies JSON-encoded boolean results match the expected truth table.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main fix: preventing a panic caused by dangling '-' chunks in the semver range parser, directly matching the core changes in SemverQuery.rs.
Description check ✅ Passed The description comprehensively covers both required template sections: 'What does this PR do?' (Problem, Cause, Fix) and 'How did you verify your code works?' (Verification with test details).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@robobun

robobun commented May 22, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:35 PM PT - May 22nd, 2026

❌ @robobun, your commit c36f774 has some failures in Build #57006 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 31234

That installs a local version of the PR into your bun-31234 executable, so you can run:

bun-31234 --bun

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — straightforward hoist of the existing TokenTag::None guard so it covers count > 0 and eliminates the panic; the inline nits are non-blocking.

Extended reasoning...

Overview

This PR fixes an unreachable!() panic in src/semver/SemverQuery.rs's parse() when a dangling - chunk follows a skipped garbage token (or ||) after at least one comparator has been emitted. The fix hoists the pre-existing token.tag == TokenTag::None guard out of the count == 0 branch so it applies to every chunk. A regression test in test/cli/install/semver.test.ts covers the original fuzzed input plus minimized repros.

Security risks

None. This is parser hardening: malformed range strings that previously crashed the process now fall through the same lenient garbage-skip path used elsewhere in the parser. No auth, crypto, injection, or data-exposure surface is touched.

Level of scrutiny

Medium — the semver parser backs bun install's resolver, so regressions could affect dependency resolution. However, the change is mechanically tiny: the new branch only fires when tag == None, which for count == 0 is byte-for-byte the old behavior (the intervening count == 0 && tag == Version branch is mutually exclusive), and for count > 0 previously hit unreachable!(). So the only observable change is panic → skip on already-malformed input. The 24 existing tests still pass per the PR description.

Other factors

Two nits were flagged inline: (1) the hoisted is_or = false; makes the dangling-- skip diverge slightly from the _ garbage-token arm on inputs like "^1 || -q ^2" — but that input previously panicked, so this is still strictly an improvement and only affects input node-semver rejects outright; (2) the explicit 30_000 test timeout contradicts test/CLAUDE.md but matches the immediately preceding test in the same file. Neither blocks. No CODEOWNERS apply to these paths.

Comment thread src/semver/SemverQuery.rs Resolved
Comment thread test/cli/install/semver.test.ts Resolved
Skipping the chunk now behaves exactly like the skipped-tag path ('1.0.0 || boop'),
so '^1 || -q ^2' keeps the OR and parses like '^1 || q ^2'. Also drop the explicit
test timeout.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — thanks for dropping the is_or = false; and adding the "^1 || -q ^2" regression case.

Extended reasoning...

Overview

This PR fixes an unreachable!() panic in the semver range parser (src/semver/SemverQuery.rs) triggered by malformed range strings containing a dangling - after a skipped/garbage token once at least one comparator has been emitted (e.g. "1 || -", "1 a - b", and a fuzzer-found input). The fix hoists the existing token.tag == TokenTag::None guard out of the count == 0 branch so it applies to every chunk, skipping the chunk instead of calling to_range() with a None tag. A subprocess regression test in test/cli/install/semver.test.ts covers the fuzzed input, minimized repros, and the is_or-preservation edge case.

Security risks

None introduced. This is strictly a hardening change: inputs that previously crashed the process (a DoS vector reachable via Bun.semver.satisfies() and the bun install resolver) are now handled leniently, consistent with how the parser already treats other garbage tokens. No new parsing surface, no auth/crypto/permissions involvement.

Level of scrutiny

Moderate — the semver parser backs bun install dependency resolution, so correctness matters. However, the change is very narrow: the new branch only fires when token.tag == TokenTag::None, a state that previously fell through to to_range() and panicked. All other paths through the if-else chain are unchanged (the count == 0 && tag == Version, count == 0, is_or, and fallthrough arms are only reached when tag != None, exactly as before). For the one pre-existing reachable case (count == 0 && tag == None), behavior is identical modulo no longer clearing is_or, which is unobservable there since the count == 0 emit paths do not consult is_or.

Other factors

  • My previous review flagged that the hoisted is_or = false; line would discard a pending || (making "^1 || -q ^2" parse as AND instead of OR) and a nit about the explicit test timeout. Commit c36f774 addressed both: the is_or = false; line was dropped, the comment now documents that the pending || is preserved, a ["2.5.0", "^1 || -q ^2"] test case was added expecting true, and the 30_000 timeout was removed.
  • The bug-hunting system found no issues on the current revision.
  • No CODEOWNERS entry covers src/semver/ or test/cli/install/.
  • Test coverage is solid: original fuzz input, three minimized repros, and the is_or edge case, all run in a subprocess so a regression to the panic would fail the test rather than crash the test runner.

@Jarred-Sumner
Jarred-Sumner merged commit 586fe49 into main May 23, 2026
69 of 72 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/8d415568/fix-semver-dangling-hyphen-panic branch May 23, 2026 00:08
Jarred-Sumner pushed a commit that referenced this pull request May 23, 2026
…nks (#31234)

### Problem

`Bun.semver.satisfies()` panics with `internal error: entered
unreachable code` and crashes the process on certain malformed range
strings (found by parser fuzzing):

```js
Bun.semver.satisfies("", atob("PiA+ID4gPiA+ID4gPiBge2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Ake2Akey0gLSAtIDFlLTMyMy1hbHBoYS4x"))
```

Minimized repro:

```js
Bun.semver.satisfies("1.0.0", "1 || -")   // panic
Bun.semver.satisfies("1.0.0", "1 a - b")  // panic
```

The empty first argument in the original report is incidental — any
version string that isn't rejected earlier (e.g. `"1.2.3"` or `""`)
reaches the same panic, because the crash is in range parsing, not in
the comparison. The same `Query::parse` path is used by `bun install`'s
resolver, so a malformed range in a dependency specifier could hit it
too.

### Cause

In `src/semver/SemverQuery.rs` `parse()`, a garbage token (or `||`)
resets the pending token tag to `TokenTag::None` and skips the round. If
the next chunk starts with `-` (the `-` arm doesn't set a tag and
doesn't skip the round) and the hyphen-range lookahead fails, the parser
emits a comparator via `Token::to_range()` with the tag still `None`.
`to_range()`'s `TokenTag::None` arm is `unreachable!()`.

The `count == 0` branch already guarded against this (leading `--foo`
handling) and skipped the chunk, but the `count > 0` branches
(`or_range`/`and_range`) did not, so the invariant only held for the
first chunk.

### Fix

Hoist the `token.tag == TokenTag::None` check out of the `count == 0`
branch so it applies to every chunk: when there is no pending comparator
token, skip the chunk instead of emitting a comparator. This matches how
the parser already ignores garbage chunks like `"1 || boop"`, and makes
the `TokenTag::None => unreachable!()` arm genuinely unreachable (all
`to_range()` call sites now guarantee a real tag).

### Verification

New test in `test/cli/install/semver.test.ts` runs the fuzzed range plus
minimized variants in a subprocess and checks the results:

- without the fix: the subprocess panics with `internal error: entered
unreachable code` → test fails
- with the fix: `bun bd test test/cli/install/semver.test.ts` → 24 pass,
0 fail

The fuzzed range evaluates to `true` against `""`/`"1.0.0"` because the
parser is intentionally lenient with garbage comparators (same as the
existing behavior for `Bun.semver.satisfies("1.0.0", "garbage")`); `"1
|| -"` keeps the valid `1` comparator and ignores the dangling `-`
chunk, matching how `"1 || boop"` is handled today.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants