Skip to content

Commit e0e89f2

Browse files
authored
refactor(runtime): one URL parse for every http(s) module entry point (#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 -->
1 parent d401739 commit e0e89f2

25 files changed

Lines changed: 1429 additions & 362 deletions

‎docs/ns-builtin-modules.md‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -506,13 +506,23 @@ works; adding them is a change to this specification first.
506506
507507
Debug builds additionally carry `canonicalizeHttpUrlKey(url)`, a pure test
508508
diagnostic that takes a string and throws
509-
`canonicalizeHttpUrlKey expects a URL string` otherwise; release builds omit
510-
it. Missing members are simply absent — never
509+
`canonicalizeHttpUrlKey expects a URL string` otherwise, and
510+
`remoteUrlMatchesAllowlist(url, entries)`, which returns whether a release
511+
build with `allowRemoteModules` on would fetch `url` under a
512+
`security.remoteModuleAllowlist` of `entries` (`true` for `[]`) and throws
513+
`remoteUrlMatchesAllowlist expects a URL string and an array of strings`
514+
otherwise; release builds omit both. Missing members are simply absent — never
511515
present-but-throwing — so feature checks work. The module is registered in
512516
every build: the security boundary for remote module loading sits at the
513517
network layer (`security.allowRemoteModules` in nativescript.config, enforced
514518
by the HTTP loader), not at the module registry and not at `ns:runtime`.
515519
520+
A `security.remoteModuleAllowlist` array with at least one item is in force:
521+
a URL is fetched only when an entry matches it as a prefix ending at `/`, `?`,
522+
`#` or the end of the URL. When the key is absent, not an array, or an empty
523+
array, every URL is allowed. An item that is not a string, is empty, or is not
524+
valid Unicode matches nothing but still keeps the list in force.
525+
516526
#### Import maps and scopes
517527
518528
`importMap` takes the WHATWG shape:
@@ -541,7 +551,10 @@ A **scope key is matched as a plain prefix of the importing module's canonical
541551
registry key** — an absolute `http(s)` URL for a served module, or a canonical
542552
absolute path for a file on disk. That key is this runtime's analogue of the
543553
web's resolved referrer URL, which is what scope prefixes match in a browser.
544-
End a scope key with `/` to keep it on a directory boundary. Resolution
554+
An `http(s)` scope key is spelled the way registry keys are (see
555+
[Registry canonicalization](#registry-canonicalization)) when the map is
556+
installed, ending in `/` exactly when it is written so. End a scope key with
557+
`/` to keep it on a directory boundary. Resolution
545558
consults the most specific matching scope first (longest prefix wins), then
546559
progressively less specific ones, then `imports` — so a scope can override a
547560
global mapping for one subtree and fall through to it everywhere else. The
@@ -563,23 +576,28 @@ session's vocabulary. Every message is prefixed `configureLoader: `.
563576
| any import-map section other than `imports`/`scopes` | `unsupported import-map section '<name>'; only "imports" and "scopes" are supported` |
564577
| `imports` is not an object | `the "imports" section must be an object` |
565578
| `scopes` is not an object | `the "scopes" section must be an object` |
566-
| non-string scope key | `scopes: every scope key must be a string` |
579+
| non-string scope key, or one with a lone surrogate | `scopes: every scope key must be a string` |
567580
| empty scope key | `scopes: a scope key must not be empty` |
568581
| a scope's value is not an object | `scopes: the map for scope '<scope>' must be an object` |
569582
570583
Inside either section — labelled `imports` or `scope '<scope>'`:
571584
572585
| condition | message |
573586
|---|---|
574-
| non-string specifier key | `<section>: every key must be a string` |
587+
| non-string specifier key, or one with a lone surrogate | `<section>: every key must be a string` |
575588
| empty specifier key | `<section>: a specifier key must not be empty` |
576-
| non-string target | `<section>: the target for '<specifier>' must be a string` |
589+
| non-string target, or one with a lone surrogate | `<section>: the target for '<specifier>' must be a string` |
577590
| empty target | `<section>: the target for '<specifier>' must not be empty` |
591+
| target containing U+0000 | `<section>: the target for '<specifier>' must not contain U+0000` |
578592
| trailing-slash key, non-trailing-slash target | `<section>: the target for '<specifier>' must end with '/' because the specifier key does` |
579593
580594
#### Registry canonicalization
581595
582-
The registry keys modules by a canonical URL. The mechanism — fragment strip,
596+
The registry keys modules by a canonical URL. Before the vocabulary applies,
597+
an absolute http(s) URL is spelled by the WHATWG URL parser with its authority
598+
as written, whichever way it arrives — a specifier from any importer, an
599+
import-map target, or `invalidateModules` — so `HTTP://host/a/../x.js` and
600+
`http:/host/x.js` key as `http://host/x.js`. The mechanism — fragment strip,
583601
cache-buster param drop, param sort — is the runtime's; the *vocabulary* is
584602
server policy, supplied here:
585603
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;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * as dep from "ns-tooling-url-static";

0 commit comments

Comments
 (0)