Skip to content

Commit 3ac5f74

Browse files
committed
fix(runtime): refuse module specifiers containing U+0000
The static resolver, the import() callback and the graph walk read a specifier through Utf8Value as a C string, so everything after a U+0000 was dropped and a different module loaded. They now read it sized by length, and a specifier containing U+0000 is refused from every importer: the static resolver throws and import() rejects with an Error reading `Cannot resolve module specifier "<spec>": a module specifier must not contain U+0000`, U+0000 shown as the text \u0000. The graph walk skips such a specifier and leaves the refusal to the resolver at link time; nothing is fetched. The test server escapes U+0000 in the JS string literals it generates.
1 parent cff1666 commit 3ac5f74

7 files changed

Lines changed: 178 additions & 13 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
globalThis.__nsNulDecoyDynamicEvaluated = true;
2+
3+
export const decoy = "nul-decoy-dynamic";
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
globalThis.__nsNulDecoyStaticEvaluated = true;
2+
3+
export const decoy = "nul-decoy-static";
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function load(spec) {
2+
return import(spec);
3+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { decoy } from "./decoy-static.mjs\u0000junk";
2+
3+
export const value = decoy;

‎test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1727,6 +1727,114 @@ describe("HTTP ESM Loader", function () {
17271727
});
17281728
});
17291729
});
1730+
1731+
// Path and URL APIs read a specifier as a C string, so everything after a
1732+
// U+0000 would be dropped and a different module loaded. A browser would
1733+
// percent-encode it against an http(s) base; the loader refuses it from
1734+
// every importer alike.
1735+
describe("module specifiers containing U+0000", function () {
1736+
useHttpTimeout();
1737+
1738+
var rule = "a module specifier must not contain U+0000";
1739+
1740+
function rejectionOf(promise) {
1741+
return promise.then(function () {
1742+
return null;
1743+
}, function (e) {
1744+
return e;
1745+
});
1746+
}
1747+
1748+
function ruleMessage(shown) {
1749+
return "Cannot resolve module specifier \"" + shown + "\": " + rule;
1750+
}
1751+
1752+
function expectRuleError(e, shown) {
1753+
expect(e instanceof Error).toBe(true);
1754+
expect(String((e && e.message) || e)).toBe(ruleMessage(shown));
1755+
}
1756+
1757+
// A static import that fails to link is reported inside the loader's
1758+
// instantiation-failure wrapper, which ends with the resolver's error.
1759+
function expectLinkRuleError(e, shown) {
1760+
expect(e instanceof Error).toBe(true);
1761+
var message = String((e && e.message) || e);
1762+
var expected = ruleMessage(shown);
1763+
expect(message.slice(-expected.length)).toBe(expected);
1764+
}
1765+
1766+
function requestCount(target) {
1767+
return import(origin + "/esm/request-stats.json?target=" +
1768+
encodeURIComponent(target) + "&n=" + (++requestStatsQueries)).then(function (m) {
1769+
return m.default.count;
1770+
});
1771+
}
1772+
1773+
it("fail a static import from a file module, loading nothing", function (done) {
1774+
rejectionOf(import("~/esm/nul-specifier/static-importer.mjs")).then(function (e) {
1775+
expectLinkRuleError(e, "./decoy-static.mjs\\u0000junk");
1776+
expect(globalThis.__nsNulDecoyStaticEvaluated).toBeUndefined();
1777+
done();
1778+
});
1779+
});
1780+
1781+
it("reject an import() from a file module, loading nothing", function (done) {
1782+
import("~/esm/nul-specifier/dynamic-importer.mjs").then(function (mod) {
1783+
return Promise.all([
1784+
rejectionOf(mod.load("./decoy-dynamic.mjs\u0000junk")),
1785+
rejectionOf(mod.load("./decoy-dynamic.mjs?v=1\u0000junk")),
1786+
]);
1787+
}).then(function (errors) {
1788+
expectRuleError(errors[0], "./decoy-dynamic.mjs\\u0000junk");
1789+
expectRuleError(errors[1], "./decoy-dynamic.mjs?v=1\\u0000junk");
1790+
expect(globalThis.__nsNulDecoyDynamicEvaluated).toBeUndefined();
1791+
done();
1792+
}).catch(function (error) {
1793+
reportRejection(error, done);
1794+
});
1795+
});
1796+
1797+
it("names the specifier with U+0000 spelled as \\u0000", function (done) {
1798+
rejectionOf(import("ns-nul-named\u0000tail")).then(function (e) {
1799+
expectRuleError(e, "ns-nul-named\\u0000tail");
1800+
done();
1801+
});
1802+
});
1803+
1804+
it("rejects an import() from an HTTP module without fetching anything", function (done) {
1805+
withTimeout(import(origin + "/esm/resolve/nul-dynamic/importer.mjs").then(function (mod) {
1806+
return rejectionOf(mod.load("./target.mjs\u0000junk"));
1807+
}).then(function (e) {
1808+
expectRuleError(e, "./target.mjs\\u0000junk");
1809+
return Promise.all([
1810+
requestCount("/esm/resolve/nul-dynamic/target.mjs"),
1811+
requestCount("/esm/resolve/nul-dynamic/target.mjs%00junk"),
1812+
]);
1813+
}), 10000, "nul-dynamic").then(function (counts) {
1814+
expect(counts).toEqual([0, 0]);
1815+
done();
1816+
}).catch(function (error) {
1817+
reportRejection(error, done);
1818+
});
1819+
});
1820+
1821+
it("fails a static import from an HTTP module without fetching anything", function (done) {
1822+
var spec = "./nul-static/target.mjs\u0000junk";
1823+
withTimeout(rejectionOf(import(origin + "/esm/resolve/static.mjs?spec=" +
1824+
encodeURIComponent(spec))).then(function (e) {
1825+
expectLinkRuleError(e, "./nul-static/target.mjs\\u0000junk");
1826+
return Promise.all([
1827+
requestCount("/esm/resolve/nul-static/target.mjs"),
1828+
requestCount("/esm/resolve/nul-static/target.mjs%00junk"),
1829+
]);
1830+
}), 10000, "nul-static").then(function (counts) {
1831+
expect(counts).toEqual([0, 0]);
1832+
done();
1833+
}).catch(function (error) {
1834+
reportRejection(error, done);
1835+
});
1836+
});
1837+
});
17301838
});
17311839

17321840
// A bare `@` is not a specifier the runtime knows: it resolves through the

‎test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,8 @@ private static String jsStringLiteral(String s) {
355355
return s.replace("\\", "\\\\")
356356
.replace("\"", "\\\"")
357357
.replace("\n", "\\n")
358-
.replace("\r", "\\r");
358+
.replace("\r", "\\r")
359+
.replace("\u0000", "\\u0000");
359360
}
360361

361362
private static void respond(Socket socket, String status, String contentType, byte[] body)

‎test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp‎

Lines changed: 56 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1486,6 +1486,35 @@ static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate) {
14861486
static void AsyncGraphEnqueue(const std::shared_ptr<AsyncGraphLoad>& load,
14871487
const ModuleResolution& resolution);
14881488

1489+
// A specifier's UTF-8, sized by length, or nullopt when it contains U+0000:
1490+
// the path and URL APIs behind resolution read C strings and would load
1491+
// whatever precedes it.
1492+
static std::optional<std::string> ModuleSpecifierUtf8(v8::Isolate* isolate,
1493+
v8::Local<v8::String> specifier) {
1494+
v8::String::Utf8Value utf8(isolate, specifier);
1495+
std::string spec = *utf8 ? std::string(*utf8, utf8.length()) : std::string();
1496+
if (spec.find('\0') != std::string::npos) {
1497+
return std::nullopt;
1498+
}
1499+
return spec;
1500+
}
1501+
1502+
static std::string NulSpecifierMessage(v8::Isolate* isolate, v8::Local<v8::String> specifier) {
1503+
v8::String::Utf8Value utf8(isolate, specifier);
1504+
std::string shown;
1505+
if (*utf8) {
1506+
for (int i = 0; i < utf8.length(); i++) {
1507+
if ((*utf8)[i] == '\0') {
1508+
shown += "\\u0000";
1509+
} else {
1510+
shown += (*utf8)[i];
1511+
}
1512+
}
1513+
}
1514+
return "Cannot resolve module specifier \"" + shown +
1515+
"\": a module specifier must not contain U+0000";
1516+
}
1517+
14891518
// Walk `mod`'s static module requests and enqueue every edge the walk can
14901519
// resolve. JS thread only; `moduleKey` is the registry key the module was
14911520
// registered under, which is also the referrer for relative resolution.
@@ -1499,18 +1528,18 @@ static void AsyncGraphWalkModuleRequests(
14991528
v8::Local<v8::ModuleRequest> request =
15001529
requests->Get(i).As<v8::ModuleRequest>();
15011530
if (request.IsEmpty()) continue;
1502-
v8::Local<v8::String> specV8 = request->GetSpecifier();
1503-
v8::String::Utf8Value specUtf8(isolate, specV8);
1504-
if (!*specUtf8) continue;
1531+
// A specifier holding U+0000 is left for the resolver to refuse at link.
1532+
const std::optional<std::string> spec =
1533+
ModuleSpecifierUtf8(isolate, request->GetSpecifier());
1534+
if (!spec.has_value()) continue;
15051535
// Builtins are served by the resolver from the builtin registry, and an
15061536
// unresolved specifier (typically a bare name with no import-map entry,
15071537
// or one an HTTP importer may not use) stays on the resolver's lazy path —
15081538
// where it either resolves later or fails with the resolver's own
15091539
// message. An unmapped bare specifier's subtree is therefore not
15101540
// discovered here; any HTTP edge inside it is pathological and lands on
15111541
// the synchronous anomaly guard.
1512-
const ModuleResolution resolution =
1513-
ResolveSpecifierToPath(*specUtf8, moduleKey);
1542+
const ModuleResolution resolution = ResolveSpecifierToPath(*spec, moduleKey);
15141543
if (resolution.kind != ModuleResolution::Kind::kHttp &&
15151544
resolution.kind != ModuleResolution::Kind::kFile) {
15161545
continue;
@@ -2265,8 +2294,13 @@ v8::MaybeLocal<v8::Module> ResolveModuleCallback(
22652294
return v8::MaybeLocal<v8::Module>();
22662295
}
22672296

2268-
v8::String::Utf8Value specUtf8(isolate, specifier);
2269-
const std::string rawSpec = *specUtf8 ? *specUtf8 : "";
2297+
const std::optional<std::string> spec = ModuleSpecifierUtf8(isolate, specifier);
2298+
if (!spec.has_value()) {
2299+
isolate->ThrowException(v8::Exception::Error(
2300+
ArgConverter::ConvertToV8String(isolate, NulSpecifierMessage(isolate, specifier))));
2301+
return v8::MaybeLocal<v8::Module>();
2302+
}
2303+
const std::string& rawSpec = *spec;
22702304
if (rawSpec.empty()) return v8::MaybeLocal<v8::Module>();
22712305

22722306
const std::string referrerPath =
@@ -2530,9 +2564,21 @@ v8::MaybeLocal<v8::Promise> ImportModuleDynamicallyCallback(
25302564
auto& modulesInFlight = moduleState->modulesInFlight;
25312565
auto& httpDynamicWaiters = moduleState->httpDynamicWaiters;
25322566

2533-
v8::String::Utf8Value specUtf8(isolate, specifier);
2534-
const char* cSpec = (*specUtf8) ? *specUtf8 : "<invalid>";
2535-
TNS_DEBUG(Esm, "[dyn-import] -> %s", cSpec);
2567+
const std::optional<std::string> specUtf8 = ModuleSpecifierUtf8(isolate, specifier);
2568+
if (!specUtf8.has_value()) {
2569+
v8::EscapableHandleScope nulScope(isolate);
2570+
v8::Local<v8::Promise::Resolver> nulResolver;
2571+
if (!v8::Promise::Resolver::New(context).ToLocal(&nulResolver)) {
2572+
return v8::MaybeLocal<v8::Promise>();
2573+
}
2574+
nulResolver
2575+
->Reject(context, v8::Exception::Error(ArgConverter::ConvertToV8String(
2576+
isolate, NulSpecifierMessage(isolate, specifier))))
2577+
.FromMaybe(false);
2578+
return nulScope.Escape(nulResolver->GetPromise());
2579+
}
2580+
std::string rawSpec = *specUtf8;
2581+
TNS_DEBUG(Esm, "[dyn-import] -> %s", rawSpec.c_str());
25362582
if (LogCategoryEnabled(LogCategory::Esm)) {
25372583
v8::Local<v8::Value> resName = resource_name;
25382584
if (!resName.IsEmpty() && resName->IsString()) {
@@ -2543,8 +2589,6 @@ v8::MaybeLocal<v8::Promise> ImportModuleDynamicallyCallback(
25432589
}
25442590
}
25452591

2546-
std::string rawSpec = cSpec ? std::string(cSpec) : std::string();
2547-
25482592
// Builtin modules never touch the loader below; the namespace comes straight
25492593
// from the realm's synthetic module.
25502594
if (NsBuiltinModules::IsBuiltinScheme(rawSpec)) {

0 commit comments

Comments
 (0)