Repository navigation
fix(runtime): U+0000 in specifiers, HTTP-relative worker paths, file-only import.meta.dirname - #614
Merged
Merged
Conversation
…elative workers and import.meta.dirname
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 19 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
edusperoni
added a commit
to NativeScript/android
that referenced
this pull request
Dec 3, 2026
…#2169) ### Description Follow-up to the previous PR in the stack. Every route by which an absolute `http(s)` module URL enters the ES module loader now goes through one parse: the WHATWG URL parser, with the authority kept as written. The hand-written tolerance for malformed URL spellings is removed. The stack's previous PR gave specifiers from an HTTP importer the parser's spelling. Every other route used the raw string, so one module could get two identities. **One shared unit, `ModuleUrl.{h,cpp}`.** It holds `IsHttpRegistryKey`, `ParseModuleUrl`, `NormalizeHttpModuleUrl` and `ReportedModuleUrl`, which used to be static helpers spread over `ModuleInternalCallbacks.cpp` and `HttpLoader.cpp`. `ParseModuleUrl` now swaps only the authority inside the parser's href. Rebuilding from the getters lost a bare trailing `?` or `#`, and the lowercased host then replaced the written one. **One spelling for every entry point.** `NormalizeHttpModuleUrl` spells all of these: - the registry key (`CanonicalizeHttpUrlKey`, `CanonicalizeRegistryKey`, hence `invalidateModules`, `import.meta.url` and `getLoadedModuleUrls()`); - a specifier or import-map target from any importer; - the `import()` HTTP branch, the graph-walk root and the synchronous fallback fetch; - `LoadESModule` roots, the worker entry URL and the `require()` URL guard. The fetched URL and the registry key derive from the same string. Each URL is spelled at most once per key. A string that cannot be an http(s) URL is rejected from its first character, so file paths pay nothing. **Legacy forms are gone.** These are deleted: - the `file://http(s)://…` unwrap; - the collapsed-scheme repair (`RepairLegacyHttpModuleUrl` and its callers); - `HttpUrlEmbeddedInPath`. A collapsed `http:/host/x` still keys as `http://host/x`, because the URL parser reads it that way. A wrapped `file://http://…` is a `file:` URL that names no file: `import()` rejects without fetching. `ModuleTestServer` gained `/esm/request-stats.json`, so a spec can prove nothing was fetched. **One place builds the reported URL.** `ReportedModuleUrl` builds the script origin, `import.meta.url` and the worker inspector URL. The output is unchanged except for the worker inspector URL. That URL used to glue `file://` onto an http(s) or other-scheme script string; it is now that URL. **Remote-module allowlist** (`security.remoteModuleAllowlist`): - Entries are spelled like the URLs they gate when the allowlist is loaded, with the written authority kept. A path-scoped entry such as `https://cdn.example/modules/` no longer matches `…/modules/../../x.js` or `%2e%2e` forms. An entry that is not an http(s) URL stays verbatim, and the prefix-and-boundary rule is unchanged. - A configured list stays in force. A non-empty array applies even when none of its items is usable. An item that is not a string, is empty or has no exact UTF-8 form matches nothing instead of the list falling back to allowing every URL. - Items are read exactly. `AppConfig` reads the array with `optJSONArray`; `optString` would have turned `42` into `"42"`. The items reach native code through `GetStringRegion` and an exact UTF-16→UTF-8 conversion (`ExactUtf8.h`), not JNI modified UTF-8. U+0000 and supplementary characters therefore keep their real bytes, and a lone surrogate is an unusable item. - `InitializeSecurityConfig` builds the config in locals and commits it at the end, so a failure partway through leaves remote modules disabled. - A non-array value no longer aborts the rest of the `package.json` read. **Import maps.** - An http(s) scope key is spelled like the referrer keys it is prefix-matched against when the map is installed. It ends in `/` exactly when it was written so. A key with dot segments, an uppercase scheme or non-ASCII now matches. - A dot-segment key such as `http://host/a/..` must not widen to the prefix `http://host`, which would also match `http://host.evil/`. Only a key written with no path at all drops the parser's trailing slash. - Keys, targets and scope keys are read exactly. A key or scope key containing U+0000 matches only those exact bytes. A target containing U+0000 makes `configureLoader` throw `<section>: the target for '<specifier>' must not contain U+0000`, and the previous map stays in place. A lone surrogate is "not a string". **Specifiers containing U+0000 are refused** (the specifier part of NativeScript/ios#614). Before, the static resolver, the `import()` callback and the graph walk read the specifier as a C string, so `import("./a.mjs\0junk")` loaded `./a.mjs`. Now: - a static import fails to link and `import()` rejects, with ``Cannot resolve module specifier "<spec>": a module specifier must not contain U+0000`` (U+0000 shown as `\u0000`); - the graph walk skips such a specifier, so nothing is fetched. **Java API changes (no deprecation shim):** - `AppConfig.getRemoteModuleAllowlist()` (the `List<String>` getter) is removed. - `Runtime.getRemoteModuleAllowlist()` (still `String[]`) returns the items as read, with a `null` slot for a non-string item, or `null` when the list is not in force (absent, not an array, or empty). - `Runtime.isRemoteUrlAllowed` forwards to the native gate, and the separate Java matcher is removed. Debug builds gain `ns:module.remoteUrlMatchesAllowlist(url, entries)`. It runs the release gate's loading and matching on an explicit list, so the rule can be tested. Release builds omit it. #### Notes for review - **A non-array allowlist still fails open.** When `security.remoteModuleAllowlist` is absent, not an array or `[]`, every URL is allowed. A string or object value is the likeliest config mistake, and it allows every URL. This matches iOS (NativeScript/ios#609); changing it needs a decision on both platforms. - **Redirects are not re-checked against the allowlist.** The gate checks the requested URL. The transport then follows same-protocol redirects without checking the target. This is already true on `main`. The transport PR later in this stack keeps the behaviour, and OkHttp is configured to match it. - **Only the specifier refusal of NativeScript/ios#614 is ported.** Not ported: - resolving a relative `new Worker("./x.js")` / `"../x.js"` path from an HTTP module against the module's URL (item 2 of NativeScript/ios#614) is not handled here; - the `package.json` `main` hardening; - `import.meta.dirname` being absent for URL-keyed modules. Android still gives the URL cut at its last `/`. - **The authority is never canonicalized.** The host case and default port are kept as written, as on iOS. - **The release gate was not run end to end.** The allowlist specs use the debug-only member, which calls the same loading and matching functions. The `package.json` read is covered separately, through `AppConfig.getRemoteModuleAllowlistArray()` on generated config directories. - **The last two commits go beyond NativeScript/ios#609.** They are the U+0000 specifier refusal (from NativeScript/ios#614) and "keep a dot-segment http(s) scope key from widening its scope". Whether iOS has the same scope-key widening has not been checked. ### Does your commit message include the wording below to reference a specific issue in this repo? No issue. ### Related Pull Requests Mirrors NativeScript/ios#609; the first nine commits each name the iOS commit they port. Also ports the U+0000 specifier refusal from NativeScript/ios#614. The allowlist "stays in force" and exact-conversion commits port the same items of NativeScript/ios#609. On Android they also cover the JNI boundary and `AppConfig`. Part of a stack of six; each PR targets the branch below it: 1. #2168 `fix/http-importer-specifiers`: specifier resolution from HTTP importers 2. #2169 `refactor/module-url-parse`: one URL parse for every http(s) entry point (**this PR**) 3. #2170 `perf/http-module-streaming-compile`: compile large HTTP modules off the JS thread 4. #2171 `fix/http-module-fetch-budget`: bound fetches by the graph walk's deadline 5. #2172 `perf/http-module-transport`: persistent connections, per-host-class caps, OkHttp transport 6. #2173 `feat/http-module-cache-controls`: HTTP module cache controls ### Does your pull request have [unit tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)? Yes. - **Pinned first.** The first commit records what the loader does for the URL shapes dev tooling emits. It covers registry keys with and without a tooling-shaped vocabulary, and loads from a file module directly and through an import-map entry. For each it pins `import.meta.url`, `getLoadedModuleUrls()`, the request target the server saw, and eviction by `invalidateModules`. The rest of the PR keeps that table unchanged. - **`testEsmHttpLoader.js`** covers: - absolute URLs from a file module, spelled by the parser with the authority as written; - that a `file://http…` URL is not unwrapped and nothing is fetched; - `require()` of URLs refused whatever the scheme case; - the bare `?`/`#` authority fix; - an `import()` whose map target resolves to nothing; - http(s) scope keys: parser spelling, dot-segment keys not widening, U+0000; - import-map U+0000 and lone-surrogate keys, targets and scopes; - U+0000 specifiers from file and HTTP importers. Static and dynamic imports are both refused, with nothing loaded or fetched. - **`testNsModule.js`**: key spelling, the collapsed scheme, `file://http…` not read as http, and the tooling-shaped vocabulary. - **`testRemoteModuleSecurity.js`**: - the `package.json` read: absent, non-array and empty lists are not in force; null slots; U+0000 and lone surrogates kept exactly; - the matching rule through `remoteUrlMatchesAllowlist`: boundary, dot-segment escape, trailing slash, host compared as written, path spelling, non-URL entries, empty list, unusable items, U+0000. Full suite on the top of the stack (`./gradlew runtestsAndVerifyResults`): 2074 specs, 2068 passed, 0 failed, 6 skipped (the usual GC, native-module and environment skips), on an API 36 arm64 emulator with OkHttp in the test app, at `feat/http-module-cache-controls` 21f87a8. This stays a draft until the stack has been run against a real Vite dev session on Android, which has not happened yet. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Remote module access now supports URL allowlists, with matching that respects URL path boundaries. * Debug builds provide a diagnostic for checking whether a remote URL matches an allowlist. * **Bug Fixes** * Improved HTTP module loading and import-map resolution, including consistent handling of URL scopes and paths. * Module specifiers containing invalid characters are rejected instead of being mistaken for other modules or fetched unexpectedly. * HTTP URL modules are no longer accepted through `require()`. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Three small fixes in the ES module loader:
package.jsonmainare no longer read as C strings.import()callback and the async graph walk read the specifier through one length-exact helper (ModuleSpecifierUtf8).Error, andimport()rejects with anError. The graph walk skips the specifier, so nothing is fetched or read from disk for it.Cannot resolve module specifier "<spec with \u0000 escaped>": a module specifier must not contain U+0000. It is the same in Debug and Release.ModuleInternal::ResolvePathFromPackageJson(therequire()of a package directory):package.jsonwhose top level is not a JSON object is treated like invalid JSON.mainthat is not a string is ignored and resolution falls back toindex, as Node does.mainthat has no exact UTF-8 form, or that contains U+0000, cannot be located. These cases end in the usualUnable to locate main entry in <package.json>error.new Worker("./x.js")/new Worker("../x.js")called from a module loaded over HTTP resolves against that module's URL.ParseModuleUrl), and the worker loads from the resulting http(s) URL through the normal loader path.import.meta.dirnameis defined only for file-backed modules, as in Node. For an http(s),blob:or other URL-keyed module the property is absent ("dirname" in import.meta === false). File modules keep their current value.Why
import("./a.mjs\0junk")loaded./a.mjs, because the specifier went throughv8::String::Utf8Valueand was then used as a C string. The same truncation happened in a static import and in the graph walk's prefetch.package.json.ResolvePathFromPackageJsonusedmainwith no type checks. On the unfixed runtime, three of the new fixtures abort the process on arequire():main:-[NSPathStore2 stringByAppendingPathComponent:]raised an unrecognized-selector exception;maincontaining U+0000:std::stringwas constructed from a NULLUTF8String;objectForKey:was sent to anNSArray.http://host/src/feature/a.ts,new Worker("./w.js")loaded<app>/w.jsfrom disk. Onlyfile://and/callers got caller-relative resolution; every other caller fell through to the app-root join.import.meta.dirname. For a URL module the value was the key cut at its last/, even when that slash was inside the query. For example,http://host/ns/asm?path=/src/app/main.tsgavehttp://host/ns/asm?path=/src/app.Behaviour changes
import x from "./a.mjs\0junk"(file or HTTP importer)./a.mjsErrornaming the U+0000 ruleimport("./a.mjs\0junk")(file or HTTP importer)./a.mjsErrorrequire()of a package whosemainis not a string (e.g.42)indexrequire()of a package whosemaincontains U+0000Unable to locate main entry in …/package.jsonrequire()of a package whosepackage.jsonis a JSON arrayUnable to locate main entry in …/package.jsonrequire()of a package whosemainis a lone surrogate ("a\ud800b")Unable to locate main entry(NSJSONSerialization rejects the file)new Worker("./x.js")/"../x.js"from an HTTP module<app>/x.js(or<app>/../x.js) from disknew Worker(new URL("./x.js", import.meta.url))from an HTTP moduleimport.meta.dirnamein an http(s) module/import.meta.dirnamein ablob:moduleimport.meta.dirnamein a file module/app/<dir>How it was verified
The new specs are in
TestRunner/app/tests/LoaderHardeningTests.jsandTestRunner/app/tests/HttpEsmLoaderTests.js. The test server gained/esm/meta/…and/esm/worker/…routes, and its JS string escaping now covers U+0000.On the unfixed runtime (specs only):
main, then U+0000main, then the arraypackage.json../worker spec and the../worker spec, where the decoy at the app-root join ran and the server saw no request;import.meta.dirnamespec and theblob:import.meta.dirnamespec;file:worker URL from a file module, which is not part of this PR (see Not covered).mainspec;import.meta.dirnamespec;new Worker(new URL("./x.js", import.meta.url))from an HTTP module;new Worker("<absolute http URL>")from a file module.With the fixes:
mainat feat(runtime): load HTTP modules through an HTTP cache over persistent connections #585 (HTTP cache and persistent connections): 2353 cases, 0 failures.mainhas 2339.mainat refactor(runtime): one URL parse for every http(s) module entry point #609: 2352 cases, 0 failures, and the same under AddressSanitizer. The ASan run was not repeated after the merge.NativeScriptscheme forgeneric/platform=iOS Simulator(arm64 and x86_64, with the project's-Werror): succeeded.Not covered
require(),createRequire()and filenew Worker()paths. This PR does not change these paths.[NSString stringWithUTF8String:x.c_str()]orToV8String(isolate, x.c_str())), so a different file can load../or../worker path now goes through the URL parser instead, which percent-encodes the NUL./-rooted or bare are unchanged. A/xpath is still treated as a container-absolute file path, and bare and~/paths still resolve as before.%00when it resolves a specifier against an http(s) base. The loader instead rejects such a specifier from every importer.file:worker URLs from a file module.new Worker(new URL("./x.js", import.meta.url))gives the constructorfile:///app/…. That string is treated as a baretns_modulesname and fails with "Failed to resolve module". This is the behaviour onmainand is not changed here.mainentry.ResolveMainEntryFromPackageJsonalready ignores a non-stringmain.maincontaining U+0000 is unchanged and was not reproduced.mainto the samestringByAppendingPathComponent:/UTF8Stringsequence that aborted for a packagemain.package.json../or../from an HTTP module does not resolve to an http(s) URL, the constructor throws. No spec covers this branch.import.meta.urlasfile:///app/andimport.meta.dirnameas/app.import.metaof a builtin module.import.meta.filenameis not added.