Skip to content

resolver: don't abort the browser map lookup on a specifier longer than a path buffer - #37532

Closed
robobun wants to merge 1 commit into
mainfrom
farm/41267759/resolver-browser-map-long-specifier
Closed

robobun wants to merge 1 commit into
mainfrom
farm/41267759/resolver-browser-map-long-specifier

Conversation

@robobun

@robobun robobun commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

Reproduction

Any --target=browser build (CLI, Bun.build(), dev server) whose importing package has a "browser" object, when a bare import specifier is at least MAX_PATH_BYTES - 6 bytes long (4090 on Linux, 1018 on macOS):

bun -e 'const fs = require("fs");
fs.writeFileSync("package.json", JSON.stringify({ name: "root", browser: { "./a.js": "./b.js" } }));
fs.writeFileSync("entry.js", `import ${JSON.stringify("x".repeat(5000))};`)'
bun build --target=browser entry.js
panic: range end index 5000 out of range for slice of length 4096

The process aborts (exit 134). Without the browser field, or with any other target, the same build prints error: Could not resolve: "xxx..." and exits 1. The specifier does not have to be a nonsense name: a specifier made of x/../ segments that normalizes down to a real package aborts as well (see below), while it resolves fine without the browser field.

Cause

Resolver::check_browser_map (src/resolver/resolver.rs) runs for every bare specifier when the enclosing package has a non-empty browser map (twice per specifier for browser builds: once from the node polyfill check, once from check_package_path). It copies the specifier into three fixed-size PathBuffer scratch buffers without checking its length:

  • normalize_buf(bufs!(check_browser_map), input_path), which overflows once the specifier itself is longer than the buffer (the repro above);
  • BrowserMapPath::check_path's implicit index probe, join_string_buf(bufs!(tsconfig_base_url), [path, "/index"]), which overflows 6 bytes earlier (the join writes its result at offset 1 on POSIX, so the shortest aborting specifier is MAX_PATH_BYTES - 6 bytes);
  • the "./" + specifier copy into bufs!(abs_to_rel), which is what a long specifier that normalizes down to something short overflows (x/../x/../.../b).

Relative specifiers never get here with anything this long; they are resolved through abs_buf_checked first. Only package paths (and, in theory, the absolute-path variant when the package directory is shorter than 7 bytes) reach these copies with an unbounded length.

Fix

One length check at the top of check_browser_map, sized by the longest candidate the lookup builds (the /index probe, now a named constant shared with check_path): a specifier that does not fit is not looked up in the browser map and continues through ordinary resolution, which bounds its own buffers (resolve_without_remapping uses abs_buf_checked, load_node_modules joins on the heap).

Why bailing out is the right behavior rather than building the candidates on the heap: a browser map entry names a file or a package, and nothing that long can be either, so there is no real mapping such a specifier could hit. Skipping the candidate that does not fit is also what match_tsconfig_paths already does for the same shape of scratch buffer (tsconfig_match_full_buf3). The one observable difference from an unbounded lookup is deliberate and is pinned by a test: a specifier of at least MAX_PATH_BYTES - 6 bytes that normalizes down to a mapped name (thousands of x/../ segments) is no longer remapped and instead resolves like it would without the browser field. Below that length the lookup is unchanged; I verified by hand that a 4089-byte x/../...b specifier is still remapped by a b.js entry on Linux and a 4090-byte one falls through.

#37526 fixes the parse-side counterpart (a browser map key longer than the 1 KiB normalization buffer); the two do not touch the same code.

Verification

test/js/bun/resolve/resolve.test.ts, next to the existing browser-map buffer test. Four of the five new cases abort on the unfixed build, each at a different one of the copies above:

  • bun build with a specifier of exactly MAX_PATH_BYTES - 6 bytes (the /index probe) and of MAX_PATH_BYTES + 1000 bytes (the normalized copy): Could not resolve, exit 1;
  • Bun.build({ target: "browser", throw: false }) with the long specifier: success: false with the Could not resolve log, process exits 0;
  • a x/../...b specifier longer than the buffer (the "./" copy) with node_modules/b present still resolves to node_modules/b, proving the specifier falls through instead of failing;
  • a 1000-byte specifier that is in the browser map is still remapped (passes before and after; guards against over-tightening the check).

Lengths are derived from MAX_PATH_BYTES per platform, so the cases overflow on macOS and Windows too. Existing browser-field suites (test/bundler/esbuild/packagejson.test.ts, test/bundler/bundler_browser.test.ts, test/js/bun/resolve/resolve-error.test.ts) pass with the debug build.

…a path buffer

check_browser_map copied the specifier into fixed-size scratch buffers
(the normalized copy, the "./"-prefixed copy, and check_path's "/index"
probe) without checking its length, so a bare import longer than
MAX_PATH_BYTES aborted any --target=browser build whose importing package
has a "browser" map:

    panic: range end index 5000 out of range for slice of length 4096

Bail out of the lookup when the specifier cannot fit; it then goes through
ordinary resolution like it does without a browser map.
@robobun

robobun commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

Status: reproduced on the current release build with bun build --target=browser and a 5000-byte bare import next to a package.json that has a browser object (panic: range end index 5000 out of range for slice of length 4096, exit 134). The fix and tests are in this PR; 4 of the 5 new cases abort without the src/ change and all pass with it (bun bd test test/js/bun/resolve/resolve.test.ts). Waiting on CI.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The resolver now skips browser-map candidates that exceed MAX_PATH_BYTES. Tests cover oversized specifiers, unresolved-import errors, node_modules fallback resolution, and valid long-specifier remapping.

Changes

Browser-map resolution

Layer / File(s) Summary
Browser-map candidate bounds
src/resolver/resolver.rs
check_browser_map rejects oversized candidates before constructing probe paths. A shared BROWSER_MAP_INDEX_SUFFIX constant is used for index probes.
Resolution regression coverage
test/js/bun/resolve/resolve.test.ts
Tests cover CLI and Bun.build unresolved-import errors, node_modules fallback resolution, and successful remapping for valid long specifiers.

Possibly related PRs

  • oven-sh/bun#36881: Adds a related MAX_PATH_BYTES guard in profiler path construction.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: preventing browser-map lookup aborts for specifiers longer than the path buffer.
Description check ✅ Passed The description explains the cause, fix, expected behavior, and verification, including detailed regression test coverage.
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.

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

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/resolver/resolver.rs`:
- Around line 5160-5161: Update the guard near the package-path probe to
validate the full ./-prefixed candidate, including BROWSER_MAP_INDEX_SUFFIX,
using checked or overflow-safe additions before constructing abs_to_rel; keep
the existing guard for absolute-path candidates unchanged. Add a regression
covering the MAX_PATH_BYTES - 8 boundary and ensure the fixed-buffer join cannot
be reached when the candidate is too long.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 486630dd-90ca-49fe-a68e-cc5e5fd966d6

📥 Commits

Reviewing files that changed from the base of the PR and between da3851e and 65f5e02.

📒 Files selected for processing (2)
  • src/resolver/resolver.rs
  • test/js/bun/resolve/resolve.test.ts

Comment thread src/resolver/resolver.rs
Comment on lines +5160 to +5161
if input_path.len() + BROWSER_MAP_INDEX_SUFFIX.len() >= MAX_PATH_BYTES {
return None;

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Include the ./ candidate in the length guard.

Line 5160 checks only input_path plus BROWSER_MAP_INDEX_SUFFIX. Later, the package-path branches construct ./<specifier> and call BrowserMapPath::check_path. That method appends BROWSER_MAP_INDEX_SUFFIX at Lines 6777-6782.

For input_path.len() == MAX_PATH_BYTES - 8, the current check passes, but ./<specifier>/index reaches MAX_PATH_BYTES. The fixed-buffer join can still panic.

Validate the longest candidate with checked additions. Apply the extra check only before the ./-prefixed probe to avoid rejecting valid absolute-path candidates unnecessarily. Add a regression for this boundary.

Proposed fix
         if input_path.len() + BROWSER_MAP_INDEX_SUFFIX.len() >= MAX_PATH_BYTES {
             return None;
         }
 
         // Normalize the path so we can compare against it without getting confused by "./"

Add a candidate-specific check before constructing abs_to_rel:

         if is_package_path(checker.input_path) {
+            let Some(prefixed_index_probe_len) = checker
+                .input_path
+                .len()
+                .checked_add(b"./".len())
+                .and_then(|len| len.checked_add(BROWSER_MAP_INDEX_SUFFIX.len()))
+            else {
+                return None;
+            };
+            if prefixed_index_probe_len >= MAX_PATH_BYTES {
+                return None;
+            }
+
             let abs_to_rel = bufs!(abs_to_rel);

As per coding guidelines: “Treat all size, index, and length arithmetic derived from external data as adversarial; validate total bounds, widen before multiplication, clamp lengths, and retain checks in release builds.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if input_path.len() + BROWSER_MAP_INDEX_SUFFIX.len() >= MAX_PATH_BYTES {
return None;
if is_package_path(checker.input_path) {
let Some(prefixed_index_probe_len) = checker
.input_path
.len()
.checked_add(b"./".len())
.and_then(|len| len.checked_add(BROWSER_MAP_INDEX_SUFFIX.len()))
else {
return None;
};
if prefixed_index_probe_len >= MAX_PATH_BYTES {
return None;
}
let abs_to_rel = bufs!(abs_to_rel);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/resolver/resolver.rs` around lines 5160 - 5161, Update the guard near the
package-path probe to validate the full ./-prefixed candidate, including
BROWSER_MAP_INDEX_SUFFIX, using checked or overflow-safe additions before
constructing abs_to_rel; keep the existing guard for absolute-path candidates
unchanged. Add a regression covering the MAX_PATH_BYTES - 8 boundary and ensure
the fixed-buffer join cannot be reached when the candidate is too long.

Source: Coding guidelines

@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 — a single length guard at the top of check_browser_map prevents three unchecked PathBuffer copies from panicking on oversized bare specifiers.

What was reviewed:

  • Traced all three overflow sites (normalize_buf, the ./-prefixed abs_to_rel copy, and check_path's /index join) and confirmed the >= MAX_PATH_BYTES - 6 bound covers each; BrowserMapPath is only constructed inside this function so no other entry point bypasses the guard.
  • Checked the AbsolutePath branch trims input_path before the guard, so the check applies to the post-trim length.
  • Tests cover the exact boundary, well-over, CLI + Bun.build, fall-through to node_modules, and a regression guard for a long-but-fitting specifier; all follow harness conventions (tempDir, concurrent pipe drain, Buffer.alloc).
Extended reasoning...

Overview

The PR adds one early-return length check in Resolver::check_browser_map (src/resolver/resolver.rs:5160) and hoists the "/index" suffix into a named constant BROWSER_MAP_INDEX_SUFFIX shared between the guard and BrowserMapPath::check_path. Five new test cases in test/js/bun/resolve/resolve.test.ts exercise the three distinct overflow sites the guard protects, plus a fall-through case and a regression guard.

Security risks

None introduced. The change removes a user-reachable panic (exit 134) triggered by an import specifier in source code fed to bun build --target=browser — a DoS vector on any tooling that bundles untrusted input. Returning None from the browser-map lookup is the conservative fallback: the specifier continues through ordinary resolution, which already bounds its own buffers (abs_buf_checked, heap joins in load_node_modules).

Level of scrutiny

Low-to-medium. The production change is ~8 net lines: one comparison, one constant extraction, one comment. It follows the exact pattern already used elsewhere in the resolver for the same class of scratch-buffer overflow (the PR description cites match_tsconfig_paths / tsconfig_match_full_buf3, and dir_info_cached_maybe_log at line 4242 does the same >= MAX_PATH_BYTES early return). The bound is sized by the longest candidate the lookup builds and the author verified the boundary empirically (4089 bytes remaps, 4090 falls through on Linux). I confirmed BrowserMapPath is pub(crate) and only instantiated inside check_browser_map, so the single guard is exhaustive.

Other factors

Test quality is high: platform-aware maxPathBytes, describe.concurrent, Buffer.alloc(n, fill) per repo guidance, pipes drained concurrently, stderr asserted before exit code, and both the CLI and JS API paths covered. Four of five cases are stated to abort on the unfixed build (each at a different copy site), satisfying the fails-for-the-right-reason requirement; the fifth is an explicit over-tightening guard. No outstanding reviewer comments and the bug-hunting system found nothing.

Jarred-Sumner pushed a commit that referenced this pull request Aug 21, 2026
…linking zero entry points (#39799)

### Problem
- `bun build` and `Bun.build()` abort with `panic: index out of bounds:
the len is 0 but the index is 0` in `generate_chunks_in_parallel`
(`generateChunksInParallel.rs:64`, `chunks[0]`) when every entry point
is dropped (Sentry BUN-3RAS). With a live entry point beside it, the
build exits 0 and silently emits fewer outputs.
- Three producers drop an entry point without a log entry, so the
drivers link with `graph.entry_points` empty: (a) a result with every
path disabled (`"browser": {"./a.ts": false}`, or `fs` / `node:*` under
the browser target); (b) an onResolve plugin that returns `external:
true` for it; (c) an over-long specifier, which `resolve_entry_point`
returned before it logged.

### Fix
- `resolve_entry_point` rejects a disabled result: `"./a.ts" is disabled
due to "browser" field in package.json (entry point)` or `Cannot use
Node.js builtin "fs" as an entry point`. This covers the CLI,
`Bun.build()` and the plugin fallback. It makes two no-path arms
unreachable, so they are deleted: the `Ok(None)` return in
`enqueue_entry_item` (the old drop site) and the `Worker entry point is
missing` arm in `web_worker.rs`.
- `on_resolve` logs `The entry point "x" cannot be marked as external`
(esbuild's error). The length guard now only skips the cache bust, so an
over-long entry point logs `ModuleNotFound` like any missing one.
- Backstop: both drivers fail with `None of the entry points could be
bundled` when no entry point survives parsing. The linker's
`debug_assert` stays. The CLI drivers check the log after
`wait_for_parse()`, as the JS driver did, so no parse task is in flight
at teardown.
- Verified: `test/bundler/bundler_browser.test.ts`,
`bundler_plugin.test.ts`, `bun-build-api.test.ts`,
`test/js/web/workers/worker.test.ts` (new cases, all red on 1.4.0).
Other suites: see notes.

### Background
- A disabled module is how the resolver represents `"browser": false`
and browser-stubbed builtins: `Result::path()` is `None` and an import
of it becomes `{}`. An entry point has nothing to emit in that state.
- `enqueue_entry_item` appends each resolved entry point to
`graph.entry_points` (a plugin answer arrives in `on_resolve` instead).
The drivers wait for parsing, fail if the log has errors, then link. The
linker needs one entry point, so every drop has to log.

Supersedes #38778 and #38391. Carries the entry point arm of #35053,
whose import path rewrite is independent.

<details><summary>Notes</summary>

Repros on 1.4.0 (each exits 134, now exits 1 or returns `success: false`
with one message):

```sh
bun -e 'await Bun.build({entrypoints:["node:fs"]})'
bun build node:fs
bun build fs
echo '{"browser":{"./a.ts":false}}' > package.json; bun build --target=browser ./a.ts
bun -e 'await Bun.build({entrypoints:["./b.ts"], plugins:[{name:"x", setup(b){ b.onResolve({filter:/b\.ts$/}, a => ({path:a.path, external:true})) }}]})'
bun -e 'await Bun.build({entrypoints:["a".repeat(5000)]})'
```

Local debug build only: three `terminate()` tests in `worker.test.ts`
(message flood, preload with un-awaited `import()`, `fs.readFile`
completions) fail in this container, and fail the same way with the
unmodified main sources built here. `production > works with sourcemaps`
in `test/bake/dev/production.test.ts` hits its 5 s budget here and
passes in 5.07 s with a longer one, with the expected `oh no!` output.
The release binary passes all four. None of them involve entry point
resolution.

Other suites run on the debug build: `bundler_edgecase`,
`bundler_naming`, `bundler_html`, `cli`, `test/bake/dev-and-prod`, and
the three bundler files above in full.

1.3.x had the same drops and returned `success: true, outputs: []`. The
port added the bounds check, so the drop now aborts.

Silent drop on 1.4.0: `bun build --target=browser ./a.ts ./b.ts
--outdir=out` exits 0 and writes only `b.js`. Now it exits 1 with the
`./a.ts` error and writes nothing. The plugin test and the browser tests
pin this form too.

Long directory form of (c): a cwd of 3835 bytes plus a 500 byte relative
entry point (`top_level_dir + entry + 4 > MAX_PATH_BYTES`) aborts on
1.4.0 alone and is silently dropped next to a valid entry point. With
this branch both report `ModuleNotFound resolving "./eee...js" (entry
point)` from the CLI and from `Bun.build()`. The same entry point as a
4337 byte absolute path still aborts in `load_as_file`
(`src/resolver/resolver.rs:5888`), the resolver overflow #39626 is for.
A specifier longer than the buffer inside a package with a `browser`
field aborts in `check_browser_map` (`resolver.rs:5108`), which #37532
is for. Neither is an entry point drop.

Worker: the length guard also made `new Worker(longName)` fire its error
event with `BuildMessage: undefined`. The worker test pins the message.

Unchanged: `--external ./b.ts` or `external: ["*"]` on an entry point
still bundles it (entry points are exempt from external patterns,
#12734). An absolute entry point path is never looked up in the browser
map, so the bake and dev server callers of `resolve_entry_point`, which
pass absolute paths, cannot hit the new error. `node:path` under the
browser target still bundles its polyfill.

Backstop reachability: the only known route left is `bun build
--target=bun bun:wrap` in a release build (the specifier collides with
the runtime's `bun:wrap` map key, so `enqueue_entry_item` returns
`Ok(None)`). A debug build trips `assert_file_path_is_absolute` on that
input first, so the backstop has no debug-runnable test of its own.
Builtin specifiers as entry points under `--target bun`/`node` are a
separate, pre-existing problem and are reported separately.

Teardown: `enqueue_entry_points_common` schedules the runtime parse task
before any entry point is resolved. #38778 saw ASAN crashes in
`Worker::deinit_soon` on the CLI error path while the drivers still
returned before `wait_for_parse()`. With this branch under the ASAN
debug build, 30/30 runs of `bun build --target=browser ./a.ts` exit 1
with the message, and 20/20 runs with two bad entry points report both
errors.

`USE_SYSTEM_BUN=1` (1.4.0): the two new bun-build-api tests fail (the
child aborts), the plugin test fails (the child aborts), 4 of the 5 new
bundler_browser cases fail (the `--target=bun` control passes both ways
by design), the worker test fails with `BuildMessage: undefined`.

#38752 (`--no-bundle`) keeps its own message in the transform path,
which this change does not touch.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/bundler/bun-build-api.test.ts test/bundler/bundler_plugin.test.ts

<!-- robobun:evidence:end -->

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
robobun added a commit that referenced this pull request Aug 29, 2026
#36642 and #37532 each fix one part of the "browser" field handling that
this branch reworks. Their tests are added here so that closing those
PRs loses no coverage:

- packagejson/BrowserNodeModulesSubpathDisabled, SubpathToPackage,
  SubpathToPackageCycle and ExportsShadowsBrowserSubpath (#36642): a
  package subpath import whose map entry is false, a bare package, a
  cycle, or shadowed by "exports".
- "browser map lookup of a bare specifier that does not fit a path
  buffer" in test/js/bun/resolve/resolve.test.ts (#37532): a specifier
  longer than a path buffer must fail to resolve, not abort the build.

On main, four of the six packagejson cases and four of the five
resolve.test.ts cases fail. All pass with this branch.
@robobun

robobun commented Aug 29, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #40832, which reworks the browser field to follow esbuild and covers this case. Its check_browser_map builds every candidate with a bounds-checked concat_into, so a specifier that does not fit a path buffer is not remapped and falls through to ordinary resolution. The panic on main is confirmed (panic: range end index 4096 out of range for slice of length 4095).

The test block from this PR, browser map lookup of a bare specifier that does not fit a path buffer in test/js/bun/resolve/resolve.test.ts, now lives on that branch (bdb312e2b6). All five cases pass with that branch's debug build, and four of them abort on main.

Closing in favor of that PR.

@robobun robobun closed this Aug 29, 2026
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.

1 participant