Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions src/jsc/bindings/ImportMetaObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,12 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlo
WTF::Vector<BunString> paths;
for (size_t i = 0; i < userPathListArray->length(); ++i) {
JSValue path = userPathListArray->getIndex(globalObject, i);
if (scope.exception()) [[unlikely]]
goto cleanup;
if (!path.isString()) {
Bun::ERR::INVALID_ARG_TYPE(scope, globalObject, makeString("paths["_s, i, "]"_s), "string"_s, path);
goto cleanup;
}
WTF::String pathStr = path.toWTFString(globalObject);
if (scope.exception()) [[unlikely]]
goto cleanup;
Expand Down
7 changes: 7 additions & 0 deletions src/jsc/modules/NodeModuleModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -374,12 +374,19 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName,
}

WTF::Vector<BunString> paths;
size_t pathIndex = 0;

// Iterate through the array using forEachInIterable
forEachInIterable(globalObject, pathsValue, [&](JSC::VM&, JSC::JSGlobalObject* lexicalGlobalObject, JSC::JSValue item) {
if (scope.exception())
return;

if (!item.isString()) {
Bun::ERR::INVALID_ARG_TYPE(scope, lexicalGlobalObject, makeString("paths["_s, pathIndex, "]"_s), "string"_s, item);
return;
}
pathIndex++;

WTF::String pathStr = item.toWTFString(lexicalGlobalObject);
if (scope.exception())
return;
Expand Down
12 changes: 11 additions & 1 deletion src/resolver/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2040,10 +2040,20 @@ impl<'a> Resolver<'a> {

if let Some(custom_paths) = self.custom_dir_paths {
bun_core::hint::cold();
let mut abs_buf = bun_paths::path_buffer_pool::get();
for custom_path in custom_paths {
let custom_utf8 = custom_path.to_utf8_without_ref();
let custom_slice = custom_utf8.slice();
let abs_custom = if bun_paths::is_absolute(custom_slice) {
custom_slice
} else {
match self.fs_ref().abs_buf_checked(&[custom_slice], &mut abs_buf) {
Some(p) => p,
None => continue,
}
};
match self.check_package_path(
custom_utf8.slice(),
abs_custom,
import_path,
kind,
global_cache,
Expand Down
38 changes: 38 additions & 0 deletions test/js/node/module/module-resolve-filename-paths.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,41 @@
Module._resolveFilename("path", __filename, false, { paths: { 0: "/some/path" } });
}).toThrow();
});

test("require.resolve throws ERR_INVALID_ARG_TYPE if options.paths contains a non-string", () => {
let err;
try {
require.resolve("nonexistent", { paths: [new DataView(new ArrayBuffer(8))] });
} catch (e) {
err = e;
}
expect(err.code).toBe("ERR_INVALID_ARG_TYPE");

err = undefined;
try {
require.resolve("nonexistent", { paths: ["/tmp", {}] });
} catch (e) {
err = e;
}
expect(err.code).toBe("ERR_INVALID_ARG_TYPE");

Check warning on line 218 in test/js/node/module/module-resolve-filename-paths.test.js

View check run for this annotation

Claude / Claude Code Review

Non-string paths tests do not assert the reported index in the error message

The new tests only assert `err.code`, but both C++ sites go to the trouble of building `makeString("paths["_s, i, "]"_s)` so the error names the offending index — and the `["/tmp", {}]` case is clearly designed to exercise index 1. Consider also asserting `expect(err.message).toContain("paths[1]")` here (and `"paths[0]"` for the DataView / `_resolveFilename` cases) so that an off-by-one in `pathIndex++` or the loop counter would be caught.
Comment on lines +212 to +218

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.

🟡 The new tests only assert err.code, but both C++ sites go to the trouble of building makeString("paths["_s, i, "]"_s) so the error names the offending index — and the ["/tmp", {}] case is clearly designed to exercise index 1. Consider also asserting expect(err.message).toContain("paths[1]") here (and "paths[0]" for the DataView / _resolveFilename cases) so that an off-by-one in pathIndex++ or the loop counter would be caught.

Extended reasoning...

What the gap is

Both changed C++ sites deliberately construct an indexed argument name for the error:

  • ImportMetaObject.cpp: Bun::ERR::INVALID_ARG_TYPE(scope, globalObject, makeString("paths["_s, i, "]"_s), "string"_s, path) inside the for (size_t i = 0; ...) loop.
  • NodeModuleModule.cpp: a manually-maintained size_t pathIndex = 0; incremented inside the forEachInIterable lambda, with makeString("paths["_s, pathIndex, "]"_s).

The new tests, however, only assert err.code === "ERR_INVALID_ARG_TYPE". They never look at err.message, so the index that the C++ code computes is untested.

Why it matters

The ["/tmp", {}] case at lines ~212-218 exists specifically to put the bad entry at a non-zero index. But if the NodeModuleModule.cpp implementation had pathIndex++ placed before the isString() check instead of after — a very easy mistake with a captured counter inside a lambda — the error would say paths[1] for the first element and paths[2] for the second, and every test in this file would still pass. Similarly, if the ImportMetaObject.cpp loop reported the wrong i, or if either site dropped the index entirely and just said "paths", nothing would fail.

REVIEW.md's test guidance is explicit: "assert the strongest invariant… specific error class/code/message (never bare toThrow())" and "Error messages are reviewed word-for-word as code". The tests already assert the specific error code (which is good — better than bare toThrow()), but since this PR's diff went out of its way to add index formatting, the tests should lock that in.

Step-by-step proof

  1. In NodeModuleModule.cpp, the lambda body is:
    if (!item.isString()) { …INVALID_ARG_TYPE(…, makeString("paths["_s, pathIndex, "]"_s), …); return; }
    pathIndex++;
  2. Suppose a future refactor moves pathIndex++; above the isString() check (or switches to a post-increment inside the makeString call and gets it wrong).
  3. For { paths: ["/tmp", {}] }: iteration 0 sees "/tmp" (string) → pathIndex becomes 1; iteration 1 sees {} → error reports paths[1]. Correct today. But with the increment moved before the check: iteration 0 → pathIndex becomes 1, string, continue; iteration 1 → pathIndex becomes 2, not string → error reports paths[2].
  4. The current test only checks err.code === "ERR_INVALID_ARG_TYPE", which is unchanged → test still passes despite the wrong index in the user-visible message.

Suggested fix

Add one assertion per case:

// DataView case
expect(err.code).toBe("ERR_INVALID_ARG_TYPE");
expect(err.message).toContain("paths[0]");

// ["/tmp", {}] case
expect(err.code).toBe("ERR_INVALID_ARG_TYPE");
expect(err.message).toContain("paths[1]");

// Module._resolveFilename [{}] case
expect(err.code).toBe("ERR_INVALID_ARG_TYPE");
expect(err.message).toContain("paths[0]");

This is a test-strengthening suggestion, not a production defect — the runtime behavior is correct as written.

});

test("Module._resolveFilename throws ERR_INVALID_ARG_TYPE if options.paths contains a non-string", () => {
let err;
try {
Module._resolveFilename("nonexistent", null, false, { paths: [{}] });
} catch (e) {
err = e;
}
expect(err.code).toBe("ERR_INVALID_ARG_TYPE");
});

test("require.resolve with a relative directory in options.paths does not crash", () => {
let err;
try {
require.resolve("nonexistent", { paths: ["not/an/absolute/path"] });
} catch (e) {
err = e;
}
expect(err.code).toBe("MODULE_NOT_FOUND");
});

Check warning on line 239 in test/js/node/module/module-resolve-filename-paths.test.js

View check run for this annotation

Claude / Claude Code Review

Relative-paths test only asserts non-crash, not successful resolution

This test only proves the panic is gone — a resolver that skipped every non-absolute entry (replacing the `abs_buf_checked` call with a bare `continue`) would also pass it. The PR claims relative `paths` entries resolve against cwd like Node, but the load-bearing `Some(p) => p` arm has no coverage. Consider adding a positive case that creates a package under a cwd-relative directory and asserts it actually resolves.
Comment on lines +231 to +239

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.

🟡 This test only proves the panic is gone — a resolver that skipped every non-absolute entry (replacing the abs_buf_checked call with a bare continue) would also pass it. The PR claims relative paths entries resolve against cwd like Node, but the load-bearing Some(p) => p arm has no coverage. Consider adding a positive case that creates a package under a cwd-relative directory and asserts it actually resolves.

Extended reasoning...

What's missing

The resolver.rs change introduces two distinct behaviors for non-absolute custom_dir_paths entries:

let abs_custom = if bun_paths::is_absolute(custom_slice) {
    custom_slice
} else {
    match self.fs_ref().abs_buf_checked(&[custom_slice], &mut abs_buf) {
        Some(p) => p,      // (a) absolutize against top_level_dir and search there
        None => continue,  // (b) skip on failure
    }
};

The new test at line 231 only asserts require.resolve('nonexistent', { paths: ['not/an/absolute/path'] }) throws MODULE_NOT_FOUND. That covers (a) doesn't panic, but it does not prove (a) actually searches the absolutized path.

Step-by-step: the test can't distinguish the fix from a weaker one

  1. Suppose the else-branch were replaced with just continue; — i.e., silently skip every non-absolute entry without absolutizing.
  2. require.resolve('nonexistent', { paths: ['not/an/absolute/path'] }) runs; the resolver sees one non-absolute entry, hits continue, exhausts custom_paths, and returns MODULE_NOT_FOUND.
  3. The test asserts err.code === 'MODULE_NOT_FOUND' → passes.
  4. Now with the real fix: abs_buf_checked returns Some(<cwd>/not/an/absolute/path), check_package_path looks there, finds nothing (the directory doesn't exist), returns MODULE_NOT_FOUND.
  5. The test asserts err.code === 'MODULE_NOT_FOUND' → also passes.

Both implementations produce identical observable behavior for this input. Per REVIEW.md: "confirm deleting each load-bearing clause of your fix breaks at least one test — a test that passes both ways is worse than no test." The Some(p) => p arm is load-bearing for the PR description's claim ("This matches Node, which resolves relative paths entries against cwd"), and deleting it breaks no test.

Why existing coverage doesn't help

The other tests in this file (Module._resolveFilename respects options.paths for package resolution, require.resolve respects options.paths, etc.) all pass absolute temp-dir paths, so they take the is_absolute fast path and never exercise abs_buf_checked at all.

Suggested addition

Something along these lines (mirroring the existing createTempDir pattern in this file, plus a process.chdir so the relative path is deterministic):

test("require.resolve resolves a relative options.paths entry against cwd", () => {
  const { path: dir, cleanup } = createTempDir("require-resolve-relative-paths", {
    "sub/node_modules/rel-pkg/package.json": JSON.stringify({ name: "rel-pkg", main: "index.js" }),
    "sub/node_modules/rel-pkg/index.js": "module.exports = 1;",
  });
  const prev = process.cwd();
  try {
    process.chdir(dir);
    const resolved = require.resolve("rel-pkg", { paths: ["./sub"] });
    expect(resolved).toBe(resolve(dir, "sub/node_modules/rel-pkg/index.js"));
  } finally {
    process.chdir(prev);
    cleanup();
  }
});

This would fail (MODULE_NOT_FOUND) if the resolver merely skipped relative entries, and pass only when abs_buf_checked actually joins against cwd — so it pins the Node-compat behavior the PR description claims.

Severity

nit — the fuzzer-reported panic (the primary bug) is properly regression-tested: a panic would not yield err.code === 'MODULE_NOT_FOUND'. This is a coverage gap on the secondary Node-parity claim, worth adding but not blocking.

Loading