Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions src/paths/resolve_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use bun_core::{ZStr, strings};
// callers must not re-enter the accessor while a previous borrow is alive.
thread_local! {
static PARSER_JOIN_INPUT_BUFFER: UnsafeCell<[u8; 4096]> = const { UnsafeCell::new([0u8; 4096]) };
static PARSER_JOIN_SPILL_BUFFER: UnsafeCell<Vec<u8>> = const { UnsafeCell::new(Vec::new()) };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
static PARSER_BUFFER: UnsafeCell<[u8; 1024]> = const { UnsafeCell::new([0u8; 1024]) };
}

Expand Down Expand Up @@ -1346,6 +1347,28 @@ pub fn join_abs<'a, P: PlatformT>(cwd: &'a [u8], part: &[u8]) -> &'a [u8] {
join_abs_string::<P>(cwd, &[part])
}

#[inline]
fn join_abs_needed(cwd: &[u8], parts: &[&[u8]]) -> usize {
// Normalization never grows the concatenation; +1 sep per part, +1 leading sep, +1 NUL.
parts.iter().map(|p| p.len() + 1).sum::<usize>() + cwd.len() + 2
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

#[inline]
fn parser_join_out_buf(needed: usize) -> &'static mut [u8] {
if needed <= 4096 {
PARSER_JOIN_INPUT_BUFFER.with(|b| &mut tl_buf_mut(b)[..])
} else {
PARSER_JOIN_SPILL_BUFFER.with(|b| {
// SAFETY: same single-live-borrow-per-thread invariant as `tl_buf_mut`.
let v: &'static mut Vec<u8> = unsafe { &mut *b.get() };
if v.len() < needed {
v.resize(needed, 0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
&mut v[..]
})
}
}

/// Convert parts of potentially invalid file paths into a single valid filpeath
/// without querying the filesystem
/// This is the equivalent of path.resolve
Expand All @@ -1354,7 +1377,7 @@ pub fn join_abs<'a, P: PlatformT>(cwd: &'a [u8], part: &[u8]) -> &'a [u8] {
// result borrows the thread-local buffer ('static) OR returns `cwd`
// directly when `parts.is_empty()`. Return tied to `cwd`'s lifetime ('static: 'a).
pub fn join_abs_string<'a, P: PlatformT>(cwd: &'a [u8], parts: &[&[u8]]) -> &'a [u8] {
PARSER_JOIN_INPUT_BUFFER.with(|b| join_abs_string_buf::<P>(cwd, tl_buf_mut(b), parts))
join_abs_string_buf::<P>(cwd, parser_join_out_buf(join_abs_needed(cwd, parts)), parts)
}

/// Convert parts of potentially invalid file paths into a single valid filpeath
Expand All @@ -1363,7 +1386,7 @@ pub fn join_abs_string<'a, P: PlatformT>(cwd: &'a [u8], parts: &[&[u8]]) -> &'a
///
/// Returned path is stored in a temporary buffer. It must be copied if it needs to be stored.
pub fn join_abs_string_z<'a, P: PlatformT>(cwd: &'a [u8], parts: &[&[u8]]) -> &'a ZStr {
PARSER_JOIN_INPUT_BUFFER.with(|b| join_abs_string_buf_z::<P>(cwd, tl_buf_mut(b), parts))
join_abs_string_buf_z::<P>(cwd, parser_join_out_buf(join_abs_needed(cwd, parts)), parts)
}

const JOIN_BUF_LEN: usize = 4096;
Expand Down
23 changes: 15 additions & 8 deletions src/resolver/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4023,10 +4023,9 @@
input_path = self.fs_ref().top_level_dir;
}

// A path longer than MAX_PATH_BYTES cannot name a real directory.
// Bailing here also prevents overflowing `dir_info_uncached_path`
// below when called with user-controlled absolute import paths.
if input_path.len() > MAX_PATH_BYTES {
// `dir_info_cached_miss` slices `[..len + 1]` into `dir_info_uncached_path`,
// and a path this long cannot name a real directory anyway.
Comment thread
robobun marked this conversation as resolved.
Resolved
if input_path.len() >= MAX_PATH_BYTES {
return Ok(None);
}

Expand Down Expand Up @@ -4115,9 +4114,8 @@
dir_info_uncached_path_buf[..input_path_len].copy_from_slice(input_path);
// The slice spans one byte past the copied path so the NUL-splice/restore at
// `input_path_len` (queue index 0, processed last in the open-dir loop below)
// writes through `path`'s own provenance. `input_path_len + 1 ≤ MAX_PATH_BYTES + 1`
// (checked above) and `PathBuffer` always carries the +1 sentinel slot, so the
// safe slice is in-bounds and the threadlocal buffer outlives this fn.
// writes through `path`'s own provenance. The caller bounds `input_path_len
// < MAX_PATH_BYTES`, and the threadlocal buffer outlives this fn.
Comment thread
robobun marked this conversation as resolved.
Resolved
let path: &mut [u8] = &mut dir_info_uncached_path_buf[..input_path_len + 1];

queue[0].write(DirEntryResolveQueueItem {
Expand Down Expand Up @@ -5703,7 +5701,13 @@
}

// Try the path with extensions
bufs!(load_as_file)[..path.len()].copy_from_slice(path);
{
let buf = bufs!(load_as_file);
if path.len() >= buf.len() {
dec_ret!(None);
}
buf[..path.len()].copy_from_slice(path);
}

Check failure on line 5710 in src/resolver/resolver.rs

View check run for this annotation

Claude / Claude Code Review

Same-class panic uncovered: absolute-import '..' renormalization writes buf[MAX_PATH_BYTES]

A fourth same-class site is still unguarded, upstream of the three now checked: at `resolver.rs:1821` the absolute-import `..`-renormalization branch writes `buf[len] = platform.separator()` where `buf = bufs!(relative_abs_path)` is `[u8; MAX_PATH_BYTES]` and `len` can equal `MAX_PATH_BYTES` — `join_abs_string_buf_checked`'s slow-path rejection is `> buf.len()`, not `>=`, so it returns `Some` at exactly the limit. Reachable via the same HTML vector with e.g. `<script src="/foo..PADDING/">` (the
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
// NOTE: index by `0..len` so each iteration takes a fresh short
// borrow of `self.opts` that ends before `&mut self` is taken by
// `load_extension` (matches `extra_cjs_extensions` loop below).
Expand Down Expand Up @@ -5865,6 +5869,9 @@
// `&mut self` calls below (debug_logs / fs_ref) don't conflict, while
// each read stays a safe `BackRef: Deref`.
let entries = bun_ptr::BackRef::new(entries);
if path.len() + ext.len() > MAX_PATH_BYTES {
return None;
}
let buffer = &mut bufs!(load_as_file)[0..path.len() + ext.len()];
buffer[path.len()..].copy_from_slice(ext);
let file_name = &buffer[path.len() - base.len()..buffer.len()];
Expand Down
38 changes: 38 additions & 0 deletions test/bundler/bun-build-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,44 @@ describe("Bun.build", () => {
expect(await html?.text()).toContain("<meta name='injected-by-plugin' content='true'>");
},
);

test.concurrent("HTML entrypoint with rooted <script src> near/over MAX_PATH_BYTES does not abort", async () => {
// Rooted `/...` script src values are re-based onto the project root via the
// path-join primitive, whose output buffer is a fixed 4096-byte threadlocal.
// With an attacker-authored path >= 4096 bytes this used to panic and abort
// the process instead of surfacing a ResolveMessage.
using dir = tempDir("bun-build-html-long-rooted-src", {
"build.mjs": `
import { writeFileSync } from "node:fs";
// Sweep the MAX_PATH_BYTES boundary so that at least one resolved path
// lands in the window where the load_as_file copy fits but the
// extension-probe append would overflow, plus one well past it.
const max = process.platform === "darwin" ? 1024 : process.platform === "win32" ? 32767 * 3 + 1 : 4096;
const lens = [...Array.from({ length: 16 }, (_, i) => max - 8 + i), max + 1000];
const tags = lens
.map(n => \`<script src="/\${Buffer.alloc(Math.max(1, n - import.meta.dir.length - 4), "a")}.js"></script>\`)
.join("");
writeFileSync("./index.html", \`<html><body>\${tags}</body></html>\`);
const r = await Bun.build({ entrypoints: ["./index.html"], throw: false });
console.log(JSON.stringify({ success: r.success, logs: r.logs.map(l => l.name) }));
`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "build.mjs"],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

Comment thread
robobun marked this conversation as resolved.
Resolved
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({
success: false,
logs: expect.arrayContaining(["ResolveMessage"]),
});
expect(exitCode).toBe(0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
});

test.concurrent("macro with nested object", async () => {
Expand Down
Loading