Repository navigation
Conversation
…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.
|
Status: reproduced on the current release build with |
WalkthroughThe resolver now skips browser-map candidates that exceed ChangesBrowser-map resolution
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/resolver/resolver.rstest/js/bun/resolve/resolve.test.ts
| if input_path.len() + BROWSER_MAP_INDEX_SUFFIX.len() >= MAX_PATH_BYTES { | ||
| return None; |
There was a problem hiding this comment.
🩺 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.
| 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
There was a problem hiding this comment.
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./-prefixedabs_to_relcopy, andcheck_path's/indexjoin) and confirmed the>= MAX_PATH_BYTES - 6bound covers each;BrowserMapPathis only constructed inside this function so no other entry point bypasses the guard. - Checked the
AbsolutePathbranch trimsinput_pathbefore the guard, so the check applies to the post-trim length. - Tests cover the exact boundary, well-over, CLI +
Bun.build, fall-through tonode_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.
…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>
#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.
|
Superseded by #40832, which reworks the The test block from this PR, Closing in favor of that PR. |
Reproduction
Any
--target=browserbuild (CLI,Bun.build(), dev server) whose importing package has a"browser"object, when a bare import specifier is at leastMAX_PATH_BYTES - 6bytes long (4090 on Linux, 1018 on macOS):The process aborts (exit 134). Without the
browserfield, or with any other target, the same build printserror: Could not resolve: "xxx..."and exits 1. The specifier does not have to be a nonsense name: a specifier made ofx/../segments that normalizes down to a real package aborts as well (see below), while it resolves fine without thebrowserfield.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 fromcheck_package_path). It copies the specifier into three fixed-sizePathBufferscratch 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 isMAX_PATH_BYTES - 6bytes);"./" + specifiercopy intobufs!(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_checkedfirst. 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/indexprobe, now a named constant shared withcheck_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_remappingusesabs_buf_checked,load_node_modulesjoins 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_pathsalready 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 leastMAX_PATH_BYTES - 6bytes that normalizes down to a mapped name (thousands ofx/../segments) is no longer remapped and instead resolves like it would without thebrowserfield. Below that length the lookup is unchanged; I verified by hand that a 4089-bytex/../...bspecifier is still remapped by ab.jsentry 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 buildwith a specifier of exactlyMAX_PATH_BYTES - 6bytes (the/indexprobe) and ofMAX_PATH_BYTES + 1000bytes (the normalized copy):Could not resolve, exit 1;Bun.build({ target: "browser", throw: false })with the long specifier:success: falsewith theCould not resolvelog, process exits 0;x/../...bspecifier longer than the buffer (the"./"copy) withnode_modules/bpresent still resolves tonode_modules/b, proving the specifier falls through instead of failing;Lengths are derived from
MAX_PATH_BYTESper 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.