diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index d7424de29..ee1b5ad23 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -506,13 +506,23 @@ works; adding them is a change to this specification first. Debug builds additionally carry `canonicalizeHttpUrlKey(url)`, a pure test diagnostic that takes a string and throws -`canonicalizeHttpUrlKey expects a URL string` otherwise; release builds omit -it. Missing members are simply absent — never +`canonicalizeHttpUrlKey expects a URL string` otherwise, and +`remoteUrlMatchesAllowlist(url, entries)`, which returns whether a release +build with `allowRemoteModules` on would fetch `url` under a +`security.remoteModuleAllowlist` of `entries` (`true` for `[]`) and throws +`remoteUrlMatchesAllowlist expects a URL string and an array of strings` +otherwise; release builds omit both. Missing members are simply absent — never present-but-throwing — so feature checks work. The module is registered in every build: the security boundary for remote module loading sits at the network layer (`security.allowRemoteModules` in nativescript.config, enforced by the HTTP loader), not at the module registry and not at `ns:runtime`. +A `security.remoteModuleAllowlist` array with at least one item is in force: +a URL is fetched only when an entry matches it as a prefix ending at `/`, `?`, +`#` or the end of the URL. When the key is absent, not an array, or an empty +array, every URL is allowed. An item that is not a string, is empty, or is not +valid Unicode matches nothing but still keeps the list in force. + #### Import maps and scopes `importMap` takes the WHATWG shape: @@ -541,7 +551,10 @@ A **scope key is matched as a plain prefix of the importing module's canonical registry key** — an absolute `http(s)` URL for a served module, or a canonical absolute path for a file on disk. That key is this runtime's analogue of the web's resolved referrer URL, which is what scope prefixes match in a browser. -End a scope key with `/` to keep it on a directory boundary. Resolution +An `http(s)` scope key is spelled the way registry keys are (see +[Registry canonicalization](#registry-canonicalization)) when the map is +installed, ending in `/` exactly when it is written so. End a scope key with +`/` to keep it on a directory boundary. Resolution consults the most specific matching scope first (longest prefix wins), then progressively less specific ones, then `imports` — so a scope can override a global mapping for one subtree and fall through to it everywhere else. The @@ -563,7 +576,7 @@ session's vocabulary. Every message is prefixed `configureLoader: `. | any import-map section other than `imports`/`scopes` | `unsupported import-map section ''; only "imports" and "scopes" are supported` | | `imports` is not an object | `the "imports" section must be an object` | | `scopes` is not an object | `the "scopes" section must be an object` | -| non-string scope key | `scopes: every scope key must be a string` | +| non-string scope key, or one with a lone surrogate | `scopes: every scope key must be a string` | | empty scope key | `scopes: a scope key must not be empty` | | a scope's value is not an object | `scopes: the map for scope '' must be an object` | @@ -571,15 +584,20 @@ Inside either section — labelled `imports` or `scope ''`: | condition | message | |---|---| -| non-string specifier key | `
: every key must be a string` | +| non-string specifier key, or one with a lone surrogate | `
: every key must be a string` | | empty specifier key | `
: a specifier key must not be empty` | -| non-string target | `
: the target for '' must be a string` | +| non-string target, or one with a lone surrogate | `
: the target for '' must be a string` | | empty target | `
: the target for '' must not be empty` | +| target containing U+0000 | `
: the target for '' must not contain U+0000` | | trailing-slash key, non-trailing-slash target | `
: the target for '' must end with '/' because the specifier key does` | #### Registry canonicalization -The registry keys modules by a canonical URL. The mechanism — fragment strip, +The registry keys modules by a canonical URL. Before the vocabulary applies, +an absolute http(s) URL is spelled by the WHATWG URL parser with its authority +as written, whichever way it arrives — a specifier from any importer, an +import-map target, or `invalidateModules` — so `HTTP://host/a/../x.js` and +`http:/host/x.js` key as `http://host/x.js`. The mechanism — fragment strip, cache-buster param drop, param sort — is the runtime's; the *vocabulary* is server policy, supplied here: diff --git a/test-app/app/src/main/assets/app/esm/nul-specifier/decoy-dynamic.mjs b/test-app/app/src/main/assets/app/esm/nul-specifier/decoy-dynamic.mjs new file mode 100644 index 000000000..ba7324c08 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/nul-specifier/decoy-dynamic.mjs @@ -0,0 +1,3 @@ +globalThis.__nsNulDecoyDynamicEvaluated = true; + +export const decoy = "nul-decoy-dynamic"; diff --git a/test-app/app/src/main/assets/app/esm/nul-specifier/decoy-static.mjs b/test-app/app/src/main/assets/app/esm/nul-specifier/decoy-static.mjs new file mode 100644 index 000000000..de9952582 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/nul-specifier/decoy-static.mjs @@ -0,0 +1,3 @@ +globalThis.__nsNulDecoyStaticEvaluated = true; + +export const decoy = "nul-decoy-static"; diff --git a/test-app/app/src/main/assets/app/esm/nul-specifier/dynamic-importer.mjs b/test-app/app/src/main/assets/app/esm/nul-specifier/dynamic-importer.mjs new file mode 100644 index 000000000..0712d2d4b --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/nul-specifier/dynamic-importer.mjs @@ -0,0 +1,3 @@ +export function load(spec) { + return import(spec); +} diff --git a/test-app/app/src/main/assets/app/esm/nul-specifier/static-importer.mjs b/test-app/app/src/main/assets/app/esm/nul-specifier/static-importer.mjs new file mode 100644 index 000000000..2aecc34c0 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/nul-specifier/static-importer.mjs @@ -0,0 +1,3 @@ +import { decoy } from "./decoy-static.mjs\u0000junk"; + +export const value = decoy; diff --git a/test-app/app/src/main/assets/app/esm/tooling-url/static-importer.mjs b/test-app/app/src/main/assets/app/esm/tooling-url/static-importer.mjs new file mode 100644 index 000000000..d4c10436f --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/tooling-url/static-importer.mjs @@ -0,0 +1 @@ +export * as dep from "ns-tooling-url-static"; diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 51966949d..f031593e6 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -3,6 +3,9 @@ // platforms. var appRoot = __dirname.replace(/\/tests$/, ""); var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); +// The stats route is imported as a JSON module, so each query needs its own +// URL or the registry answers with the first count. +var requestStatsQueries = 0; describe("HTTP ESM Loader", function () { @@ -536,6 +539,108 @@ describe("HTTP ESM Loader", function () { }); }); + it("matches an http(s) scope the way the URL parser spells it", function (done) { + var base = origin + "/esm/resolve/scope-norm"; + var scopes = {}; + scopes[base + "/x/../dots/"] = { "ns-scope-norm": base + "/target.mjs?k=dots" }; + scopes[base + "/m\u00f6dir/"] = { "ns-scope-norm": base + "/target.mjs?k=nonascii" }; + // No trailing slash: still a plain prefix, here inside a segment. + scopes[base + "/pla"] = { "ns-scope-norm": base + "/target.mjs?k=plain" }; + scopes[origin] = { "ns-scope-norm-origin": base + "/target.mjs?k=origin" }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + function load(dir, spec) { + return importer(origin, "scope-norm/" + dir).then(function (mod) { + return mod.load(spec); + }); + } + Promise.all([ + load("dots", "ns-scope-norm"), + load("m\u00f6dir", "ns-scope-norm"), + load("plain", "ns-scope-norm"), + load("dots", "ns-scope-norm-origin"), + ]).then(function (mods) { + expect(mods.map(function (m) { return m.query; })) + .toEqual(["k=dots", "k=nonascii", "k=plain", "k=origin"]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("does not widen an http(s) scope whose key ends in a dot segment", function (done) { + var base = origin + "/esm/resolve/scope-dot-end"; + var scopes = {}; + scopes[base + "/sub/."] = { "ns-scope-dot-end": base + "/target.mjs?k=sub" }; + scopes[base + "/up/a/.."] = { "ns-scope-dot-end": base + "/target.mjs?k=up" }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + function load(dir) { + return importer(origin, "scope-dot-end/" + dir).then(function (mod) { + return mod.load("ns-scope-dot-end").then(function (m) { + return m.query; + }, function (error) { + return String((error && error.message) || error); + }); + }); + } + Promise.all([load("sub"), load("subx"), load("up"), load("upx")]).then(function (r) { + expect(r[0]).toBe("k=sub"); + expect(r[1]).toContain("it is not in the import map"); + expect(r[2]).toBe("k=up"); + expect(r[3]).toContain("it is not in the import map"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("keeps an http(s) scope key containing U+0000 whole", function (done) { + var base = origin + "/esm/resolve/nul-scope"; + var scopes = {}; + scopes[base + "/a\u0000/b/"] = { "ns-nul-scope": base + "/target.mjs?k=nul" }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + importer(origin, "nul-scope/a").then(function (mod) { + return rejectionMessage(mod.load("ns-nul-scope")); + }).then(function (message) { + expect(message).toContain("not in the import map"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("rejects an import() whose import-map target resolves to nothing", function (done) { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-tail-a": "ns-tail-b", + "ns-tail-b": "~/esm/query-map/literal.mjs", + }, + }, + }); + importer(origin, "tail").then(function (mod) { + return rejectionMessage(mod.load("ns-tail-a")); + }).then(function (message) { + expect(message).toContain("Cannot find module 'ns-tail-b'"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("keeps the importer's origin as written when the query or fragment is empty", + function (done) { + var written = origin.replace("127.0.0.1", "LOCALHOST"); + importer(written, "authority-empty").then(function (mod) { + return Promise.all([mod.load("./query.mjs?"), mod.load("./hash.mjs#")]); + }).then(function (mods) { + expect(mods[0].url).toBe(written + "/esm/resolve/authority-empty/query.mjs?"); + expect(mods[1].url).toBe(written + "/esm/resolve/authority-empty/hash.mjs"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("normalizes a specifier the way the WHATWG URL parser does", function (done) { importer(origin, "norm").then(function (mod) { return Promise.all([ @@ -806,6 +911,53 @@ describe("HTTP ESM Loader", function () { }).toThrowError(TypeError, /must be a string/); }); + it("rejects a target containing U+0000 and keeps the previous map", function (done) { + setMap({ imports: { "ns-nul-prev": "~/esm/query-map/stripped.mjs" } }); + expect(function () { + setMap({ + imports: { + "ns-nul-target": "~/esm/query-map/literal.mjs\u0000/../../x.mjs", + }, + }); + }).toThrowError(TypeError, + "configureLoader: imports: the target for 'ns-nul-target' " + + "must not contain U+0000"); + import("ns-nul-prev").then(function (ns) { + expect(ns.name).toBe("stripped"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("matches a specifier key containing U+0000 whole", function (done) { + setMap({ imports: { "ns-nul-key\u0000x": "~/esm/query-map/literal.mjs" } }); + import("ns-nul-key").then(function () { + expect("resolved").toBe("rejected"); + done(); + }, function (error) { + expect(String((error && error.message) || error)).toContain("Cannot find module"); + done(); + }); + }); + + it("rejects a key, target or scope key with a lone surrogate as not a string", + function () { + var scopes = {}; + scopes["/a\uD800/"] = { "pkg": "~/esm/query-map/literal.mjs" }; + expect(function () { + setMap({ imports: { "pkg\uD800": "~/esm/query-map/literal.mjs" } }); + }).toThrowError(TypeError, "configureLoader: imports: every key must be a string"); + expect(function () { + setMap({ imports: { "pkg": "~/esm/query-map/literal\uDC00.mjs" } }); + }).toThrowError(TypeError, + "configureLoader: imports: the target for 'pkg' must be a string"); + expect(function () { + setMap({ imports: {}, scopes: scopes }); + }).toThrowError(TypeError, "configureLoader: scopes: every scope key must be a string"); + }); + it("rejects a non-object scope map", function () { expect(function () { setMap({ scopes: { "/a/": "not-an-object" } }); @@ -1436,6 +1588,279 @@ describe("HTTP ESM Loader", function () { }); }); }); + + // The spelling of these URLs is what dev tooling compares module URLs + // against, so it must survive every route into the loader byte for byte. + describe("module URLs in the shapes dev tooling emits", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + // Each module reports the request target the server saw and its own + // import.meta.url. + function expectSpelledAsWritten(ns, url) { + var target = url.slice(url.indexOf("/", url.indexOf("://") + 3)); + var q = target.indexOf("?"); + expect(ns.url).toBe(url); + expect(ns.path).toBe(q < 0 ? target : target.slice(0, q)); + expect(ns.query).toBe(q < 0 ? "" : target.slice(q + 1)); + expect(nsModule.getLoadedModuleUrls()).toContain(url); + } + + function expectEvicted(urls) { + nsModule.invalidateModules(urls); + var loaded = nsModule.getLoadedModuleUrls(); + urls.forEach(function (url) { + expect(loaded).not.toContain(url); + }); + } + + it("keeps them as written when a file module imports them", function (done) { + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var base = origin + "/esm/resolve/tooling-direct"; + var urls = [ + base + "/ns/m/src/app.ts?v=abc", + base + "/ns/core/index.js", + base + "/ns/node/x", + base + "/ns/m/node_modules/pkg/index.js", + base + "/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + base + "/ns/asm?path=/src/App.vue&mode=inline", + base + "/ns/sfc/src/App.vue?vue&type=script", + base + "/ns/m/q.js?b=2&a=1", + base + "/@ng/component?c=x&t=1", + base + "/@id/__x00__virtual:thing", + base + "/@fs/Users/me/proj/x.ts", + written + "/esm/resolve/tooling-direct/ns/m/upper.js?v=1", + ]; + Promise.all(urls.map(function (url) { + return import(url); + })).then(function (namespaces) { + namespaces.forEach(function (ns, i) { + expectSpelledAsWritten(ns, urls[i]); + }); + expectEvicted(urls); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("keeps them as written when an import-map entry targets them", function (done) { + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var base = origin + "/esm/resolve/tooling-mapped"; + var dynamicUrl = base + "/ns/m/src/dynamic.ts?v=abc"; + var staticUrl = base + "/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline"; + var upperUrl = written + "/esm/resolve/tooling-mapped/ns/m/upper.js?b=2&a=1"; + nsModule.configureLoader({ + importMap: { + imports: { + "ns-tooling-url-dynamic": dynamicUrl, + "ns-tooling-url-static": staticUrl, + "ns-tooling-url-upper": upperUrl, + }, + }, + }); + Promise.all([ + import("ns-tooling-url-dynamic"), + import("~/esm/tooling-url/static-importer.mjs"), + import("ns-tooling-url-upper"), + ]).then(function (namespaces) { + expectSpelledAsWritten(namespaces[0], dynamicUrl); + expectSpelledAsWritten(namespaces[1].dep, staticUrl); + expectSpelledAsWritten(namespaces[2], upperUrl); + expectEvicted([dynamicUrl, staticUrl, upperUrl]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + + describe("absolute http(s) URLs from a file module", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + it("are spelled by the URL parser, keeping the authority as written", function (done) { + var hostport = origin.replace(/^http:\/\//, ""); + var base = origin + "/esm/resolve/file-abs"; + nsModule.configureLoader({ + importMap: { imports: { "ns-file-abs-mapped": base + "/mapped/../mapped.mjs" } }, + }); + Promise.all([ + import("HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"), + import("http:/" + hostport + "/esm/resolve/file-abs/collapsed.mjs?k=1"), + import(base + "/sub/../dots.mjs"), + import(base + "/m\u00f6dule.mjs"), + import("ns-file-abs-mapped"), + ]).then(function (mods) { + expect(mods.map(function (m) { return m.url; })).toEqual([ + base + "/upper.mjs", + base + "/collapsed.mjs?k=1", + base + "/dots.mjs", + base + "/m%C3%B6dule.mjs", + base + "/mapped.mjs", + ]); + expect(mods.map(function (m) { return m.path + "?" + m.query; })).toEqual([ + "/esm/resolve/file-abs/upper.mjs?", + "/esm/resolve/file-abs/collapsed.mjs?k=1", + "/esm/resolve/file-abs/dots.mjs?", + "/esm/resolve/file-abs/m%C3%B6dule.mjs?", + "/esm/resolve/file-abs/mapped.mjs?", + ]); + nsModule.invalidateModules(["HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"]); + expect(nsModule.getLoadedModuleUrls()).not.toContain(base + "/upper.mjs"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("are not unwrapped from a file:// URL", function (done) { + var target = "/esm/resolve/file-abs/wrapped.mjs"; + import("file://" + origin + target).then(function () { + expect("resolved").toBe("rejected"); + }, function (error) { + expect(String((error && error.message) || error)).toContain("Cannot find module"); + }).then(function () { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target) + "&n=" + (++requestStatsQueries)); + }).then(function (stats) { + expect(stats.default.count).toBe(0); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("are refused by require() whatever their scheme's case", function () { + ["http://h/x.js", "HTTP://h/x.js"].forEach(function (url) { + var message = ""; + try { + require(url); + } catch (e) { + message = String((e && e.message) || e); + } + expect(message).toContain("require() of URL module is not supported: " + url); + }); + }); + }); + + // Path and URL APIs read a specifier as a C string, so everything after a + // U+0000 would be dropped and a different module loaded. A browser would + // percent-encode it against an http(s) base; the loader refuses it from + // every importer alike. + describe("module specifiers containing U+0000", function () { + useHttpTimeout(); + + var rule = "a module specifier must not contain U+0000"; + + function rejectionOf(promise) { + return promise.then(function () { + return null; + }, function (e) { + return e; + }); + } + + function ruleMessage(shown) { + return "Cannot resolve module specifier \"" + shown + "\": " + rule; + } + + function expectRuleError(e, shown) { + expect(e instanceof Error).toBe(true); + expect(String((e && e.message) || e)).toBe(ruleMessage(shown)); + } + + // A static import that fails to link is reported inside the loader's + // instantiation-failure wrapper, which ends with the resolver's error. + function expectLinkRuleError(e, shown) { + expect(e instanceof Error).toBe(true); + var message = String((e && e.message) || e); + var expected = ruleMessage(shown); + expect(message.slice(-expected.length)).toBe(expected); + } + + function requestCount(target) { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target) + "&n=" + (++requestStatsQueries)).then(function (m) { + return m.default.count; + }); + } + + it("fail a static import from a file module, loading nothing", function (done) { + rejectionOf(import("~/esm/nul-specifier/static-importer.mjs")).then(function (e) { + expectLinkRuleError(e, "./decoy-static.mjs\\u0000junk"); + expect(globalThis.__nsNulDecoyStaticEvaluated).toBeUndefined(); + done(); + }); + }); + + it("reject an import() from a file module, loading nothing", function (done) { + import("~/esm/nul-specifier/dynamic-importer.mjs").then(function (mod) { + return Promise.all([ + rejectionOf(mod.load("./decoy-dynamic.mjs\u0000junk")), + rejectionOf(mod.load("./decoy-dynamic.mjs?v=1\u0000junk")), + ]); + }).then(function (errors) { + expectRuleError(errors[0], "./decoy-dynamic.mjs\\u0000junk"); + expectRuleError(errors[1], "./decoy-dynamic.mjs?v=1\\u0000junk"); + expect(globalThis.__nsNulDecoyDynamicEvaluated).toBeUndefined(); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("names the specifier with U+0000 spelled as \\u0000", function (done) { + rejectionOf(import("ns-nul-named\u0000tail")).then(function (e) { + expectRuleError(e, "ns-nul-named\\u0000tail"); + done(); + }); + }); + + it("rejects an import() from an HTTP module without fetching anything", function (done) { + withTimeout(import(origin + "/esm/resolve/nul-dynamic/importer.mjs").then(function (mod) { + return rejectionOf(mod.load("./target.mjs\u0000junk")); + }).then(function (e) { + expectRuleError(e, "./target.mjs\\u0000junk"); + return Promise.all([ + requestCount("/esm/resolve/nul-dynamic/target.mjs"), + requestCount("/esm/resolve/nul-dynamic/target.mjs%00junk"), + ]); + }), 10000, "nul-dynamic").then(function (counts) { + expect(counts).toEqual([0, 0]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("fails a static import from an HTTP module without fetching anything", function (done) { + var spec = "./nul-static/target.mjs\u0000junk"; + withTimeout(rejectionOf(import(origin + "/esm/resolve/static.mjs?spec=" + + encodeURIComponent(spec))).then(function (e) { + expectLinkRuleError(e, "./nul-static/target.mjs\\u0000junk"); + return Promise.all([ + requestCount("/esm/resolve/nul-static/target.mjs"), + requestCount("/esm/resolve/nul-static/target.mjs%00junk"), + ]); + }), 10000, "nul-static").then(function (counts) { + expect(counts).toEqual([0, 0]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); }); // A bare `@` is not a specifier the runtime knows: it resolves through the diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index b3597024e..e74d98be2 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -16,7 +16,7 @@ describe("ns:module", function () { var expected = ["configureLoader", "createPumpingRequire", "createRequire", "getLoadedModuleUrls", "invalidateModules"]; if (typeof nsModule.canonicalizeHttpUrlKey === "function") { - expected.push("canonicalizeHttpUrlKey"); + expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist"); } expect(Object.keys(nsModule).sort()).toEqual(expected.sort()); }); @@ -47,6 +47,8 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { return require("ns:module").canonicalizeHttpUrlKey; } + // A registered key is canonicalized again whenever it is looked up, so a key + // must be a fixed point. function checkKey(input, expected) { var canon = getCanon(); if (typeof canon !== "function") { @@ -54,8 +56,77 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { return; } expect(canon(input)).toBe(expected); + expect(canon(expected)).toBe(expected); } + // [input, key with no vocabulary, key under TOOLING_VOCABULARY] + var TOOLING_URLS = [ + ["http://h:5173/ns/m/src/app.ts?v=abc", + "http://h:5173/ns/m/src/app.ts?v=abc", + "http://h:5173/ns/m/src/app.ts"], + ["http://h:5173/ns/core/index.js", + "http://h:5173/ns/core/index.js", + "http://h:5173/ns/core/index.js"], + ["http://h:5173/ns/node/x", + "http://h:5173/ns/node/x", + "http://h:5173/ns/node/x"], + ["http://h:5173/ns/m/node_modules/pkg/index.js?v=abc", + "http://h:5173/ns/m/node_modules/pkg/index.js?v=abc", + "http://h:5173/ns/m/node_modules/pkg/index.js"], + ["http://h:5173/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + "http://h:5173/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + "http://h:5173/ns/asm?mode=inline&path=%2Fsrc%2FApp.vue"], + ["http://h:5173/ns/asm?path=/src/App.vue&mode=inline", + "http://h:5173/ns/asm?path=/src/App.vue&mode=inline", + "http://h:5173/ns/asm?mode=inline&path=/src/App.vue"], + ["http://h:5173/ns/sfc/src/App.vue?vue&type=script", + "http://h:5173/ns/sfc/src/App.vue?vue&type=script", + "http://h:5173/ns/sfc/src/App.vue?type=script&vue"], + ["http://h:5173/ns/m/q.js?b=2&a=1", + "http://h:5173/ns/m/q.js?b=2&a=1", + "http://h:5173/ns/m/q.js?a=1&b=2"], + ["http://h:5173/@ng/component?c=x&t=1", + "http://h:5173/@ng/component?c=x&t=1", + "http://h:5173/@ng/component?c=x&t=1"], + ["http://h:5173/@id/__x00__virtual:thing?import", + "http://h:5173/@id/__x00__virtual:thing?import", + "http://h:5173/@id/__x00__virtual:thing"], + ["http://h:5173/@fs/Users/me/proj/x.ts?t=1", + "http://h:5173/@fs/Users/me/proj/x.ts?t=1", + "http://h:5173/@fs/Users/me/proj/x.ts"], + ["http://h:5173/node_modules/.vite/deps/pkg.js?v=abc", + "http://h:5173/node_modules/.vite/deps/pkg.js?v=abc", + "http://h:5173/node_modules/.vite/deps/pkg.js"], + ["http://MyMac.local:5173/ns/m/app.js?v=1", + "http://MyMac.local:5173/ns/m/app.js?v=1", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://MyMac.local:5173/ns/m/app.js?", + "http://MyMac.local:5173/ns/m/app.js?", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://MyMac.local:5173/ns/m/app.js#", + "http://MyMac.local:5173/ns/m/app.js", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://h:80/ns/m/app.js?v=1", + "http://h:80/ns/m/app.js?v=1", + "http://h:80/ns/m/app.js"], + ["http://192.168.1.20:5173/ns/m/app.js?v=1", + "http://192.168.1.20:5173/ns/m/app.js?v=1", + "http://192.168.1.20:5173/ns/m/app.js"], + ["http://[::1]:5173/ns/m/app.js?v=1", + "http://[::1]:5173/ns/m/app.js?v=1", + "http://[::1]:5173/ns/m/app.js"], + // The URL parser rejects a zone id; the key keeps the URL as written. + ["http://[fe80::1%25en0]:5173/ns/m/app.js?v=1#x", + "http://[fe80::1%25en0]:5173/ns/m/app.js?v=1", + "http://[fe80::1%25en0]:5173/ns/m/app.js"], + ]; + + var TOOLING_VOCABULARY = { + stripParams: ["t", "v", "import"], + forPathPrefixes: ["/ns/", "/@id/", "/@fs/", "/node_modules/.vite/"], + preserveQueryFor: ["/@ng/component"], + }; + it("is exposed as a function in debug builds", function () { var canon = getCanon(); if (typeof canon !== "function") { @@ -89,6 +160,67 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { checkKey("https://cdn.example.com/lib.js?token=abc#frag", "https://cdn.example.com/lib.js?token=abc"); }); + + // The URL parser reads `http:/host` as `http://host`, so a key that + // arrives collapsed, through invalidateModules say, lands on the same + // identity the resolver produces. + it("repairs a collapsed scheme to one identity", function () { + checkKey("http:/h/ns/core", "http://h/ns/core"); + checkKey("https:/h/ns/core", "https://h/ns/core"); + checkKey("http://h/ns/core", "http://h/ns/core"); + }); + + it("does not read an http URL inside a file:// URL as an http key", function () { + checkKey("file://http:/h/ns/core", "file://http:/h/ns/core"); + checkKey("file://https:/h/ns/core", "file://https:/h/ns/core"); + checkKey("file://http://h/ns/core", "file://http://h/ns/core"); + }); + + it("spells a URL the way the URL parser does, authority aside", function () { + checkKey("HTTP://h/x", "http://h/x"); + checkKey("http:h/x", "http://h/x"); + checkKey(" http://h/x", "http://h/x"); + checkKey("\t\n HTTPS://h/x", "https://h/x"); + checkKey("h\tttp://h/x", "http://h/x"); + checkKey("http://h", "http://h/"); + checkKey("http://h?x", "http://h/?x"); + checkKey("http://h/a/../b.js", "http://h/b.js"); + checkKey("http://h/%2e%2e/b.js", "http://h/b.js"); + checkKey("http://h\\x\\y.js", "http://h/x/y.js"); + checkKey("http://h/m\u00f6dule.js", "http://h/m%C3%B6dule.js"); + checkKey("http://h/a b.js?q=a b", "http://h/a%20b.js?q=a%20b"); + checkKey("http://H:80/x?", "http://H:80/x?"); + }); + + it("keeps the URLs dev tooling emits as written", function () { + TOOLING_URLS.forEach(function (row) { + checkKey(row[0], row[1]); + }); + }); + }); + + describe("with a tooling-shaped vocabulary", function () { + beforeEach(function () { + if (typeof getCanon() !== "function") { + return; + } + require("ns:module").configureLoader({ canonicalization: TOOLING_VOCABULARY }); + }); + + afterEach(function () { + if (typeof getCanon() !== "function") { + return; + } + require("ns:module").configureLoader({ + canonicalization: { stripParams: [], forPathPrefixes: [], preserveQueryFor: [] }, + }); + }); + + it("keys the URLs dev tooling emits", function () { + TOOLING_URLS.forEach(function (row) { + checkKey(row[0], row[2]); + }); + }); }); // The canonicalization vocabulary is per-isolate loader state, so each spec diff --git a/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js b/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js index a53474d9b..095a80e74 100644 --- a/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js +++ b/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js @@ -110,6 +110,57 @@ describe("Remote Module Security", function() { }); }); + // The config array reaches the native gate raw: AppConfig keeps the list + // in force whenever the array has an item, and keeps each string item + // exactly as parsed, so the gate alone decides what an item matches. + describe("security.remoteModuleAllowlist as read from package.json", function() { + function readAllowlist(allowlistJson) { + var dir = java.io.File.createTempFile("ns-appconfig", ""); + dir["delete"](); + var appDir = new java.io.File(dir, "app"); + appDir.mkdirs(); + var json = '{"security":{"allowRemoteModules":true' + + (allowlistJson === undefined ? "" : ',"remoteModuleAllowlist":' + allowlistJson) + "}}"; + var out = new java.io.FileOutputStream(new java.io.File(appDir, "package.json")); + try { + out.write(new java.lang.String(json).getBytes("UTF-8")); + } finally { + out.close(); + } + try { + var items = new com.tns.AppConfig(dir).getRemoteModuleAllowlistArray(); + if (items === null) { + return null; + } + var result = []; + for (var i = 0; i < items.length; i++) { + result.push(items[i]); + } + return result; + } finally { + new java.io.File(appDir, "package.json")["delete"](); + appDir["delete"](); + dir["delete"](); + } + } + + it("is not in force when absent, not an array, or empty", function() { + expect(readAllowlist(undefined)).toBeNull(); + expect(readAllowlist('"https://cdn.example/"')).toBeNull(); + expect(readAllowlist("[]")).toBeNull(); + }); + + it("keeps every item, with a null slot for one that is not a string", function() { + expect(readAllowlist('[42, null, true, "", "https://cdn.example/"]')) + .toEqual([null, null, null, "", "https://cdn.example/"]); + }); + + it("keeps a string item exactly, U+0000 and lone surrogates included", function() { + expect(readAllowlist('["https://cdn.example\\u0000/private/", "\\ud800"]')) + .toEqual(["https://cdn.example\u0000/private/", "\ud800"]); + }); + }); + describe("URL Allowlist Matching", function() { it("should match URLs in the allowlist (esm.sh)", function() { @@ -132,10 +183,10 @@ describe("Remote Module Security", function() { }); it("should refuse lookalike-host prefixes at a URL-component boundary (Java helper)", function() { - // The Java helper is the production-path twin of the native gate. - // Debug still short-circuits to true, so this only asserts the - // helper exists and debug bypass still holds; production matching - // is covered by the native RemoteUrlMatchesAllowlistEntry logic. + // The Java helper answers through the native gate. Debug still + // short-circuits to true, so this only asserts the helper exists + // and debug bypass still holds; the release rule is covered by + // the remoteUrlMatchesAllowlist specs below. expect(typeof com.tns.Runtime.isRemoteUrlAllowed).toBe("function"); expect(com.tns.Runtime.isRemoteUrlAllowed("https://cdn.example.com.attacker.com/x.js")).toBe(true); }); @@ -180,4 +231,133 @@ describe("Remote Module Security", function() { }); }); }); + + // The release allowlist rule, through the debug-only diagnostic that runs + // it: debug builds never gate a fetch on it. + describe("Allowlist rule (ns:module remoteUrlMatchesAllowlist)", function() { + function matches(url, entries) { + var fn = require("ns:module").remoteUrlMatchesAllowlist; + if (typeof fn !== "function") { + pending("ns:module.remoteUrlMatchesAllowlist not exposed (release build)"); + return undefined; + } + return fn(url, entries); + } + + function expectRows(entry, rows) { + rows.forEach(function (row) { + var actual = matches(row[0], [entry]); + if (actual === undefined) { + return; + } + expect(entry + " vs " + row[0] + ": " + actual).toBe(entry + " vs " + row[0] + ": " + row[1]); + }); + } + + it("matches a plain entry by prefix at a component boundary", function() { + expectRows("https://cdn.example", [ + ["https://cdn.example/x.js", true], + ["https://cdn.example", true], + ["https://cdn.example.evil/x.js", false], + ["https://cdn.example@evil/x.js", false], + ["https://cdn.example:9999/x.js", false], + ]); + }); + + it("keeps a path-scoped entry from being escaped by dot segments", function() { + expectRows("https://cdn.example/modules/", [ + ["https://cdn.example/modules/x.js", true], + ["https://cdn.example/modules/../../x.js", false], + ["https://cdn.example/modules/%2e%2e/x.js", false], + ["https://cdn.example/other/../modules/x.js", true], + ]); + }); + + it("treats an entry with and without a trailing slash by the boundary rule", function() { + expectRows("https://cdn.example/modules", [ + ["https://cdn.example/modules/x.js", true], + ["https://cdn.example/modules?v=1", true], + ["https://cdn.example/modulesx/y.js", false], + ]); + expectRows("https://cdn.example/modules/", [ + ["https://cdn.example/modules", false], + ["https://cdn.example/modulesx/y.js", false], + ]); + }); + + it("compares the host as written", function() { + expectRows("https://CDN.example/modules/", [ + ["https://CDN.example/modules/x.js", true], + ["https://cdn.example/modules/x.js", false], + ]); + expectRows("HTTPS://cdn.example/modules/", [ + ["https://cdn.example/modules/x.js", true], + ]); + }); + + it("spells an entry's path the way fetched URLs are spelled", function() { + expectRows("https://cdn.example/m\u00f6dule/", [ + ["https://cdn.example/m\u00f6dule/x.js", true], + ["https://cdn.example/m%C3%B6dule/x.js", true], + ]); + }); + + it("keeps an entry that is not a parseable http(s) URL verbatim", function() { + expectRows("https://[fe80::1%25en0]/", [ + ["https://[fe80::1%25en0]/x.js", true], + ]); + expectRows("cdn.example/", [ + ["https://cdn.example/x.js", false], + ]); + }); + + function expectLists(url, rows) { + rows.forEach(function (row) { + var actual = matches(url, row[0]); + if (actual === undefined) { + return; + } + var label = JSON.stringify(row[0]) + " vs " + JSON.stringify(url) + ": "; + expect(label + actual).toBe(label + row[1]); + }); + } + + it("allows every URL only when the list is empty", function() { + expectLists("https://cdn.example/x.js", [ + [[], true], + [[""], false], + [["", "https://cdn.example/"], true], + [["", "https://other.example/"], false], + [["https://other.example/", "https://cdn.example/lib/"], false], + ]); + }); + + it("lets an item with no exact UTF-8 form match nothing", function() { + expectLists("https://cdn.example/x.js", [ + [["\uD800"], false], + [["\uD800", "https://cdn.example/"], true], + ]); + }); + + it("keeps an entry with an embedded U+0000 whole", function() { + var entry = "https://cdn.example\u0000/private/"; + expectLists("https://cdn.example/other.js", [[[entry], false]]); + expectLists("https://cdn.example/private/x.js", [[[entry], false]]); + expectLists(entry + "x.js", [[[entry], true]]); + }); + + it("rejects arguments that are not a URL string and an array of strings", function() { + var fn = require("ns:module").remoteUrlMatchesAllowlist; + if (typeof fn !== "function") { + pending("ns:module.remoteUrlMatchesAllowlist not exposed (release build)"); + return; + } + [[], ["https://h/x.js"], ["https://h/x.js", "https://h/"], [1, []], + ["https://h/x.js", [1]]].forEach(function (args) { + expect(function () { fn.apply(null, args); }) + .toThrowError(TypeError, + "remoteUrlMatchesAllowlist expects a URL string and an array of strings"); + }); + }); + }); }); diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index 4bc76fa93..fb1413804 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -10,7 +10,9 @@ import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Loopback HTTP/1.1 fixture server for the in-app Jasmine suite. Mirrors the @@ -25,6 +27,10 @@ public final class ModuleTestServer { private static Thread acceptThread; private static int boundPort = -1; private static final List workers = new ArrayList(); + // Requests received per target (path plus query), readable back through + // /esm/request-stats.json so a spec can prove how often a module was + // fetched, or that it never was. + private static final Map requestCounts = new HashMap(); private ModuleTestServer() { } @@ -146,6 +152,28 @@ private static void handle(Socket socket) throws IOException { } private static void route(Socket socket, String path, String query) throws IOException { + if (path.startsWith("/esm/") && !"/esm/request-stats.json".equals(path)) { + String target = query.isEmpty() ? path : path + "?" + query; + synchronized (requestCounts) { + Integer count = requestCounts.get(target); + requestCounts.put(target, count == null ? 1 : count + 1); + } + } + + if ("/esm/request-stats.json".equals(path)) { + // `target` is the percent-encoded request target to count. + String raw = param(query, "target="); + String wanted = raw == null ? "" : URLDecoder.decode(raw, "UTF-8"); + int count; + synchronized (requestCounts) { + Integer c = requestCounts.get(wanted); + count = c == null ? 0 : c; + } + String body = "{\"target\":\"" + jsStringLiteral(wanted) + "\",\"count\":" + count + "}"; + respond(socket, "200 OK", "application/json; charset=utf-8", body.getBytes(UTF8)); + return; + } + if ("/esm/query.mjs".equals(path) || "/ns/m/query.mjs".equals(path)) { String body = "export const path = \"" + jsStringLiteral(path) + "\";\n" + "export const query = \"" + jsStringLiteral(query) + "\";\n" @@ -327,7 +355,8 @@ private static String jsStringLiteral(String s) { return s.replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") - .replace("\r", "\\r"); + .replace("\r", "\\r") + .replace("\u0000", "\\u0000"); } private static void respond(Socket socket, String status, String contentType, byte[] body) diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index d5937c294..a17a37bef 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -243,6 +243,7 @@ add_library( src/main/cpp/ModuleBinding.cpp src/main/cpp/ModuleInternal.cpp src/main/cpp/ModuleInternalCallbacks.cpp + src/main/cpp/ModuleUrl.cpp src/main/cpp/NativeScriptAssert.cpp src/main/cpp/NativeScriptException.cpp src/main/cpp/NativeScriptPlatform.cpp diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 11d31a1f0..e73f16b21 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -19,6 +19,7 @@ #include #include #include "HttpLoader.h" +#include "ModuleUrl.h" #include "MethodCache.h" #include "ModuleInternal.h" #include "SimpleProfiler.h" @@ -1767,7 +1768,8 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo + +#include +#include +#include +#include + +#include "v8.h" + +namespace tns { + +// The exact UTF-8 bytes of a UTF-16 string, sized by length so an embedded +// U+0000 is kept; nullopt for a string with a lone surrogate, which has no +// UTF-8 spelling. JNI's GetStringUTFChars and V8's Utf8Value are not exact: +// the first writes modified UTF-8 (U+0000 as C0 80, supplementary characters +// as surrogate pairs), the second replaces a lone surrogate with U+FFFD. +inline std::optional Utf16ToExactUtf8(const uint16_t* units, size_t length) { + std::string out; + out.reserve(length); + for (size_t i = 0; i < length; i++) { + uint32_t cp = units[i]; + if (cp >= 0xD800 && cp <= 0xDBFF) { + if (i + 1 >= length || units[i + 1] < 0xDC00 || units[i + 1] > 0xDFFF) { + return std::nullopt; + } + cp = 0x10000 + ((cp - 0xD800) << 10) + (units[i + 1] - 0xDC00); + i++; + } else if (cp >= 0xDC00 && cp <= 0xDFFF) { + return std::nullopt; + } + if (cp < 0x80) { + out.push_back(static_cast(cp)); + } else if (cp < 0x800) { + out.push_back(static_cast(0xC0 | (cp >> 6))); + out.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp < 0x10000) { + out.push_back(static_cast(0xE0 | (cp >> 12))); + out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (cp & 0x3F))); + } else { + out.push_back(static_cast(0xF0 | (cp >> 18))); + out.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (cp & 0x3F))); + } + } + return out; +} + +inline std::optional ToExactUtf8(v8::Isolate* isolate, v8::Local value) { + std::vector units(value->Length()); + value->WriteV2(isolate, 0, value->Length(), units.data()); + return Utf16ToExactUtf8(units.data(), units.size()); +} + +// nullopt for a null jstring too. +inline std::optional ToExactUtf8(JNIEnv* env, jstring value) { + if (value == nullptr) { + return std::nullopt; + } + const jsize length = env->GetStringLength(value); + std::vector units(length); + env->GetStringRegion(value, 0, length, units.data()); + return Utf16ToExactUtf8(reinterpret_cast(units.data()), units.size()); +} + +} // namespace tns + +#endif // EXACT_UTF8_H_ diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index 9d9424ef6..c97f57417 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -15,11 +15,13 @@ #include #include "ArgConverter.h" +#include "ExactUtf8.h" #include "JEnv.h" // The transport carries canonical keys rather than computing them, but // CanonicalizeHttpUrlKey itself reads the calling isolate's canonicalization // vocabulary — the one loader dependency left here. #include "ModuleInternalCallbacks.h" +#include "ModuleUrl.h" #include "NativeScriptException.h" #include "Runtime.h" #include "TraceLog.h" @@ -37,7 +39,7 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { static std::once_flag s_securityConfigInitFlag; static bool s_allowRemoteModules = false; -static std::vector s_remoteModuleAllowlist; +static RemoteModuleAllowlist s_remoteModuleAllowlist; static bool s_isDebuggable = false; static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::string& entry) { @@ -50,8 +52,43 @@ static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::st return next == '/' || next == '?' || next == '#'; } +static std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { + const std::string url = NormalizeHttpModuleUrl(entry); + return url.empty() ? entry : url; +} + +RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( + const std::optional>>& items) { + RemoteModuleAllowlist allowlist; + if (!items.has_value() || items->empty()) { + return allowlist; + } + allowlist.inForce = true; + for (const std::optional& item : *items) { + if (item.has_value() && !item->empty()) { + allowlist.entries.push_back(NormalizeRemoteModuleAllowlistEntry(*item)); + } + } + return allowlist; +} + +bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist) { + if (!allowlist.inForce) { + return true; + } + for (const std::string& entry : allowlist.entries) { + if (RemoteUrlMatchesAllowlistEntry(url, entry)) { + return true; + } + } + return false; +} + static void InitializeSecurityConfig() { std::call_once(s_securityConfigInitFlag, []() { + // Remote modules are enabled only after the allowlist was read in + // full: a failure part way keeps them disabled rather than enabling + // them with a list cut short. try { JEnv env; jclass runtimeClass = env.FindClass("com/tns/Runtime"); @@ -70,35 +107,40 @@ static void InitializeSecurityConfig() { return; } + bool allowRemoteModules = false; jmethodID allowRemoteMid = env.GetStaticMethodID(runtimeClass, "isRemoteModulesAllowed", "()Z"); if (allowRemoteMid != nullptr) { - s_allowRemoteModules = + allowRemoteModules = env.CallStaticBooleanMethod(runtimeClass, allowRemoteMid) == JNI_TRUE; } + // Null when the list is not in force; a null element stands for an + // item that is not a string. + std::optional>> items; jmethodID getAllowlistMid = env.GetStaticMethodID( runtimeClass, "getRemoteModuleAllowlist", "()[Ljava/lang/String;"); - if (getAllowlistMid != nullptr) { - jobjectArray allowlistArray = static_cast( - env.CallStaticObjectMethod(runtimeClass, getAllowlistMid)); - if (allowlistArray != nullptr) { - jsize len = env.GetArrayLength(allowlistArray); - for (jsize i = 0; i < len; i++) { - jstring jstr = - static_cast(env.GetObjectArrayElement(allowlistArray, i)); - if (jstr != nullptr) { - const char* str = env.GetStringUTFChars(jstr, nullptr); - if (str != nullptr) { - s_remoteModuleAllowlist.emplace_back(str); - env.ReleaseStringUTFChars(jstr, str); - } - env.DeleteLocalRef(jstr); - } + if (getAllowlistMid == nullptr) { + return; + } + jobjectArray allowlistArray = static_cast( + env.CallStaticObjectMethod(runtimeClass, getAllowlistMid)); + if (allowlistArray != nullptr) { + items.emplace(); + jsize len = env.GetArrayLength(allowlistArray); + for (jsize i = 0; i < len; i++) { + jstring jstr = + static_cast(env.GetObjectArrayElement(allowlistArray, i)); + items->push_back(ToExactUtf8(env, jstr)); + if (jstr != nullptr) { + env.DeleteLocalRef(jstr); } - env.DeleteLocalRef(allowlistArray); } + env.DeleteLocalRef(allowlistArray); } + + s_remoteModuleAllowlist = RemoteModuleAllowlistFromConfig(items); + s_allowRemoteModules = allowRemoteModules; } catch (...) { // Keep defaults (remote modules disabled) } @@ -128,51 +170,18 @@ bool IsRemoteUrlAllowed(const std::string& url) { return false; } - if (s_remoteModuleAllowlist.empty()) { - return true; - } - - for (const std::string& entry : s_remoteModuleAllowlist) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - - return false; + return RemoteUrlAllowedByAllowlist(url, s_remoteModuleAllowlist); } // ───────────────────────────────────────────────────────────── // Canonical module keys -std::string NormalizeHttpModuleUrl(const std::string& path) { - if (path.empty()) { - return path; - } - - std::string normalized = path; - if (StartsWith(normalized, "file://http://") || StartsWith(normalized, "file://https://")) { - normalized = normalized.substr(strlen("file://")); - } - - // A path normalizer that collapses `//` into `/` (Java's, or a URL that - // travelled through one) leaves the scheme separator one slash short. - if (normalized.rfind("http:/", 0) == 0 && normalized.rfind("http://", 0) != 0) { - normalized.insert(5, "/"); - } else if (normalized.rfind("https:/", 0) == 0 && normalized.rfind("https://", 0) != 0) { - normalized.insert(6, "/"); - } - - return normalized; +std::string CanonicalizeHttpUrlKey(const std::string& url) { + const std::string normalizedUrl = NormalizeHttpModuleUrl(url); + return normalizedUrl.empty() ? url : CanonicalizeNormalizedHttpUrlKey(normalizedUrl); } -std::string CanonicalizeHttpUrlKey(const std::string& url) { - std::string normalizedUrl = url; - if (StartsWith(normalizedUrl, "file://http://") || StartsWith(normalizedUrl, "file://https://")) { - normalizedUrl = normalizedUrl.substr(strlen("file://")); - } - if (!(StartsWith(normalizedUrl, "http://") || StartsWith(normalizedUrl, "https://"))) { - return normalizedUrl; - } +std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { size_t hashPos = normalizedUrl.find('#'); std::string noHash = (hashPos == std::string::npos) ? normalizedUrl : normalizedUrl.substr(0, hashPos); diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index f4de96615..4b6c0f542 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -45,8 +46,8 @@ struct CanonicalizationConfig { }; // Normalize an HTTP(S) URL into a stable module registry/cache key. -// - Anything that is not HTTP(S) comes back unchanged, after unwrapping a -// `file://` prefix the resolver may have put in front of an http(s) URL. +// - Anything that is not HTTP(S) comes back unchanged; an http(s) URL is +// first spelled by NormalizeHttpModuleUrl. // - The fragment is always stripped. // - The query survives unless the isolate's canonicalization vocabulary says // otherwise: a path matching `preserveQueryFor` keeps its query verbatim; @@ -56,12 +57,8 @@ struct CanonicalizationConfig { // module under exactly one URL and never varies it for freshness. std::string CanonicalizeHttpUrlKey(const std::string& url); -// Undoes what a path normalizer did to an http(s) URL — unwraps a `file://` -// prefix the resolver may have put in front, and re-doubles a scheme -// separator collapsed to a single slash (`http:/host/...`). Every consumer -// that classifies or keys a module URL must run this first, or the same -// module string routes/keys differently at different sites. -std::string NormalizeHttpModuleUrl(const std::string& path); +// CanonicalizeHttpUrlKey for a URL already spelled by NormalizeHttpModuleUrl. +std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl); // What a module response turned out to be. Decided once, by the shared // classifier, for whichever transport produced the response. @@ -148,10 +145,33 @@ void CleanupHttpLoaderGlobals(); bool IsRemoteModulesAllowed(); // Whether `url` may be fetched as a remote ES module. Debug apps always -// allow. Production requires allowRemoteModules, then an allowlist match -// (or all URLs if the allowlist is empty). +// allow. Production requires allowRemoteModules, then RemoteUrlAllowedByAllowlist. bool IsRemoteUrlAllowed(const std::string& url); +// The allowlist IsRemoteUrlAllowed applies once remote modules are enabled. +struct RemoteModuleAllowlist { + // False only when `security.remoteModuleAllowlist` is absent, not an + // array, or an empty array: then every URL is allowed. + bool inForce = false; + // The usable items, each spelled the way the loader spells the URLs it + // fetches (NormalizeHttpModuleUrl) so path-scoped entries compare against + // resolved paths, or kept verbatim when it is not an http(s) URL. An item + // that is not a string, is empty or has no exact UTF-8 form is not here: + // it matches nothing but still keeps the list in force. + std::vector entries; +}; + +// The allowlist for the `security.remoteModuleAllowlist` config value: nullopt +// when it is absent or not an array, otherwise its items in order, each +// nullopt when it is not a string or has no exact UTF-8 form. +RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( + const std::optional>>& items); + +// Whether `url` (as fetched) passes `allowlist`: always when it is not in +// force, otherwise when one entry matches it by prefix with the match ending +// at a URL-component boundary. +bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist); + // Mirrors com.tns.Runtime.isDebuggable(), cached once via the security // config init. Fail-safe false until initialized. bool IsDebuggable(); diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index 4f966e2ac..bb17511a7 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -9,6 +9,7 @@ #include "BuiltinLoader.h" #include "File.h" #include "HttpLoader.h" +#include "ModuleUrl.h" #include "JniLocalRef.h" #include "ArgConverter.h" #include "NativeScriptAssert.h" @@ -39,8 +40,7 @@ using namespace std; using namespace tns; bool ModuleInternal::IsHttpModulePath(const std::string& path) { - const std::string normalized = NormalizeHttpModuleUrl(path); - return normalized.rfind("http://", 0) == 0 || normalized.rfind("https://", 0) == 0; + return !NormalizeHttpModuleUrl(path).empty(); } // What a rejected evaluation promise says about itself. @@ -513,7 +513,7 @@ void ModuleInternal::RequireCallbackImpl(const v8::FunctionCallbackInfo ModuleInternal::LoadScript(Isolate* isolate, const string& path, c // auto cacheData = TryLoadScriptCache(path, ScriptCacheKind::Classic); - auto fullRequiredModulePathWithSchema = ArgConverter::ConvertToV8String(isolate, "file://" + path); + auto fullRequiredModulePathWithSchema = ArgConverter::ConvertToV8String(isolate, ReportedModuleUrl(path)); ScriptOrigin origin(fullRequiredModulePathWithSchema); ScriptCompiler::Source source(scriptText, origin, cacheData); ScriptCompiler::CompileOptions option = ScriptCompiler::kNoCompileOptions; @@ -1063,7 +1063,7 @@ MaybeLocal ModuleInternal::CompileFileEsModule(Isolate* isolate, const s throw NativeScriptException("Cannot find module " + path); } - string url = "file://" + path; + string url = ReportedModuleUrl(path); // An exists-but-unreadable file, or one deleted between the stat above and // the open, reads as "" — which compiles into a perfectly valid empty // module unless the failure is told apart from an empty file here. @@ -1443,12 +1443,14 @@ EntryEvaluationState ModuleInternal::PollEntryEvaluation(Isolate* isolate, const Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& path, const ModuleEvaluationOptions& options) { auto context = isolate->GetCurrentContext(); - const bool isHttpModule = IsHttpModulePath(path); + const std::string httpUrl = NormalizeHttpModuleUrl(path); + const bool isHttpModule = !httpUrl.empty(); // The key the resolver would derive for this same module as someone's // dependency. Keying the root by anything else mints a second identity for // one file, so a cycle back to the root would not terminate on its entry. - const std::string canonicalPath = CanonicalizeRegistryKey(path); - const std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath; + const std::string canonicalPath = isHttpModule ? CanonicalizeNormalizedHttpUrlKey(httpUrl) + : CanonicalizeRegistryKey(path); + const std::string requestPath = isHttpModule ? httpUrl : canonicalPath; auto logPhase = [&canonicalPath](const char* phase, const char* status, const char* classification = "", const char* extra = "") { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 22767662b..bb540e50d 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -12,15 +12,18 @@ #include #include #include +#include #include #include #include #include "ArgConverter.h" #include "EventLoop.h" +#include "ExactUtf8.h" #include "HttpLoader.h" #include "JEnv.h" #include "ModuleInternal.h" +#include "ModuleUrl.h" #include "NativeScriptAssert.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" @@ -28,7 +31,6 @@ #include "Runtime.h" #include "RuntimeState.h" #include "TraceLog.h" -#include "ada/ada.h" #include "robin_hood.h" using namespace v8; @@ -45,17 +47,6 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { return s.size() >= n && s.compare(0, n, prefix) == 0; } -// Whether `key` is spelled the way the loader keys an HTTP module: a lowercase -// `http://` or `https://` prefix, file modules being keyed by absolute paths. -// Deliberately not a URL parse: it gates the rule that an HTTP importer never -// reaches the filesystem implicitly, so a key the URL parser would reject (an -// IPv6 zone id, say) must still count as HTTP. -static bool IsHttpRegistryKey(const std::string& key) { - if (key.compare(0, 4, "http") != 0) return false; - const size_t schemeEnd = key.size() > 4 && key[4] == 's' ? 5 : 4; - return key.compare(schemeEnd, 3, "://") == 0; -} - static inline bool EndsWith(const std::string& value, const std::string& suffix) { if (suffix.size() > value.size()) return false; return std::equal(suffix.rbegin(), suffix.rend(), value.rbegin()); @@ -590,13 +581,12 @@ std::string CanonicalizeRegistryKey(const std::string& key) { const char* classification = "path"; bool traceEvenWithoutChange = false; - // Repair-first, exactly like IsHttpModulePath: a collapsed scheme - // separator (`http:/host/...`) must key as the URL it routes as, or the - // loader registers a module under a key the probes and evictions of the - // raw string can never find. - const std::string repaired = NormalizeHttpModuleUrl(key); - if (IsHttpRegistryKey(repaired)) { - registryKey = CanonicalizeHttpUrlKey(repaired); + // Before any other scheme test: an http(s) URL in a spelling other than the + // key's (`HTTP://`, `http:/host`) must not fall through as a custom scheme + // and give the module a second identity. + const std::string httpUrl = NormalizeHttpModuleUrl(key); + if (!httpUrl.empty()) { + registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { registryKey = NormalizePath(FileURLToPath(key)); @@ -635,7 +625,7 @@ v8::MaybeLocal LoadHttpModuleForUrl(v8::Isolate* isolate, return v8::MaybeLocal(); } auto& registry = moduleState->registry; - const std::string registryKey = CanonicalizeHttpUrlKey(requestedUrl); + const std::string registryKey = CanonicalizeNormalizedHttpUrlKey(requestedUrl); TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s", requestedUrl.c_str(), registryKey.c_str()); @@ -727,12 +717,14 @@ static bool ParseImportMapEntries(v8::Isolate* isolate, v8::Local c *error = sectionLabel + ": every key must be a string"; return false; } - v8::String::Utf8Value keyUtf8(isolate, keyVal); - if (!*keyUtf8) { + // V8's JSON parser accepts lone surrogates, which have no UTF-8 form, so + // a key or target holding one is reported as not a string. + const std::optional keyUtf8 = ToExactUtf8(isolate, keyVal.As()); + if (!keyUtf8.has_value()) { *error = sectionLabel + ": every key must be a string"; return false; } - const std::string specifier(*keyUtf8); + const std::string& specifier = *keyUtf8; if (specifier.empty()) { *error = sectionLabel + ": a specifier key must not be empty"; return false; @@ -743,16 +735,22 @@ static bool ParseImportMapEntries(v8::Isolate* isolate, v8::Local c *error = sectionLabel + ": the target for '" + specifier + "' must be a string"; return false; } - v8::String::Utf8Value valueUtf8(isolate, value); - if (!*valueUtf8) { + const std::optional valueUtf8 = ToExactUtf8(isolate, value.As()); + if (!valueUtf8.has_value()) { *error = sectionLabel + ": the target for '" + specifier + "' must be a string"; return false; } - const std::string target(*valueUtf8); + const std::string& target = *valueUtf8; if (target.empty()) { *error = sectionLabel + ": the target for '" + specifier + "' must not be empty"; return false; } + // A target resolves as a filesystem path or is fetched as a URL, and both + // go through C-string APIs that would end it at U+0000. + if (target.find('\0') != std::string::npos) { + *error = sectionLabel + ": the target for '" + specifier + "' must not contain U+0000"; + return false; + } // A trailing-slash key maps a whole subtree, so its target must name one // too — otherwise the remainder would be pasted onto a file path. @@ -767,6 +765,30 @@ static bool ParseImportMapEntries(v8::Isolate* isolate, v8::Local c return true; } +// A scope key matches referrer registry keys by plain prefix, and an http(s) +// referrer key is spelled by NormalizeHttpModuleUrl, so an http(s) scope key +// is spelled the same way. A key written with no path at all stays path-less: +// the parser gives it the path "/", which would narrow the prefix. Any other +// trailing '/' is the parser's and stays, so dot segments can't widen a scope +// past a path-segment boundary. +static std::string ImportMapScopePrefix(const std::string& scopeKey) { + std::string prefix = NormalizeHttpModuleUrl(scopeKey); + if (prefix.empty()) { + return scopeKey; + } + const size_t colon = scopeKey.find(':'); + const size_t authority = colon == std::string::npos + ? std::string::npos + : scopeKey.find_first_not_of("/\\", colon + 1); + const bool writtenWithoutPath = + authority != std::string::npos && + scopeKey.find_first_of("/\\?#", authority) == std::string::npos; + if (writtenWithoutPath && prefix.back() == '/') { + prefix.pop_back(); + } + return prefix; +} + // Parse without touching the live map. On any failure `error` explains what is // wrong and `out` is meaningless — the caller keeps whatever it already had. // V8's JSON parser stands in for iOS's NSJSONSerialization: escapes, nesting @@ -807,8 +829,7 @@ static bool ParseImportMap(v8::Isolate* isolate, const std::string& json, v8::Local sectionVal; std::string name; if (sections->Get(context, i).ToLocal(§ionVal) && sectionVal->IsString()) { - v8::String::Utf8Value utf8(isolate, sectionVal); - if (*utf8) name = *utf8; + name = ToExactUtf8(isolate, sectionVal.As()).value_or(std::string()); } if (name == "imports") { hasImports = true; @@ -855,8 +876,13 @@ static bool ParseImportMap(v8::Isolate* isolate, const std::string& json, *error = "scopes: every scope key must be a string"; return false; } - v8::String::Utf8Value scopeUtf8(isolate, scopeKeyVal); - const std::string scopePrefix(*scopeUtf8 ? *scopeUtf8 : ""); + const std::optional scopeUtf8 = + ToExactUtf8(isolate, scopeKeyVal.As()); + if (!scopeUtf8.has_value()) { + *error = "scopes: every scope key must be a string"; + return false; + } + const std::string& scopePrefix = *scopeUtf8; if (scopePrefix.empty()) { *error = "scopes: a scope key must not be empty"; return false; @@ -872,7 +898,7 @@ static bool ParseImportMap(v8::Isolate* isolate, const std::string& json, "scope '" + scopePrefix + "'", &entries, error)) { return false; } - out->scopes.emplace_back(scopePrefix, std::move(entries)); + out->scopes.emplace_back(ImportMapScopePrefix(scopePrefix), std::move(entries)); } } @@ -1066,80 +1092,6 @@ static std::string UnresolvedModuleMessage(const ModuleResolution& resolution) { resolution.attempted + ")"; } -static bool HasHttpScheme(const ada::url_aggregator& url) { - return url.type == ada::scheme::type::HTTP || - url.type == ada::scheme::type::HTTPS; -} - -// The authority (userinfo, host, port) of an absolute or scheme-relative URL -// exactly as written, or empty when `url` does not spell one plainly. -static std::string WrittenAuthority(const std::string& url) { - size_t start = 0; - if (StartsWith(url, "//")) { - start = 2; - } else { - const size_t colon = url.find(':'); - if (colon == std::string::npos || url.compare(colon, 3, "://") != 0) { - return std::string(); - } - start = colon + 3; - } - const size_t end = url.find_first_of("/?#", start); - std::string authority = - url.substr(start, end == std::string::npos ? end : end - start); - for (const char c : authority) { - if (static_cast(c) <= 0x20 || c == '\\') { - return std::string(); - } - } - return authority; -} - -struct ModuleUrl { - bool parsed = false; - bool http = false; // the scheme is http or https - std::string href; -}; - -// `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): -// as an absolute URL when `base` is empty, otherwise as a path- or -// scheme-relative reference against `base`. -// -// An http(s) result keeps its authority as written by whichever string -// supplied it: tooling compares module URLs against the origin string it was -// configured with, so that spelling is part of a module's identity until every -// loader entry point canonicalizes. The parser's own href is used whenever the -// written authority would not name the same URL. -static ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { - ModuleUrl result; - ada::result url; - if (base.empty()) { - url = ada::parse(input, nullptr); - } else { - auto baseUrl = ada::parse(base, nullptr); - if (!baseUrl) return result; - url = ada::parse(input, &baseUrl.value()); - } - if (!url) return result; - result.parsed = true; - result.http = HasHttpScheme(*url); - result.href = std::string(url->get_href()); - if (!result.http) return result; - - const std::string authority = - WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); - if (authority.empty()) return result; - const std::string written = std::string(url->get_protocol()) + "//" + authority + - std::string(url->get_pathname()) + - std::string(url->get_search()) + - std::string(url->get_hash()); - auto reparsed = ada::parse(written, nullptr); - if (reparsed && reparsed->get_href() == url->get_href()) { - result.href = written; - } - return result; -} - struct UrlSpecifier { enum class Kind { kHttpUrl, // an http(s) URL @@ -1176,24 +1128,6 @@ static std::string BlockedFromHttpMessage(const std::string& rawSpec, referrerKey + ": " + reason; } -// Rebuild an HTTP URL a path join swallowed ('/app/http:/host/x' → -// 'http://host/x'), or empty when the path embeds none. -static std::string HttpUrlEmbeddedInPath(const std::string& p) { - size_t pos1 = p.find("/http:/"); - size_t pos2 = p.find("/https:/"); - size_t pos = std::min(pos1 == std::string::npos ? SIZE_MAX : pos1, - pos2 == std::string::npos ? SIZE_MAX : pos2); - if (pos == SIZE_MAX) return ""; - std::string tail = p.substr(pos + 1); - if (StartsWith(tail, "http:/") && !StartsWith(tail, "http://")) { - tail.insert(5, "/"); - } else if (StartsWith(tail, "https:/") && !StartsWith(tail, "https://")) { - tail.insert(6, "/"); - } - if (!IsHttpRegistryKey(tail)) return ""; - return tail; -} - // `referrerKey` is the registry key of the importing module — empty when the // importer is unknown (a dynamic import with no compiled referrer). static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, @@ -1218,13 +1152,6 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } std::string spec = rawSpec; - // Repair 'http:/host' (single slash) left by upstream path joins, so the URL - // takes the HTTP path instead of becoming '/app/http:/host'. - if (spec.rfind("http:/", 0) == 0 && spec.rfind("http://", 0) != 0) { - spec.insert(5, "/"); - } else if (spec.rfind("https:/", 0) == 0 && spec.rfind("https://", 0) != 0) { - spec.insert(6, "/"); - } TNS_DEBUG(Esm, "[resolver][spec] %s", spec.c_str()); @@ -1298,9 +1225,10 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } } - if (IsHttpRegistryKey(spec)) { + const std::string httpUrl = NormalizeHttpModuleUrl(spec); + if (!httpUrl.empty()) { result.kind = ModuleResolution::Kind::kHttp; - result.url = spec; + result.url = httpUrl; return result; } @@ -1420,15 +1348,6 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, for (const std::string& baseCandidate : candidateBases) { absPath = baseCandidate; - std::string embedded = HttpUrlEmbeddedInPath(absPath); - if (!embedded.empty()) { - TNS_DEBUG(Esm, "[resolver][http-embedded] %s -> %s", absPath.c_str(), - embedded.c_str()); - result.kind = ModuleResolution::Kind::kHttp; - result.url = embedded; - return result; - } - if (IsFile(absPath)) { found = true; break; @@ -1576,6 +1495,35 @@ static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate) { static void AsyncGraphEnqueue(const std::shared_ptr& load, const ModuleResolution& resolution); +// A specifier's UTF-8, sized by length, or nullopt when it contains U+0000: +// the path and URL APIs behind resolution read C strings and would load +// whatever precedes it. +static std::optional ModuleSpecifierUtf8(v8::Isolate* isolate, + v8::Local specifier) { + v8::String::Utf8Value utf8(isolate, specifier); + std::string spec = *utf8 ? std::string(*utf8, utf8.length()) : std::string(); + if (spec.find('\0') != std::string::npos) { + return std::nullopt; + } + return spec; +} + +static std::string NulSpecifierMessage(v8::Isolate* isolate, v8::Local specifier) { + v8::String::Utf8Value utf8(isolate, specifier); + std::string shown; + if (*utf8) { + for (int i = 0; i < utf8.length(); i++) { + if ((*utf8)[i] == '\0') { + shown += "\\u0000"; + } else { + shown += (*utf8)[i]; + } + } + } + return "Cannot resolve module specifier \"" + shown + + "\": a module specifier must not contain U+0000"; +} + // Walk `mod`'s static module requests and enqueue every edge the walk can // resolve. JS thread only; `moduleKey` is the registry key the module was // registered under, which is also the referrer for relative resolution. @@ -1589,9 +1537,10 @@ static void AsyncGraphWalkModuleRequests( v8::Local request = requests->Get(i).As(); if (request.IsEmpty()) continue; - v8::Local specV8 = request->GetSpecifier(); - v8::String::Utf8Value specUtf8(isolate, specV8); - if (!*specUtf8) continue; + // A specifier holding U+0000 is left for the resolver to refuse at link. + const std::optional spec = + ModuleSpecifierUtf8(isolate, request->GetSpecifier()); + if (!spec.has_value()) continue; // Builtins are served by the resolver from the builtin registry, and an // unresolved specifier (typically a bare name with no import-map entry, // or one an HTTP importer may not use) stays on the resolver's lazy path — @@ -1599,8 +1548,7 @@ static void AsyncGraphWalkModuleRequests( // message. An unmapped bare specifier's subtree is therefore not // discovered here; any HTTP edge inside it is pathological and lands on // the synchronous anomaly guard. - const ModuleResolution resolution = - ResolveSpecifierToPath(*specUtf8, moduleKey); + const ModuleResolution resolution = ResolveSpecifierToPath(*spec, moduleKey); if (resolution.kind != ModuleResolution::Kind::kHttp && resolution.kind != ModuleResolution::Kind::kFile) { continue; @@ -1652,7 +1600,7 @@ static void AsyncGraphOnFetchCompleted( load->pendingFetches--; - const std::string key = CanonicalizeRegistryKey(url); + const std::string key = CanonicalizeNormalizedHttpUrlKey(url); const bool isRoot = (key == load->rootKey); if (!load->failed) { @@ -1768,10 +1716,11 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, const ModuleResolution& resolution) { const bool isHttp = resolution.kind == ModuleResolution::Kind::kHttp; const std::string& target = isHttp ? resolution.url : resolution.path; - // One keying function for both schemes: it dispatches to the HTTP canonical - // key for URLs and to the normalized path otherwise, so the walk registers - // every module under the exact key the resolver will look up. - const std::string key = CanonicalizeRegistryKey(target); + // The keys CanonicalizeRegistryKey gives these targets, so the walk registers + // every module under the exact key the resolver will look up; a resolved + // URL is already spelled, so only its vocabulary is applied. + const std::string key = + isHttp ? CanonicalizeNormalizedHttpUrlKey(target) : CanonicalizeRegistryKey(target); if (!load->visited.insert(key).second) return; v8::Isolate* isolate = load->isolate; @@ -1839,9 +1788,10 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, static ModuleResolution ResolutionForRoot(const std::string& root) { ModuleResolution resolution; resolution.specifier = root; - if (IsHttpRegistryKey(root)) { + const std::string httpUrl = NormalizeHttpModuleUrl(root); + if (!httpUrl.empty()) { resolution.kind = ModuleResolution::Kind::kHttp; - resolution.url = root; + resolution.url = httpUrl; } else if (IsFile(root)) { resolution.kind = ModuleResolution::Kind::kFile; resolution.path = root; @@ -1857,10 +1807,13 @@ void StartModuleGraphLoad( std::function context)> onComplete) { + const ModuleResolution rootResolution = ResolutionForRoot(root); auto load = std::make_shared(); load->isolate = isolate; load->context.Reset(isolate, context); - load->rootKey = CanonicalizeRegistryKey(root); + load->rootKey = rootResolution.kind == ModuleResolution::Kind::kHttp + ? CanonicalizeNormalizedHttpUrlKey(rootResolution.url) + : CanonicalizeRegistryKey(root); load->startUs = MonotonicUs(); load->onComplete = std::move(onComplete); @@ -1871,7 +1824,6 @@ void StartModuleGraphLoad( TNS_DEBUG(Esm, "[graph][start] root=%s key=%s", root.c_str(), load->rootKey.c_str()); - const ModuleResolution rootResolution = ResolutionForRoot(root); if (rootResolution.kind != ModuleResolution::Kind::kUnresolved) { AsyncGraphEnqueue(load, rootResolution); } @@ -2327,7 +2279,7 @@ static v8::MaybeLocal CompileJsonAsEsModule( } const std::string jsonText = runtime->ReadFileText(absPath); return CompileJsonTextAsEsModule(isolate, context, jsonText, registryAbsPath, - "file://" + absPath); + ReportedModuleUrl(absPath)); } // ───────────────────────────────────────────────────────────── @@ -2351,8 +2303,13 @@ v8::MaybeLocal ResolveModuleCallback( return v8::MaybeLocal(); } - v8::String::Utf8Value specUtf8(isolate, specifier); - const std::string rawSpec = *specUtf8 ? *specUtf8 : ""; + const std::optional spec = ModuleSpecifierUtf8(isolate, specifier); + if (!spec.has_value()) { + isolate->ThrowException(v8::Exception::Error( + ArgConverter::ConvertToV8String(isolate, NulSpecifierMessage(isolate, specifier)))); + return v8::MaybeLocal(); + } + const std::string& rawSpec = *spec; if (rawSpec.empty()) return v8::MaybeLocal(); const std::string referrerPath = @@ -2616,9 +2573,21 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( auto& modulesInFlight = moduleState->modulesInFlight; auto& httpDynamicWaiters = moduleState->httpDynamicWaiters; - v8::String::Utf8Value specUtf8(isolate, specifier); - const char* cSpec = (*specUtf8) ? *specUtf8 : ""; - TNS_DEBUG(Esm, "[dyn-import] -> %s", cSpec); + const std::optional specUtf8 = ModuleSpecifierUtf8(isolate, specifier); + if (!specUtf8.has_value()) { + v8::EscapableHandleScope nulScope(isolate); + v8::Local nulResolver; + if (!v8::Promise::Resolver::New(context).ToLocal(&nulResolver)) { + return v8::MaybeLocal(); + } + nulResolver + ->Reject(context, v8::Exception::Error(ArgConverter::ConvertToV8String( + isolate, NulSpecifierMessage(isolate, specifier)))) + .FromMaybe(false); + return nulScope.Escape(nulResolver->GetPromise()); + } + std::string rawSpec = *specUtf8; + TNS_DEBUG(Esm, "[dyn-import] -> %s", rawSpec.c_str()); if (LogCategoryEnabled(LogCategory::Esm)) { v8::Local resName = resource_name; if (!resName.IsEmpty() && resName->IsString()) { @@ -2629,8 +2598,6 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( } } - std::string rawSpec = cSpec ? std::string(cSpec) : std::string(); - // Builtin modules never touch the loader below; the namespace comes straight // from the realm's synthetic module. if (NsBuiltinModules::IsBuiltinScheme(rawSpec)) { @@ -2699,9 +2666,8 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); } - // A relative or root-absolute specifier from a served referrer resolves to - // a URL the specifier itself never spells out. Routing on that URL keeps - // such an import() on the async fetch path with its absolute-URL siblings. + // Whatever resolves to an http(s) URL continues as the URL the resolver + // spelled, through the HTTP path. if (dynamicResolution.kind == ModuleResolution::Kind::kHttp && !dynamicResolution.url.empty() && dynamicResolution.url != normalizedSpec) { @@ -3094,10 +3060,10 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( // ── HTTP(S) fast path ── // Security: HttpFetchModule gates remote module access centrally. - if (!normalizedSpec.empty() && IsHttpRegistryKey(normalizedSpec)) { + if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); - std::string key = CanonicalizeHttpUrlKey(normalizedSpec); + std::string key = CanonicalizeNormalizedHttpUrlKey(normalizedSpec); // Volatile-pattern eviction: if the URL matches any configured volatile // pattern, evict the cached module so we always re-fetch. Policy is @@ -3487,34 +3453,7 @@ void InitializeImportMetaObject(v8::Local context, const std::string modulePath = FindKeyForModule(*moduleState, isolate, module); - // A registry key either carries a URL scheme — http(s):, blob:, node:, and - // whatever else a synthetic module is keyed under — or it is a filesystem - // path. A scheme'd key IS the module's identity and passes through untouched; - // only a path becomes a file:// URL. - auto hasUrlScheme = [](const std::string& s) -> bool { - if (s.empty()) return false; - size_t colonPos = s.find(':'); - if (colonPos == 0 || colonPos == std::string::npos) return false; - size_t slashPos = s.find('/'); - if (slashPos != std::string::npos && slashPos < colonPos) return false; - for (size_t i = 0; i < colonPos; i++) { - char c = s[i]; - const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || c == '+' || c == '-' || - c == '.'; - if (!ok) return false; - } - return true; - }; - - std::string moduleUrl; - if (modulePath.empty()) { - moduleUrl = "file:///app/"; - } else if (hasUrlScheme(modulePath)) { - moduleUrl = modulePath; - } else { - moduleUrl = "file://" + modulePath; - } + const std::string moduleUrl = ReportedModuleUrl(modulePath); // `dirname` is a filesystem notion; a URL-backed module has no directory, so // it gets the URL with its last path segment stripped — stable and useful in @@ -3523,7 +3462,7 @@ void InitializeImportMetaObject(v8::Local context, std::string moduleDirname; if (modulePath.empty()) { moduleDirname = "/app"; - } else if (hasUrlScheme(modulePath)) { + } else if (HasUrlScheme(modulePath)) { size_t schemeEnd = modulePath.find("://"); size_t pathStart = (schemeEnd == std::string::npos) ? std::string::npos @@ -3908,6 +3847,52 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local return false; } } + + // The release allowlist rule, which debug builds never apply to + // fetches. `url` is spelled as the loader spells the URL it fetches, + // and `entries` goes through the same loading as the + // `security.remoteModuleAllowlist` config array. + auto allowlistCb = [](const v8::FunctionCallbackInfo& info) { + v8::Isolate* iso = info.GetIsolate(); + v8::Local ctx = iso->GetCurrentContext(); + std::vector> entries; + bool valid = info.Length() >= 2 && info[0]->IsString() && info[1]->IsArray(); + if (valid) { + v8::Local list = info[1].As(); + for (uint32_t i = 0; valid && i < list->Length(); i++) { + v8::Local item; + if (!list->Get(ctx, i).ToLocal(&item)) { + return; // the element getter threw + } + valid = item->IsString(); + if (valid) { + entries.push_back(ToExactUtf8(iso, item.As())); + } + } + } + if (!valid) { + iso->ThrowException(v8::Exception::TypeError(ToV8String( + iso, + "remoteUrlMatchesAllowlist expects a URL string and an array of strings"))); + return; + } + const std::string raw = ArgConverter::ToString(iso, info[0]); + const std::string url = NormalizeHttpModuleUrl(raw); + info.GetReturnValue().Set(RemoteUrlAllowedByAllowlist( + url.empty() ? raw : url, RemoteModuleAllowlistFromConfig(entries))); + }; + v8::Local allowlistFn; + if (!v8::Function::New(context, allowlistCb).ToLocal(&allowlistFn)) { + return false; + } + allowlistFn->SetName(ToV8String(isolate, "remoteUrlMatchesAllowlist")); + if (!binding + ->CreateDataProperty(context, + ToV8String(isolate, "remoteUrlMatchesAllowlist"), + allowlistFn) + .FromMaybe(false)) { + return false; + } } return true; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index 34752d848..cdb869fdc 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -124,6 +124,8 @@ v8::MaybeLocal GetOrCreateRequireFacade( // Authoritative HTTP URL loader for dev-served ESM. This compiles and // registers the module under its canonical URL key without evaluating it. +// `requestedUrl` must be spelled by NormalizeHttpModuleUrl: it is fetched as is +// and its key derives from it without spelling it again. // Returns empty with a V8 exception scheduled on `isolate` — the fetch // classifier's reason, or the compile error — so a caller that is not a V8 // resolve callback must consume it through its own TryCatch and route the text @@ -269,6 +271,8 @@ void SetCanonicalizationConfig(CanonicalizationConfig config); // - getLoadedModuleUrls() (registry introspection) // - createRequire(path) (a CommonJS require for `path`) // - canonicalizeHttpUrlKey(url) (debug builds only; test diagnostic) +// - remoteUrlMatchesAllowlist(url, entries) +// (debug builds only; test diagnostic) // // Worker teardown across HMR cycles is userland: the dev client intercepts // the global `Worker` constructor and terminates tracked instances diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.cpp b/test-app/runtime/src/main/cpp/ModuleUrl.cpp new file mode 100644 index 000000000..d86a93807 --- /dev/null +++ b/test-app/runtime/src/main/cpp/ModuleUrl.cpp @@ -0,0 +1,156 @@ +#include "ModuleUrl.h" + +#include + +#include "ada/ada.h" + +namespace tns { + +namespace { + +bool StartsWith(const std::string& s, const char* prefix) { + const size_t n = std::char_traits::length(prefix); + return s.size() >= n && s.compare(0, n, prefix) == 0; +} + +bool HasHttpScheme(const ada::url_aggregator& url) { + return url.type == ada::scheme::type::HTTP || + url.type == ada::scheme::type::HTTPS; +} + +// The authority (userinfo, host, port) of an absolute or scheme-relative URL +// exactly as written, or empty when `url` does not spell one plainly. +std::string WrittenAuthority(const std::string& url) { + size_t start = 0; + if (StartsWith(url, "//")) { + start = 2; + } else { + const size_t colon = url.find(':'); + if (colon == std::string::npos || url.compare(colon, 3, "://") != 0) { + return std::string(); + } + start = colon + 3; + } + const size_t end = url.find_first_of("/?#", start); + std::string authority = + url.substr(start, end == std::string::npos ? end : end - start); + for (const char c : authority) { + if (static_cast(c) <= 0x20 || c == '\\') { + return std::string(); + } + } + return authority; +} + +} // namespace + +bool IsHttpRegistryKey(const std::string& key) { + if (key.compare(0, 4, "http") != 0) { + return false; + } + const size_t schemeEnd = key.size() > 4 && key[4] == 's' ? 5 : 4; + return key.compare(schemeEnd, 3, "://") == 0; +} + +ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { + ModuleUrl result; + ada::result url; + if (base.empty()) { + url = ada::parse(input, nullptr); + } else { + auto baseUrl = ada::parse(base, nullptr); + if (!baseUrl) { + return result; + } + url = ada::parse(input, &baseUrl.value()); + } + if (!url) { + return result; + } + result.parsed = true; + result.http = HasHttpScheme(*url); + result.href = std::string(url->get_href()); + if (!result.http) { + return result; + } + + const std::string authority = + WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); + if (authority.empty()) { + return result; + } + const std::string_view href = url->get_href(); + const size_t authorityStart = url->get_protocol().size() + 2; + const size_t pathnameStart = url->get_components().pathname_start; + if (href.substr(authorityStart, pathnameStart - authorityStart) == + authority) { + return result; + } + // Everything after the authority comes from the parser's own href: its + // getters drop an empty query's '?' and an empty fragment's '#'. + const std::string written = std::string(url->get_protocol()) + "//" + + authority + + std::string(href.substr(pathnameStart)); + auto reparsed = ada::parse(written, nullptr); + if (reparsed && reparsed->get_href() == href) { + result.href = written; + } + return result; +} + +std::string NormalizeHttpModuleUrl(const std::string& input) { + // Fast reject only: the parser drops leading C0 controls and spaces, after + // which an http(s) URL (or an HTTP key) starts with 'h' or 'H'. + size_t first = 0; + while (first < input.size() && + static_cast(input[first]) <= 0x20) { + first++; + } + if (first == input.size() || (input[first] != 'h' && input[first] != 'H')) { + return std::string(); + } + const ModuleUrl url = ParseModuleUrl(input, std::string()); + if (url.parsed) { + return url.http ? url.href : std::string(); + } + return IsHttpRegistryKey(input) ? input : std::string(); +} + +bool HasUrlScheme(const std::string& s) { + const size_t colon = s.find(':'); + if (colon == 0 || colon == std::string::npos) { + return false; + } + const size_t slash = s.find('/'); + if (slash != std::string::npos && slash < colon) { + return false; + } + for (size_t i = 0; i < colon; i++) { + const char c = s[i]; + const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.'; + if (!ok) { + return false; + } + } + return true; +} + +std::string ReportedModuleUrl(const std::string& keyOrPath) { + if (keyOrPath.empty()) { + return "file:///app/"; + } + // Before the scheme test: the loader reads strings as http(s) URLs that the + // scheme test rejects (leading whitespace), and those must never be + // prefixed with file://. + const std::string http = NormalizeHttpModuleUrl(keyOrPath); + if (!http.empty()) { + return http; + } + if (HasUrlScheme(keyOrPath)) { + return keyOrPath; + } + return "file://" + keyOrPath; +} + +} // namespace tns diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.h b/test-app/runtime/src/main/cpp/ModuleUrl.h new file mode 100644 index 000000000..44bd43716 --- /dev/null +++ b/test-app/runtime/src/main/cpp/ModuleUrl.h @@ -0,0 +1,49 @@ +#pragma once + +#include + +namespace tns { + +// Whether `key` is spelled the way the loader keys an HTTP module: a lowercase +// `http://` or `https://` prefix, file modules being keyed by absolute paths. +// Deliberately not a URL parse: it gates the rule that an HTTP importer never +// reaches the filesystem implicitly, so a key the URL parser would reject (an +// IPv6 zone id, say) must still count as HTTP. +bool IsHttpRegistryKey(const std::string& key); + +struct ModuleUrl { + bool parsed = false; + bool http = false; // the scheme is http or https + std::string href; +}; + +// `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): +// as an absolute URL when `base` is empty, otherwise as a path- or +// scheme-relative reference against `base`. +// +// An http(s) result keeps its authority as written by whichever string +// supplied it: tooling compares module URLs against the origin string it was +// configured with, so that spelling is part of a module's identity. The +// parser's own href is used whenever the written authority would not name the +// same URL. +ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); + +// The spelling the loader gives `input` as an absolute http(s) module URL: +// ParseModuleUrl's href; `input` itself when the parser rejects it but it is +// spelled as an HTTP key (fail closed: it stays HTTP); empty when `input` is +// not an http(s) URL. +std::string NormalizeHttpModuleUrl(const std::string& input); + +// Whether `s` starts with a URL scheme and ':' (`node:fs`, `blob:…`, +// `http://…`) rather than being a filesystem path. +bool HasUrlScheme(const std::string& s); + +// The URL a module or script is reported under (script origin, +// import.meta.url, inspector target), from its registry key or path: an +// http(s) URL as NormalizeHttpModuleUrl spells it; any other string that +// carries a URL scheme unchanged; a filesystem path as `file://` plus the +// absolute path, `file:///app/` for an empty one. The only place a `file://` +// URL is built from a path. +std::string ReportedModuleUrl(const std::string& keyOrPath); + +} // namespace tns diff --git a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp index cba9672ea..bd8f871be 100644 --- a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp +++ b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp @@ -15,6 +15,7 @@ #include "JEnv.h" #include "JniLocalRef.h" #include "ModuleInternal.h" +#include "ModuleUrl.h" #include "NativeScriptAssert.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" @@ -960,11 +961,8 @@ void WorkerWrapper::CreateInspector(Isolate* isolate) { return; } - // Same url the module loader reports in Debugger.scriptParsed: an http(s) - // entry already IS that url, only a filesystem path needs the scheme. - std::string url = ModuleInternal::IsHttpModulePath(workerPath_) - ? workerPath_ - : "file://" + workerPath_; + // Same url the module loader reports in Debugger.scriptParsed. + std::string url = ReportedModuleUrl(workerPath_); auto* client = new WorkerInspectorClient(workerId_, isolate, ALooper_forThread(), url); { diff --git a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp index 7a430ea9e..1d32c8a75 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -6,6 +6,9 @@ #include "CallbackHandlers.h" #include "ArgConverter.h" #include "MetadataNode.h" +#include "ExactUtf8.h" +#include "HttpLoader.h" +#include "ModuleUrl.h" #include #include #include @@ -93,6 +96,16 @@ static void setManualInstrumentationModeFast_impl(JNIEnv* env, jclass clazz, jst } } +extern "C" JNIEXPORT jboolean Java_com_tns_Runtime_isRemoteUrlAllowedNative(JNIEnv* env, jclass, jstring url) { + // A string with no exact UTF-8 form names no fetchable URL. + const std::optional raw = tns::ToExactUtf8(env, url); + if (!raw.has_value()) { + return JNI_FALSE; + } + const std::string normalized = tns::NormalizeHttpModuleUrl(*raw); + return tns::IsRemoteUrlAllowed(normalized.empty() ? *raw : normalized) ? JNI_TRUE : JNI_FALSE; +} + // Auto-bound legacy variant for Android < 8.0 (annotation absent / unsupported). extern "C" JNIEXPORT void Java_com_tns_Runtime_setManualInstrumentationModeLegacy(JNIEnv* _env, jclass clazz, jstring mode) { setManualInstrumentationModeFast_impl(_env, clazz, mode); diff --git a/test-app/runtime/src/main/cpp/js/ns-module.js b/test-app/runtime/src/main/cpp/js/ns-module.js index 4059a7c10..9d57e30ea 100644 --- a/test-app/runtime/src/main/cpp/js/ns-module.js +++ b/test-app/runtime/src/main/cpp/js/ns-module.js @@ -6,7 +6,8 @@ // and freezes the exports. // // Membership varies by build: -// - `canonicalizeHttpUrlKey` exists only in debug builds (test diagnostic). +// - `canonicalizeHttpUrlKey` and `remoteUrlMatchesAllowlist` exist only in +// debug builds (test diagnostics). // Missing members are simply absent — never present-but-throwing — so // feature checks work. @@ -179,5 +180,8 @@ const surface = { if (binding.canonicalizeHttpUrlKey !== undefined) { surface.canonicalizeHttpUrlKey = binding.canonicalizeHttpUrlKey; } +if (binding.remoteUrlMatchesAllowlist !== undefined) { + surface.remoteUrlMatchesAllowlist = binding.remoteUrlMatchesAllowlist; +} module.exports = ObjectFreeze(surface); diff --git a/test-app/runtime/src/main/java/com/tns/AppConfig.java b/test-app/runtime/src/main/java/com/tns/AppConfig.java index 3195cf81d..ae826d5ab 100644 --- a/test-app/runtime/src/main/java/com/tns/AppConfig.java +++ b/test-app/runtime/src/main/java/com/tns/AppConfig.java @@ -5,8 +5,6 @@ import org.json.JSONArray; import android.os.Build; import android.util.Log; -import java.util.ArrayList; -import java.util.List; class AppConfig { protected enum KnownKeys { @@ -53,7 +51,10 @@ public Object getDefaultValue() { // Security config private boolean allowRemoteModules = false; - private List remoteModuleAllowlist = new ArrayList<>(); + // Null when the list is not in force (absent, not an array, or empty); + // otherwise one slot per item, null for an item that is not a string. + // Items are kept raw: the native gate decides what each one matches. + private String[] remoteModuleAllowlist = null; public AppConfig(File appDir) { values = makeDefaultOptions(); @@ -78,14 +79,15 @@ public AppConfig(File appDir) { if (securityObject.has("allowRemoteModules")) { allowRemoteModules = securityObject.getBoolean("allowRemoteModules"); } - if (securityObject.has("remoteModuleAllowlist")) { - JSONArray allowlist = securityObject.getJSONArray("remoteModuleAllowlist"); - for (int i = 0; i < allowlist.length(); i++) { - String url = allowlist.optString(i); - if (url != null && !url.isEmpty()) { - remoteModuleAllowlist.add(url); - } + JSONArray allowlist = securityObject.optJSONArray("remoteModuleAllowlist"); + if (allowlist != null && allowlist.length() > 0) { + String[] items = new String[allowlist.length()]; + for (int i = 0; i < items.length; i++) { + // Not optString: it turns 42 into "42" and null into "null". + Object item = allowlist.opt(i); + items[i] = item instanceof String ? (String) item : null; } + remoteModuleAllowlist = items; } } @@ -284,17 +286,10 @@ public boolean getAllowRemoteModules() { } /** - * Returns the list of allowed URL prefixes for remote module loading. - * Only used when allowRemoteModules is true. - */ - public List getRemoteModuleAllowlist() { - return remoteModuleAllowlist; - } - - /** - * Returns the allowlist + * The raw security.remoteModuleAllowlist items, or null when the list is + * not in force. An item that is not a string is a null slot. */ public String[] getRemoteModuleAllowlistArray() { - return remoteModuleAllowlist.toArray(new String[0]); + return remoteModuleAllowlist == null ? null : remoteModuleAllowlist.clone(); } } diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index dc51b898b..6a0b7d95a 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -426,9 +426,8 @@ public static boolean isDebuggable() { Runtime runtime = com.tns.Runtime.getCurrentRuntime(); if (runtime != null) { return runtime.config.isDebuggable; - } else { - return false; } + return staticConfiguration != null && staticConfiguration.isDebuggable; } // Security config @@ -454,55 +453,15 @@ public static boolean isRemoteModulesAllowed() { } /** - * checks against security.remoteModuleAllowlist. + * Whether the module loader would fetch `url` as a remote ES module: the + * native gate's answer, spelling `url` the way the loader spells the URLs + * it fetches. */ public static boolean isRemoteUrlAllowed(String url) { - // Debug mode always allows all URLs - if (isDebuggable()) { - return true; - } - - // Production: first check if remote modules are allowed at all - if (!isRemoteModulesAllowed()) { - return false; - } - - // Get the allowlist - String[] allowlist = getRemoteModuleAllowlist(); - - // If no allowlist is configured, allow all URLs (user explicitly enabled remote modules) - if (allowlist == null || allowlist.length == 0) { - return true; - } - - // Check if URL matches any allowlist prefix at a URL-component boundary - // (exact match, entry ends in '/', or next char is '/', '?', or '#'). - // This refuses lookalike-host and lookalike-port bypasses. - for (String prefix : allowlist) { - if (url != null && prefix != null && remoteUrlMatchesAllowlistEntry(url, prefix)) { - return true; - } - } - - return false; + return isRemoteUrlAllowedNative(url); } - private static boolean remoteUrlMatchesAllowlistEntry(String url, String entry) { - if (entry.isEmpty() || url.length() < entry.length()) { - return false; - } - if (!url.startsWith(entry)) { - return false; - } - if (url.length() == entry.length()) { - return true; - } - if (entry.charAt(entry.length() - 1) == '/') { - return true; - } - char next = url.charAt(entry.length()); - return next == '/' || next == '?' || next == '#'; - } + private static native boolean isRemoteUrlAllowedNative(String url); /** * Test/JNI helper: boot-time security.allowRemoteModules (debug always true). @@ -519,7 +478,8 @@ public static String[] getSecurityRemoteModuleAllowlist() { } /** - * Returns the remote module allowlist as a String array for JNI. + * The raw security.remoteModuleAllowlist items for JNI, or null when the + * list is not in force. An item that is not a string is a null slot. */ public static String[] getRemoteModuleAllowlist() { Runtime runtime = com.tns.Runtime.getCurrentRuntime(); @@ -529,7 +489,7 @@ public static String[] getRemoteModuleAllowlist() { if (staticConfiguration != null && staticConfiguration.appConfig != null) { return staticConfiguration.appConfig.getRemoteModuleAllowlistArray(); } - return new String[0]; + return null; } private static final int NO_OWNING_RUNTIME = -1;