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
17 changes: 16 additions & 1 deletion src/jsc/SavedSourceMap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use core::ffi::c_void;
use std::sync::Arc;

use bun_collections::{HashMap, IdentityContext, TaggedPtrUnion};
use bun_collections::{HashMap, IdentityContext, StringArrayHashMap, TaggedPtrUnion};
use bun_core::MutableString;
use bun_core::Ordinal;
use bun_ptr::tagged_pointer::TagType;
Expand All @@ -16,6 +16,9 @@ use bun_wyhash::hash;
pub struct SavedSourceMap {
/// Only accessed between [`Self::lock`] and [`Self::unlock`].
map: HashTable,
/// Every path ever inserted into `map`, by bytes. `map` keys are hashes,
/// so a membership test for an untrusted path must not go through it.
Comment thread
robobun marked this conversation as resolved.
Resolved
paths: StringArrayHashMap<()>,
mutex: Mutex,
}

Expand Down Expand Up @@ -141,6 +144,7 @@ impl SavedSourceMap {
};
if refers_to_provider {
self.map.remove(&key);
self.paths.swap_remove(path);
// SAFETY: `old_value` was stored by us; the table's ownership of
// it ends here.
unsafe { Self::release_value(old_value) };
Expand Down Expand Up @@ -248,10 +252,21 @@ impl SavedSourceMap {
v.insert(value.ptr());
}
}
if !self.paths.contains(path) {
self.paths.insert(path, ());
}
self.unlock();
Ok(())
}

/// Whether the module loader registered a source map for exactly `path`.
pub(crate) fn has_mapping(&mut self, path: &[u8]) -> bool {
self.lock();
let found = self.paths.contains(path);
self.unlock();
found
}

/// You must call `sourcemap.map.deref()` or you will leak memory
fn get_with_content(
&mut self,
Expand Down
11 changes: 11 additions & 0 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5833,6 +5833,14 @@ impl VirtualMachine {
}

let already_remapped = frames[top].remapped;
// A frame parsed from an `error.stack` string names whatever the thrown
// code chose (`//# sourceURL`). Read it from disk only if the loader loaded it.
Comment thread
robobun marked this conversation as resolved.
Resolved
let allow_source_from_disk = if already_remapped {
let url = frames[top].source_url.to_utf8();
self.source_mappings.has_mapping(url.slice())
Comment thread
robobun marked this conversation as resolved.
Resolved
} else {
true
};
Comment thread
robobun marked this conversation as resolved.
Resolved
let resolved = {
let top_source_url = frames[top].source_url.to_utf8();
let maybe_lookup: Option<bun_sourcemap::mapping::Lookup> = if already_remapped {
Expand Down Expand Up @@ -5900,6 +5908,9 @@ impl VirtualMachine {
// Avoid printing "export default 'native'"
break 'code bun_core::Utf8Bytes::EMPTY;
}
if !allow_source_from_disk {
break 'code bun_core::Utf8Bytes::EMPTY;
}
let mut log = bun_ast::Log::default();
let Ok(original_source) = Self::fetch_without_on_load_plugins(
self,
Expand Down
6 changes: 3 additions & 3 deletions test/js/node/vm/__snapshots__/vm-sourceUrl.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ throw new Error("hello");
Error: hello
at hellohello.js:2:16
at runInNewContext (unknown)
at <anonymous> (<this-url>:6:5)"
at <anonymous> (<this-url>:8:5)"
`;

exports[`can get sourceURL inside node:vm 1`] = `
Expand All @@ -17,7 +17,7 @@ exports[`can get sourceURL inside node:vm 1`] = `
error: hello
at hello (hellohello.js:4:24)
at hellohello.js:7:6
at <anonymous> (<this-url>:21:15)
at <anonymous> (<this-url>:23:15)
"
`;

Expand All @@ -27,6 +27,6 @@ exports[`eval sourceURL is correct 1`] = `
error: hello
at hello (hellohello.js:4:24)
at eval (hellohello.js:7:6)
at <anonymous> (<this-url>:39:15)
at <anonymous> (<this-url>:41:15)
"
`;
76 changes: 75 additions & 1 deletion test/js/node/vm/vm-sourceUrl.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { expect, test } from "bun:test";
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";
import path from "node:path";
import { runInNewContext } from "node:vm";

test("can get sourceURL from eval inside node:vm", () => {
Expand Down Expand Up @@ -50,3 +52,75 @@ hello();
);
expect(err.replaceAll(import.meta.path, "<this-url>")).toMatchSnapshot();
});

const CANARY = "SECRET_CANARY_DO_NOT_LEAK_8f2a";

// The error printer reads a frame's source file from disk for a code-frame
// excerpt. A `//# sourceURL` directive, or a node:vm `filename`, lets the code
// that throws choose that source URL. The printer must not open a file the
// module loader never loaded.
describe.concurrent("error printer does not read attacker-named source files", () => {
for (const via of ["sourceURL", "filename"] as const) {
for (const caught of [true, false]) {
for (const nul of [false, true]) {
const label = `${via}, ${caught ? "caught" : "uncaught"}${nul ? ", interior NUL in the path" : ""}`;
test(`vm code does not leak a named file's contents (${label})`, async () => {
using dir = tempDir("vm-sourceurl-leak", {
"secret.txt": CANARY + "\n",
"run.js": `
const vm = require("node:vm");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const target = process.env.CANARY_PATH + ${JSON.stringify(nul ? "\0.js" : "")};
const code = 'function f(){ throw new Error("boom") }; f()' ${
via === "sourceURL" ? `+ '\\n//# sourceURL=' + target` : ""
};
const options = { filename: ${via === "filename" ? "target" : '"sandbox.js"'} };
${
caught
? `try { vm.runInNewContext(code, {}, options); } catch (e) { console.error(e); }`
: `vm.runInNewContext(code, {}, options);`
}
`,
});

await using proc = Bun.spawn({
cmd: [bunExe(), path.join(String(dir), "run.js")],
env: { ...bunEnv, CANARY_PATH: path.join(String(dir), "secret.txt") },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([
proc.stdout.text(),
proc.stderr.text(),
proc.exited,
]);
const output = stdout + stderr;

// The error is still reported.
expect(output).toContain("boom");
// The file's contents are never shown.
expect(output).not.toContain(CANARY);
// An interior NUL in the name must not crash the printer. An
// uncaught error exits 1, a caught one exits 0.
expect(exitCode).toBe(caught ? 0 : 1);
});
}
}
}
});

test.concurrent("a real module still shows its source code frame", async () => {
using dir = tempDir("vm-sourceurl-real", {
"app.ts": `function doWork(): void {\n throw new Error("real module error");\n}\ndoWork();\n`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), path.join(String(dir), "app.ts")],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
Comment thread
robobun marked this conversation as resolved.
Resolved
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
expect(stderr).toContain("real module error");
// The original source line is read from disk and shown as the code frame.
expect(stderr).toContain(`throw new Error("real module error");`);
expect(exitCode).not.toBe(0);
});
Comment thread
robobun marked this conversation as resolved.
Resolved
Loading