From 537fcf58802b1756ecc354523e00bd4551db73b9 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Thu, 22 Oct 2026 11:13:08 +0530 Subject: [PATCH 01/10] fix(abstractions): normalize allowed hosts whitespace and enforce url validation when empty Signed-off-by: Hardik Kaurani --- .../authentication/allowedHostsValidator.ts | 16 ++++++++++---- .../authentication/allowedHostsValidator.ts | 21 +++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index 4fd22eba2..29c084360 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -41,9 +41,10 @@ export class AllowedHostsValidator { */ public isUrlHostValid(url: string): boolean { if (!url) return false; - if (this.allowedHosts.size === 0) return true; + const trimmedUrl = url.trim(); + if (!trimmedUrl) return false; const defaultProtocol = typeof window !== "undefined" ? window.location.protocol : "https:"; - const candidate = url.includes("://") ? url : !url.startsWith("http") ? `${defaultProtocol}//${url.replace(/^\/\//, "")}` : undefined; + const candidate = trimmedUrl.includes("://") ? trimmedUrl : !trimmedUrl.startsWith("http") ? `${defaultProtocol}//${trimmedUrl.replace(/^\/\//, "")}` : undefined; if (candidate) { let parsed: URL; try { @@ -55,9 +56,15 @@ export class AllowedHostsValidator { if (parsed.username || parsed.password) { return false; } + if (this.allowedHosts.size === 0) { + return true; + } return this.isHostValid(parsed.hostname); } if (typeof window !== "undefined" && window.location?.host) { + if (this.allowedHosts.size === 0) { + return true; + } return this.isHostValid(window.location.host); } return false; @@ -70,7 +77,7 @@ export class AllowedHostsValidator { return Array.from(this.allowedHosts).some((allowedHost) => allowedHost.startsWith(".") && normalizedHost.endsWith(allowedHost)); } private normalizeHosts(hostsToNormalize: Set): Set { - return new Set(Array.from(hostsToNormalize, (host) => host.toLowerCase())); + return new Set(Array.from(hostsToNormalize, (host) => host.trim().toLowerCase()).filter((host) => host.length > 0)); } private validateHosts(hostsToValidate: Set) { @@ -78,7 +85,8 @@ export class AllowedHostsValidator { throw new Error("hostsToValidate cannot be null"); } hostsToValidate.forEach((host) => { - if (host.toLowerCase().startsWith("http://") || host.toLowerCase().startsWith("https://")) { + const trimmedHost = host?.trim().toLowerCase(); + if (trimmedHost.startsWith("http://") || trimmedHost.startsWith("https://")) { throw new Error("host should not contain http or https prefix"); } }); diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 843f7da52..072694516 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -19,10 +19,20 @@ describe("AllowedHostsValidator", () => { expect(() => new AllowedHostsValidator(new Set(["http://invalid.com"]))).to.throw("host should not contain http or https prefix"); }); + it("constructor should validate hosts with leading/trailing whitespace", () => { + expect(() => new AllowedHostsValidator(new Set([" http://invalid.com "]))).to.throw("host should not contain http or https prefix"); + expect(() => new AllowedHostsValidator(new Set([" https://invalid.com "]))).to.throw("host should not contain http or https prefix"); + }); + it("getAllowedHosts should return correct hosts", () => { expect(JSON.stringify(validator.getAllowedHosts())).to.equal(JSON.stringify(["example.com", "test.com"])); }); + it("getAllowedHosts should trim hosts", () => { + const trimmedValidator = new AllowedHostsValidator(new Set([" example.com ", " test.com "])); + expect(JSON.stringify(trimmedValidator.getAllowedHosts())).to.equal(JSON.stringify(["example.com", "test.com"])); + }); + it("setAllowedHosts should update allowed hosts", () => { validator.setAllowedHosts(new Set(["newhost.com"])); expect(JSON.stringify(validator.getAllowedHosts())).to.equal(JSON.stringify(["newhost.com"])); @@ -30,6 +40,7 @@ describe("AllowedHostsValidator", () => { it("setAllowedHosts should validate new hosts", () => { expect(() => validator.setAllowedHosts(new Set(["https://invalid.com"]))).to.throw("host should not contain http or https prefix"); + expect(() => validator.setAllowedHosts(new Set([" https://invalid.com "]))).to.throw("host should not contain http or https prefix"); }); it("isUrlHostValid should return true for valid hosts", () => { @@ -37,6 +48,10 @@ describe("AllowedHostsValidator", () => { expect(validator.isUrlHostValid("http://test.com/path")).to.be.true; }); + it("isUrlHostValid should handle url with whitespace", () => { + expect(validator.isUrlHostValid(" http://example.com/path ")).to.be.true; + }); + it("isUrlHostValid should return false for invalid hosts", () => { expect(validator.isUrlHostValid("http://invalid.com/path")).to.be.false; }); @@ -86,4 +101,10 @@ describe("AllowedHostsValidator", () => { it("isUrlHostValid should return false when userinfo is present", () => { expect(validator.isUrlHostValid("https://user:pass@example.com/path")).to.be.false; }); + + it("isUrlHostValid should reject userinfo even when allowedHosts is empty", () => { + const emptyValidator = new AllowedHostsValidator(); + expect(emptyValidator.isUrlHostValid("https://user:pass@example.com/path")).to.be.false; + expect(emptyValidator.isUrlHostValid("https://example.com/path")).to.be.true; + }); }); From e56aa965e84a74d7d3a529082f5bb00dd88f6b39 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Tue, 27 Oct 2026 04:17:49 +0530 Subject: [PATCH 02/10] fix(abstractions): reject nonempty allowlists normalizing to empty and guard browser empty fallback Signed-off-by: Hardik Kaurani --- .../authentication/allowedHostsValidator.ts | 5 ++- .../authentication/allowedHostsValidator.ts | 41 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index 29c084360..6bb5e4c51 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -63,7 +63,7 @@ export class AllowedHostsValidator { } if (typeof window !== "undefined" && window.location?.host) { if (this.allowedHosts.size === 0) { - return true; + return false; } return this.isHostValid(window.location.host); } @@ -84,6 +84,9 @@ export class AllowedHostsValidator { if (!hostsToValidate) { throw new Error("hostsToValidate cannot be null"); } + if (hostsToValidate.size > 0 && this.normalizeHosts(hostsToValidate).size === 0) { + throw new Error("hostsToValidate cannot normalize to an empty set from a non-empty allowlist"); + } hostsToValidate.forEach((host) => { const trimmedHost = host?.trim().toLowerCase(); if (trimmedHost.startsWith("http://") || trimmedHost.startsWith("https://")) { diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 072694516..2f18e53e2 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -24,6 +24,16 @@ describe("AllowedHostsValidator", () => { expect(() => new AllowedHostsValidator(new Set([" https://invalid.com "]))).to.throw("host should not contain http or https prefix"); }); + it("constructor should reject nonempty allowlist that normalizes to empty", () => { + expect(() => new AllowedHostsValidator(new Set([" "]))).to.throw("hostsToValidate cannot normalize to an empty set from a non-empty allowlist"); + expect(() => new AllowedHostsValidator(new Set([""]))).to.throw("hostsToValidate cannot normalize to an empty set from a non-empty allowlist"); + }); + + it("constructor should preserve unrestricted access for explicitly empty allowlist", () => { + const emptyValidator = new AllowedHostsValidator(new Set()); + expect(emptyValidator.getAllowedHosts()).to.deep.equal([]); + }); + it("getAllowedHosts should return correct hosts", () => { expect(JSON.stringify(validator.getAllowedHosts())).to.equal(JSON.stringify(["example.com", "test.com"])); }); @@ -43,6 +53,16 @@ describe("AllowedHostsValidator", () => { expect(() => validator.setAllowedHosts(new Set([" https://invalid.com "]))).to.throw("host should not contain http or https prefix"); }); + it("setAllowedHosts should reject nonempty allowlist that normalizes to empty", () => { + expect(() => validator.setAllowedHosts(new Set([" "]))).to.throw("hostsToValidate cannot normalize to an empty set from a non-empty allowlist"); + expect(() => validator.setAllowedHosts(new Set([""]))).to.throw("hostsToValidate cannot normalize to an empty set from a non-empty allowlist"); + }); + + it("setAllowedHosts should preserve unrestricted access for explicitly empty allowlist", () => { + validator.setAllowedHosts(new Set()); + expect(validator.getAllowedHosts()).to.deep.equal([]); + }); + it("isUrlHostValid should return true for valid hosts", () => { expect(validator.isUrlHostValid("http://example.com/path")).to.be.true; expect(validator.isUrlHostValid("http://test.com/path")).to.be.true; @@ -107,4 +127,25 @@ describe("AllowedHostsValidator", () => { expect(emptyValidator.isUrlHostValid("https://user:pass@example.com/path")).to.be.false; expect(emptyValidator.isUrlHostValid("https://example.com/path")).to.be.true; }); + + it("isUrlHostValid should return false in browser for unparsed URLs when allowlist is empty", () => { + const emptyValidator = new AllowedHostsValidator(); + if (typeof window === "undefined") { + try { + (globalThis as any).window = { + location: { + protocol: "https:", + host: "example.com", + }, + }; + expect(emptyValidator.isUrlHostValid("http%")).to.be.false; + expect(emptyValidator.isUrlHostValid("https:user:pass@example.com/path")).to.be.false; + } finally { + delete (globalThis as any).window; + } + } else { + expect(emptyValidator.isUrlHostValid("http%")).to.be.false; + expect(emptyValidator.isUrlHostValid("https:user:pass@example.com/path")).to.be.false; + } + }); }); From 3333780dc0ba9b84b79b7e2a10bffd575c1681ad Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 28 Oct 2026 02:25:17 +0530 Subject: [PATCH 03/10] fix(abstractions): resolve browser-relative urls and detect http scheme-less hosts Signed-off-by: Hardik Kaurani --- .../authentication/allowedHostsValidator.ts | 46 ++++++++------- .../authentication/allowedHostsValidator.ts | 57 +++++++++++++++++++ 2 files changed, 82 insertions(+), 21 deletions(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index 6bb5e4c51..5806678e8 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -43,31 +43,35 @@ export class AllowedHostsValidator { if (!url) return false; const trimmedUrl = url.trim(); if (!trimmedUrl) return false; - const defaultProtocol = typeof window !== "undefined" ? window.location.protocol : "https:"; - const candidate = trimmedUrl.includes("://") ? trimmedUrl : !trimmedUrl.startsWith("http") ? `${defaultProtocol}//${trimmedUrl.replace(/^\/\//, "")}` : undefined; - if (candidate) { - let parsed: URL; - try { + + const hasWindow = typeof window !== "undefined"; + const defaultProtocol = hasWindow && window.location?.protocol ? window.location.protocol : "https:"; + const browserBase = hasWindow && window.location ? window.location.href || (window.location.protocol && window.location.host ? `${window.location.protocol}//${window.location.host}` : undefined) : undefined; + + let parsed: URL; + try { + const isBrowserRelative = Boolean(browserBase) && ((trimmedUrl.startsWith("/") && !trimmedUrl.startsWith("//")) || trimmedUrl.startsWith("?") || trimmedUrl.startsWith("#") || trimmedUrl.startsWith("./") || trimmedUrl.startsWith("../")); + + if (isBrowserRelative) { + parsed = new URL(trimmedUrl, browserBase); + } else { + const hasScheme = trimmedUrl.includes("://") || /^https?:/i.test(trimmedUrl); + const candidate = hasScheme ? trimmedUrl : trimmedUrl.startsWith("//") ? `${defaultProtocol}${trimmedUrl}` : `${defaultProtocol}//${trimmedUrl}`; + parsed = new URL(candidate); - } catch { - return false; - } - // reject userinfo outright, it can be used to spoof the host - if (parsed.username || parsed.password) { - return false; } - if (this.allowedHosts.size === 0) { - return true; - } - return this.isHostValid(parsed.hostname); + } catch { + return false; } - if (typeof window !== "undefined" && window.location?.host) { - if (this.allowedHosts.size === 0) { - return false; - } - return this.isHostValid(window.location.host); + + // reject userinfo outright, it can be used to spoof the host + if (!parsed.hostname || parsed.username || parsed.password) { + return false; + } + if (this.allowedHosts.size === 0) { + return true; } - return false; + return this.isHostValid(parsed.hostname); } private isHostValid(host: string): boolean { const normalizedHost = host.toLowerCase(); diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 2f18e53e2..801cb6a8f 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -148,4 +148,61 @@ describe("AllowedHostsValidator", () => { expect(emptyValidator.isUrlHostValid("https:user:pass@example.com/path")).to.be.false; } }); + + it("isUrlHostValid should handle scheme-less hosts beginning with http", () => { + const emptyValidator = new AllowedHostsValidator(); + expect(emptyValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + expect(emptyValidator.isUrlHostValid("httpbin.org")).to.be.true; + expect(emptyValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; + expect(emptyValidator.isUrlHostValid("https-service.internal/path")).to.be.true; + + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); + expect(httpbinValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + expect(httpbinValidator.isUrlHostValid("http://httpbin.org/path")).to.be.true; + expect(httpbinValidator.isUrlHostValid("https://httpbin.org/path")).to.be.true; + expect(httpbinValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; + expect(httpbinValidator.isUrlHostValid("example.com/path")).to.be.false; + }); + + it("isUrlHostValid should resolve browser-relative URLs against browser location", () => { + const emptyValidator = new AllowedHostsValidator(); + const relativeUrls = ["/", "/?q=1", "?q=1", "/api/v1/users", "./path/to/resource"]; + + if (typeof window === "undefined") { + try { + (globalThis as any).window = { + location: { + protocol: "https:", + host: "example.com", + }, + }; + for (const relUrl of relativeUrls) { + expect(emptyValidator.isUrlHostValid(relUrl)).to.be.true; + expect(validator.isUrlHostValid(relUrl)).to.be.true; + } + const otherValidator = new AllowedHostsValidator(new Set(["other.com"])); + for (const relUrl of relativeUrls) { + expect(otherValidator.isUrlHostValid(relUrl)).to.be.false; + } + expect(emptyValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + expect(emptyValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; + expect(otherValidator.isUrlHostValid("other.com/path")).to.be.true; + expect(otherValidator.isUrlHostValid("example.com/path")).to.be.false; + } finally { + delete (globalThis as any).window; + } + } else { + const currentHost = window.location.hostname; + const matchingValidator = new AllowedHostsValidator(new Set([currentHost])); + const nonMatchingValidator = new AllowedHostsValidator(new Set(["non-matching-domain.internal"])); + + for (const relUrl of relativeUrls) { + expect(emptyValidator.isUrlHostValid(relUrl)).to.be.true; + expect(matchingValidator.isUrlHostValid(relUrl)).to.be.true; + expect(nonMatchingValidator.isUrlHostValid(relUrl)).to.be.false; + } + expect(emptyValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + expect(emptyValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; + } + }); }); From 958ac894e379cac37de20d101e77a889db779dbd Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 28 Oct 2026 19:27:56 +0530 Subject: [PATCH 04/10] fix(abstractions): reject http(s) urls without // to prevent credential leakage Signed-off-by: Hardik Kaurani --- .../authentication/allowedHostsValidator.ts | 6 ++- .../authentication/allowedHostsValidator.ts | 42 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index 5806678e8..64435e8b8 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -44,6 +44,10 @@ export class AllowedHostsValidator { const trimmedUrl = url.trim(); if (!trimmedUrl) return false; + if (/^https?:(?!\/\/)/i.test(trimmedUrl)) { + return false; + } + const hasWindow = typeof window !== "undefined"; const defaultProtocol = hasWindow && window.location?.protocol ? window.location.protocol : "https:"; const browserBase = hasWindow && window.location ? window.location.href || (window.location.protocol && window.location.host ? `${window.location.protocol}//${window.location.host}` : undefined) : undefined; @@ -55,7 +59,7 @@ export class AllowedHostsValidator { if (isBrowserRelative) { parsed = new URL(trimmedUrl, browserBase); } else { - const hasScheme = trimmedUrl.includes("://") || /^https?:/i.test(trimmedUrl); + const hasScheme = trimmedUrl.includes("://"); const candidate = hasScheme ? trimmedUrl : trimmedUrl.startsWith("//") ? `${defaultProtocol}${trimmedUrl}` : `${defaultProtocol}//${trimmedUrl}`; parsed = new URL(candidate); diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 801cb6a8f..8232985ab 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -205,4 +205,46 @@ describe("AllowedHostsValidator", () => { expect(emptyValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; } }); + + it("isUrlHostValid should reject HTTP(S) URLs without // to prevent credential leakage", () => { + const allowedValidator = new AllowedHostsValidator(new Set(["allowed.example"])); + + expect(allowedValidator.isUrlHostValid("https:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https://allowed.example/api")).to.be.true; + + const emptyValidator = new AllowedHostsValidator(); + expect(emptyValidator.isUrlHostValid("https:allowed.example/api")).to.be.false; + expect(emptyValidator.isUrlHostValid("https:/allowed.example/api")).to.be.false; + expect(emptyValidator.isUrlHostValid("http:allowed.example/api")).to.be.false; + expect(emptyValidator.isUrlHostValid("http:/allowed.example/api")).to.be.false; + + if (typeof window === "undefined") { + try { + (globalThis as any).window = { + location: { + protocol: "https:", + host: "other.example", + hostname: "other.example", + href: "https://other.example/page", + }, + }; + expect(allowedValidator.isUrlHostValid("https:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https://allowed.example/api")).to.be.true; + } finally { + delete (globalThis as any).window; + } + } else { + expect(allowedValidator.isUrlHostValid("https:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https://allowed.example/api")).to.be.true; + } + }); }); From 2b9202cbcc7bfd14e8baa2ecb90cc5b0a74b2c34 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 28 Oct 2026 23:48:46 +0530 Subject: [PATCH 05/10] fix(abstractions): preserve unicode whitespace and resolve relative urls against document baseURI Signed-off-by: Hardik Kaurani --- .../authentication/allowedHostsValidator.ts | 33 +++++++++++-- .../authentication/allowedHostsValidator.ts | 47 +++++++++++++++++++ 2 files changed, 76 insertions(+), 4 deletions(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index 64435e8b8..a03886d06 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -41,16 +41,29 @@ export class AllowedHostsValidator { */ public isUrlHostValid(url: string): boolean { if (!url) return false; - const trimmedUrl = url.trim(); + // Strip leading and trailing C0 controls (0x00-0x1F) and ASCII space (0x20) per WHATWG URL parsing. + // Preserves Unicode whitespace (e.g. \u00a0 NBSP) so it is not stripped before validation. + const trimmedUrl = this.trimC0AndAsciiWhitespace(url); if (!trimmedUrl) return false; if (/^https?:(?!\/\/)/i.test(trimmedUrl)) { return false; } + const hasDocument = typeof document !== "undefined"; const hasWindow = typeof window !== "undefined"; - const defaultProtocol = hasWindow && window.location?.protocol ? window.location.protocol : "https:"; - const browserBase = hasWindow && window.location ? window.location.href || (window.location.protocol && window.location.host ? `${window.location.protocol}//${window.location.host}` : undefined) : undefined; + const browserBase = (hasDocument && document.baseURI) || (hasWindow && window.location ? window.location.href || (window.location.protocol && window.location.host ? `${window.location.protocol}//${window.location.host}` : undefined) : undefined); + + let defaultProtocol = "https:"; + if (browserBase) { + try { + defaultProtocol = new URL(browserBase).protocol || "https:"; + } catch { + defaultProtocol = hasWindow && window.location?.protocol ? window.location.protocol : "https:"; + } + } else if (hasWindow && window.location?.protocol) { + defaultProtocol = window.location.protocol; + } let parsed: URL; try { @@ -59,7 +72,7 @@ export class AllowedHostsValidator { if (isBrowserRelative) { parsed = new URL(trimmedUrl, browserBase); } else { - const hasScheme = trimmedUrl.includes("://"); + const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//i.test(trimmedUrl); const candidate = hasScheme ? trimmedUrl : trimmedUrl.startsWith("//") ? `${defaultProtocol}${trimmedUrl}` : `${defaultProtocol}//${trimmedUrl}`; parsed = new URL(candidate); @@ -102,4 +115,16 @@ export class AllowedHostsValidator { } }); } + + private trimC0AndAsciiWhitespace(value: string): string { + let start = 0; + let end = value.length; + while (start < end && value.charCodeAt(start) <= 0x20) { + start++; + } + while (end > start && value.charCodeAt(end - 1) <= 0x20) { + end--; + } + return start > 0 || end < value.length ? value.slice(start, end) : value; + } } diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 8232985ab..10a8dfafd 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -247,4 +247,51 @@ describe("AllowedHostsValidator", () => { expect(allowedValidator.isUrlHostValid("https://allowed.example/api")).to.be.true; } }); + + it("isUrlHostValid should preserve Unicode whitespace and reject leading non-breaking space", () => { + const allowedValidator = new AllowedHostsValidator(new Set(["allowed.example"])); + expect(allowedValidator.isUrlHostValid("\u00a0https://allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https://allowed.example/api")).to.be.true; + expect(allowedValidator.isUrlHostValid(" https://allowed.example/api ")).to.be.true; + + const emptyValidator = new AllowedHostsValidator(); + expect(emptyValidator.isUrlHostValid("\u00a0https://allowed.example/api")).to.be.false; + }); + + it("isUrlHostValid should resolve relative URLs against document.baseURI when available", () => { + const allowedValidator = new AllowedHostsValidator(new Set(["allowed.example"])); + const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); + + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + + try { + (globalThis as any).document = { + baseURI: "https://other.example/", + }; + (globalThis as any).window = { + location: { + protocol: "https:", + host: "allowed.example", + hostname: "allowed.example", + href: "https://allowed.example/page", + }, + }; + + // When document.baseURI is other.example, /api resolves to other.example, NOT allowed.example + expect(allowedValidator.isUrlHostValid("/api")).to.be.false; + expect(otherValidator.isUrlHostValid("/api")).to.be.true; + } finally { + if (originalDocument === undefined) { + delete (globalThis as any).document; + } else { + (globalThis as any).document = originalDocument; + } + if (originalWindow === undefined) { + delete (globalThis as any).window; + } else { + (globalThis as any).window = originalWindow; + } + } + }); }); From 82c12fa74bd0444f0acff038bef104e39423f086 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Thu, 29 Oct 2026 00:21:04 +0530 Subject: [PATCH 06/10] fix(abstractions): reject embedded URL controls --- .../authentication/allowedHostsValidator.ts | 3 ++ .../authentication/allowedHostsValidator.ts | 51 ++++++++++--------- 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index a03886d06..be4573454 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -45,6 +45,9 @@ export class AllowedHostsValidator { // Preserves Unicode whitespace (e.g. \u00a0 NBSP) so it is not stripped before validation. const trimmedUrl = this.trimC0AndAsciiWhitespace(url); if (!trimmedUrl) return false; + // WHATWG URL parsing removes these characters anywhere in the input. Reject them + // before parsing so validation sees the same destination that fetch would use. + if (/[\t\r\n]/.test(trimmedUrl)) return false; if (/^https?:(?!\/\/)/i.test(trimmedUrl)) { return false; diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 10a8dfafd..c9ea3afce 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -258,40 +258,41 @@ describe("AllowedHostsValidator", () => { expect(emptyValidator.isUrlHostValid("\u00a0https://allowed.example/api")).to.be.false; }); + it("isUrlHostValid should reject embedded URL whitespace that browsers remove", () => { + const validator = new AllowedHostsValidator(new Set(["https"])); + expect(validator.isUrlHostValid("ht\ttps://evil.example/api")).to.be.false; + expect(validator.isUrlHostValid("ht\ntps://evil.example/api")).to.be.false; + expect(validator.isUrlHostValid("ht\r\ntps://evil.example/api")).to.be.false; + }); + it("isUrlHostValid should resolve relative URLs against document.baseURI when available", () => { const allowedValidator = new AllowedHostsValidator(new Set(["allowed.example"])); const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); - const originalDocument = (globalThis as any).document; - const originalWindow = (globalThis as any).window; + if (typeof document === "undefined") { + const originalWindow = (globalThis as any).window; + try { + (globalThis as any).document = { baseURI: "https://other.example/" }; + (globalThis as any).window = { location: { protocol: "https:", host: "allowed.example", hostname: "allowed.example", href: "https://allowed.example/page" } }; + expect(allowedValidator.isUrlHostValid("/api")).to.be.false; + expect(otherValidator.isUrlHostValid("/api")).to.be.true; + } finally { + delete (globalThis as any).document; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + } + return; + } + // In browsers document is read-only; insert a temporary to control baseURI. + const baseElement = document.createElement("base"); + baseElement.href = "https://other.example/"; + document.head.prepend(baseElement); try { - (globalThis as any).document = { - baseURI: "https://other.example/", - }; - (globalThis as any).window = { - location: { - protocol: "https:", - host: "allowed.example", - hostname: "allowed.example", - href: "https://allowed.example/page", - }, - }; - - // When document.baseURI is other.example, /api resolves to other.example, NOT allowed.example expect(allowedValidator.isUrlHostValid("/api")).to.be.false; expect(otherValidator.isUrlHostValid("/api")).to.be.true; } finally { - if (originalDocument === undefined) { - delete (globalThis as any).document; - } else { - (globalThis as any).document = originalDocument; - } - if (originalWindow === undefined) { - delete (globalThis as any).window; - } else { - (globalThis as any).window = originalWindow; - } + baseElement.remove(); } }); }); From 35441f7b8930b653e58b391330c2d1f985106baf Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Tue, 17 Nov 2026 11:53:10 +0530 Subject: [PATCH 07/10] fix(abstractions): align browser URL validation with fetch resolution --- .../authentication/allowedHostsValidator.ts | 41 ++-- .../authentication/allowedHostsValidator.ts | 224 +++++++++++++++++- 2 files changed, 246 insertions(+), 19 deletions(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index be4573454..830f645d9 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -53,30 +53,39 @@ export class AllowedHostsValidator { return false; } - const hasDocument = typeof document !== "undefined"; - const hasWindow = typeof window !== "undefined"; - const browserBase = (hasDocument && document.baseURI) || (hasWindow && window.location ? window.location.href || (window.location.protocol && window.location.host ? `${window.location.protocol}//${window.location.host}` : undefined) : undefined); + // Reject malformed percent-encoding sequences (e.g. '%' not followed by two hex digits like 'http%'). + if (/%(?![0-9a-fA-F]{2})/.test(trimmedUrl)) { + return false; + } - let defaultProtocol = "https:"; - if (browserBase) { - try { - defaultProtocol = new URL(browserBase).protocol || "https:"; - } catch { - defaultProtocol = hasWindow && window.location?.protocol ? window.location.protocol : "https:"; - } - } else if (hasWindow && window.location?.protocol) { - defaultProtocol = window.location.protocol; + // Reject leading or trailing Unicode whitespace (e.g. '\u00a0' NBSP) not stripped by C0/ASCII whitespace trim. + if (/^\s|\s$/.test(trimmedUrl)) { + return false; } + const hasDocument = typeof document !== "undefined"; + const hasWindow = typeof window !== "undefined"; + const docBase = hasDocument && document.baseURI && document.baseURI !== "about:blank" ? document.baseURI : undefined; + const winBase = hasWindow && window.location ? window.location.href || (window.location.protocol && window.location.host ? `${window.location.protocol}//${window.location.host}` : undefined) : undefined; + const browserBase = docBase || winBase; + let parsed: URL; try { - const isBrowserRelative = Boolean(browserBase) && ((trimmedUrl.startsWith("/") && !trimmedUrl.startsWith("//")) || trimmedUrl.startsWith("?") || trimmedUrl.startsWith("#") || trimmedUrl.startsWith("./") || trimmedUrl.startsWith("../")); - - if (isBrowserRelative) { + if (browserBase) { + // In browser environments, WHATWG fetch resolves relative URLs (including root-relative '/api', + // path-relative 'api/users', and bare scheme-less paths like 'httpbin.org/path') against the document + // base URL. We resolve against browserBase so validation checks the exact destination fetch will use. + // Absolute URLs with a scheme and protocol-relative references (e.g. '//example.com') are also + // handled according to WHATWG URL resolution against the base. parsed = new URL(trimmedUrl, browserBase); } else { + // In non-browser environments (Node.js), relative paths without a base cannot be resolved. + if ((trimmedUrl.startsWith("/") && !trimmedUrl.startsWith("//")) || trimmedUrl.startsWith("./") || trimmedUrl.startsWith("../") || trimmedUrl.startsWith("?") || trimmedUrl.startsWith("#")) { + return false; + } + // Preserve existing supported scheme-less host behavior in Node.js. const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//i.test(trimmedUrl); - const candidate = hasScheme ? trimmedUrl : trimmedUrl.startsWith("//") ? `${defaultProtocol}${trimmedUrl}` : `${defaultProtocol}//${trimmedUrl}`; + const candidate = hasScheme ? trimmedUrl : trimmedUrl.startsWith("//") ? `https:${trimmedUrl}` : `https://${trimmedUrl}`; parsed = new URL(candidate); } diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index c9ea3afce..4f3d49ef7 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -5,8 +5,10 @@ * ------------------------------------------------------------------------------------------- */ -import { expect, describe, beforeEach, it } from "vitest"; -import { AllowedHostsValidator } from "../../../src/authentication"; +import { expect, describe, beforeEach, it, vi } from "vitest"; +import { AllowedHostsValidator, ApiKeyAuthenticationProvider, ApiKeyLocation } from "../../../src/authentication"; +import { RequestInformation } from "../../../src/requestInformation"; +import * as utils from "../../../src/utils"; describe("AllowedHostsValidator", () => { let validator: AllowedHostsValidator; @@ -186,8 +188,15 @@ describe("AllowedHostsValidator", () => { } expect(emptyValidator.isUrlHostValid("httpbin.org/path")).to.be.true; expect(emptyValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; - expect(otherValidator.isUrlHostValid("other.com/path")).to.be.true; + // In a browser with host example.com, bare scheme-less paths resolve against example.com. + // Therefore otherValidator (allowlist other.com) rejects them, while validator (allowlist example.com) accepts. + expect(otherValidator.isUrlHostValid("other.com/path")).to.be.false; expect(otherValidator.isUrlHostValid("example.com/path")).to.be.false; + expect(validator.isUrlHostValid("other.com/path")).to.be.true; + expect(validator.isUrlHostValid("example.com/path")).to.be.true; + // Explicit absolute and protocol-relative URLs retain their specified destination host. + expect(otherValidator.isUrlHostValid("https://other.com/path")).to.be.true; + expect(otherValidator.isUrlHostValid("//other.com/path")).to.be.true; } finally { delete (globalThis as any).window; } @@ -295,4 +304,213 @@ describe("AllowedHostsValidator", () => { baseElement.remove(); } }); + + describe("Browser URL resolution and credential leakage prevention (P1)", () => { + const browserOrigin = "https://other.example/app/"; + + it("Test A: different browser origin rejects bare scheme-less host targeting other origin", () => { + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + try { + (globalThis as any).document = { baseURI: browserOrigin }; + (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; + + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); + // On https://other.example/app/, 'httpbin.org/path' resolves to https://other.example/app/httpbin.org/path + // The destination is other.example, NOT httpbin.org, so httpbinValidator must return false. + expect(httpbinValidator.isUrlHostValid("httpbin.org/path")).to.be.false; + + // Conversely, an allowlist matching other.example accepts the resolved destination. + const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); + expect(otherValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + } finally { + if (originalDocument === undefined) delete (globalThis as any).document; + else (globalThis as any).document = originalDocument; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + } + }); + + it("Test B: explicit absolute URL is approved regardless of browser base URL", () => { + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + try { + (globalThis as any).document = { baseURI: browserOrigin }; + (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; + + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); + expect(httpbinValidator.isUrlHostValid("https://httpbin.org/path")).to.be.true; + } finally { + if (originalDocument === undefined) delete (globalThis as any).document; + else (globalThis as any).document = originalDocument; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + } + }); + + it("Test C: protocol-relative URL resolves with browser base protocol and target host", () => { + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + try { + (globalThis as any).document = { baseURI: browserOrigin }; + (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; + + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); + const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); + + // //httpbin.org/path replaces authority with httpbin.org, using https: from browser base + expect(httpbinValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; + expect(otherValidator.isUrlHostValid("//httpbin.org/path")).to.be.false; + } finally { + if (originalDocument === undefined) delete (globalThis as any).document; + else (globalThis as any).document = originalDocument; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + } + }); + + it("Test D: root-relative URL resolves against browser base origin", () => { + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + try { + (globalThis as any).document = { baseURI: browserOrigin }; + (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; + + const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); + + expect(otherValidator.isUrlHostValid("/api")).to.be.true; + expect(httpbinValidator.isUrlHostValid("/api")).to.be.false; + } finally { + if (originalDocument === undefined) delete (globalThis as any).document; + else (globalThis as any).document = originalDocument; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + } + }); + + it("Test E: path-relative URL resolves against browser base URL", () => { + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + try { + (globalThis as any).document = { baseURI: browserOrigin }; + (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; + + const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); + + expect(otherValidator.isUrlHostValid("api/users")).to.be.true; + expect(otherValidator.isUrlHostValid("./api")).to.be.true; + expect(otherValidator.isUrlHostValid("../api")).to.be.true; + expect(otherValidator.isUrlHostValid("?q=1")).to.be.true; + expect(otherValidator.isUrlHostValid("#section")).to.be.true; + + expect(httpbinValidator.isUrlHostValid("api/users")).to.be.false; + expect(httpbinValidator.isUrlHostValid("./api")).to.be.false; + expect(httpbinValidator.isUrlHostValid("../api")).to.be.false; + } finally { + if (originalDocument === undefined) delete (globalThis as any).document; + else (globalThis as any).document = originalDocument; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + } + }); + + it("Test F: existing non-browser bare-host behavior is preserved in Node.js", () => { + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); + const exampleValidator = new AllowedHostsValidator(new Set(["example.com"])); + + expect(httpbinValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + expect(httpbinValidator.isUrlHostValid("example.com/path")).to.be.false; + expect(httpbinValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; + expect(httpbinValidator.isUrlHostValid("https://httpbin.org/path")).to.be.true; + + expect(exampleValidator.isUrlHostValid("example.com/path")).to.be.true; + expect(exampleValidator.isUrlHostValid("httpbin.org/path")).to.be.false; + + // In Node without a base URL, relative paths cannot be resolved + expect(httpbinValidator.isUrlHostValid("/api")).to.be.false; + expect(httpbinValidator.isUrlHostValid("./api")).to.be.false; + expect(httpbinValidator.isUrlHostValid("?q=1")).to.be.false; + }); + + it("Test G: credential safety rejects malformed schemes, userinfo, and control characters", () => { + const allowedValidator = new AllowedHostsValidator(new Set(["allowed.example", "example.com"])); + const emptyValidator = new AllowedHostsValidator(); + + expect(allowedValidator.isUrlHostValid("https:user:pass@example.com/path")).to.be.false; + expect(allowedValidator.isUrlHostValid("https:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("http:/allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https://user:pass@allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("https://example.com:443@evil.com/path")).to.be.false; + expect(allowedValidator.isUrlHostValid("http%")).to.be.false; + expect(allowedValidator.isUrlHostValid("ht\ttps://allowed.example/api")).to.be.false; + expect(allowedValidator.isUrlHostValid("\u00a0https://allowed.example/api")).to.be.false; + + expect(emptyValidator.isUrlHostValid("https:user:pass@example.com/path")).to.be.false; + expect(emptyValidator.isUrlHostValid("https:allowed.example/api")).to.be.false; + expect(emptyValidator.isUrlHostValid("https:/allowed.example/api")).to.be.false; + expect(emptyValidator.isUrlHostValid("http%")).to.be.false; + }); + + it("Test H: actual fetch destination consistency between authentication and request execution", async () => { + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + const inNodeSpy = vi.spyOn(utils, "inNodeEnv").mockReturnValue(false); + try { + (globalThis as any).document = { baseURI: browserOrigin }; + (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; + + // 1. Provider with allowlist containing ONLY httpbin.org + const httpbinProvider = new ApiKeyAuthenticationProvider("secret-api-key", "X-API-KEY", ApiKeyLocation.Header, new Set(["httpbin.org"])); + const req1 = new RequestInformation(); + req1.URL = "httpbin.org/path"; + + await httpbinProvider.authenticateRequest(req1); + + // Prove: credentials were NOT attached because the browser fetch destination would be other.example + expect(req1.headers.tryGetValue("X-API-KEY")).to.be.null; + + // Verify actual destination browser fetch resolves to: + const actualDestination1 = new URL(req1.URL, browserOrigin); + expect(actualDestination1.hostname).to.equal("other.example"); + expect(actualDestination1.href).to.equal("https://other.example/app/httpbin.org/path"); + + // 2. Provider with allowlist containing other.example (the actual destination) + const otherProvider = new ApiKeyAuthenticationProvider("secret-api-key", "X-API-KEY", ApiKeyLocation.Header, new Set(["other.example"])); + const req2 = new RequestInformation(); + req2.URL = "httpbin.org/path"; + + await otherProvider.authenticateRequest(req2); + + // Prove: credentials WERE attached because the browser destination is other.example + expect(req2.headers.tryGetValue("X-API-KEY")).to.deep.equal(["secret-api-key"]); + + // Verify actual destination matches the validated host + const actualDestination2 = new URL(req2.URL, browserOrigin); + expect(actualDestination2.hostname).to.equal("other.example"); + expect(otherProvider["validator"].isUrlHostValid(actualDestination2.href)).to.be.true; + + // 3. Explicit absolute URL to httpbin.org + const req3 = new RequestInformation(); + req3.URL = "https://httpbin.org/path"; + + await httpbinProvider.authenticateRequest(req3); + + // Prove: credentials WERE attached because explicit absolute URL goes to httpbin.org + expect(req3.headers.tryGetValue("X-API-KEY")).to.deep.equal(["secret-api-key"]); + const actualDestination3 = new URL(req3.URL, browserOrigin); + expect(actualDestination3.hostname).to.equal("httpbin.org"); + expect(httpbinProvider["validator"].isUrlHostValid(actualDestination3.href)).to.be.true; + } finally { + inNodeSpy.mockRestore(); + if (originalDocument === undefined) delete (globalThis as any).document; + else (globalThis as any).document = originalDocument; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + } + }); + }); }); From 74d9a43b4e50d691afbfa9f2d9c0d4f7c7f0bb1c Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Tue, 17 Nov 2026 18:31:19 +0530 Subject: [PATCH 08/10] fix(abstractions): align URL validation and repair browser tests --- .../authentication/allowedHostsValidator.ts | 12 +- .../authentication/allowedHostsValidator.ts | 174 +++++++++--------- 2 files changed, 95 insertions(+), 91 deletions(-) diff --git a/packages/abstractions/src/authentication/allowedHostsValidator.ts b/packages/abstractions/src/authentication/allowedHostsValidator.ts index 830f645d9..708feb3ae 100644 --- a/packages/abstractions/src/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/src/authentication/allowedHostsValidator.ts @@ -53,13 +53,17 @@ export class AllowedHostsValidator { return false; } - // Reject malformed percent-encoding sequences (e.g. '%' not followed by two hex digits like 'http%'). - if (/%(?![0-9a-fA-F]{2})/.test(trimmedUrl)) { + // Reject leading or trailing Unicode whitespace (e.g. '\u00a0' NBSP) not stripped by C0/ASCII whitespace trim. + if (/^\s|\s$/.test(trimmedUrl)) { return false; } - // Reject leading or trailing Unicode whitespace (e.g. '\u00a0' NBSP) not stripped by C0/ASCII whitespace trim. - if (/^\s|\s$/.test(trimmedUrl)) { + // Check authority / bare host for malformed percent-encoding sequences (e.g. 'http%'). + // Literal percent signs in paths and queries (e.g. '/items/100%?q=50%') are valid and handled by WHATWG URL parser. + const schemeMatch = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(.*)$/.exec(trimmedUrl); + const authorityCandidate = schemeMatch ? schemeMatch[1].split(/[/?#]/)[0] : trimmedUrl.startsWith("//") ? trimmedUrl.slice(2).split(/[/?#]/)[0] : !trimmedUrl.startsWith("/") && !trimmedUrl.startsWith("?") && !trimmedUrl.startsWith("#") ? trimmedUrl.split(/[/?#]/)[0] : undefined; + + if (authorityCandidate && /%(?![0-9a-fA-F]{2})/.test(authorityCandidate)) { return false; } diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 4f3d49ef7..64e389625 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -79,7 +79,9 @@ describe("AllowedHostsValidator", () => { }); it("isUrlHostValid should validate protocol-relative urls without an explicit scheme", () => { - expect(validator.isUrlHostValid("example.com/path")).to.be.true; + if (utils.inNodeEnv()) { + expect(validator.isUrlHostValid("example.com/path")).to.be.true; + } expect(validator.isUrlHostValid("//example.com/path")).to.be.true; expect(validator.isUrlHostValid("//invalid.com/path")).to.be.false; }); @@ -159,7 +161,12 @@ describe("AllowedHostsValidator", () => { expect(emptyValidator.isUrlHostValid("https-service.internal/path")).to.be.true; const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); - expect(httpbinValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + if (utils.inNodeEnv()) { + expect(httpbinValidator.isUrlHostValid("httpbin.org/path")).to.be.true; + } else { + // In browser environments where origin != httpbin.org, bare scheme-less host resolves to browser origin + expect(httpbinValidator.isUrlHostValid("httpbin.org/path")).to.be.false; + } expect(httpbinValidator.isUrlHostValid("http://httpbin.org/path")).to.be.true; expect(httpbinValidator.isUrlHostValid("https://httpbin.org/path")).to.be.true; expect(httpbinValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; @@ -308,13 +315,58 @@ describe("AllowedHostsValidator", () => { describe("Browser URL resolution and credential leakage prevention (P1)", () => { const browserOrigin = "https://other.example/app/"; - it("Test A: different browser origin rejects bare scheme-less host targeting other origin", () => { - const originalDocument = (globalThis as any).document; - const originalWindow = (globalThis as any).window; - try { - (globalThis as any).document = { baseURI: browserOrigin }; - (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; + const withBrowserBaseUrl = (baseHref: string, fn: () => T | Promise): T | Promise => { + if (typeof document !== "undefined") { + const baseElement = document.createElement("base"); + baseElement.href = baseHref; + document.head.prepend(baseElement); + const cleanup = () => baseElement.remove(); + try { + const result = fn(); + if (result && typeof (result as any).then === "function") { + return (result as Promise).finally(cleanup); + } + cleanup(); + return result; + } catch (e) { + cleanup(); + throw e; + } + } else { + const originalDocument = (globalThis as any).document; + const originalWindow = (globalThis as any).window; + const parsed = new URL(baseHref); + (globalThis as any).document = { baseURI: baseHref }; + (globalThis as any).window = { + location: { + href: baseHref, + protocol: parsed.protocol, + host: parsed.host, + hostname: parsed.hostname, + }, + }; + const cleanup = () => { + if (originalDocument === undefined) delete (globalThis as any).document; + else (globalThis as any).document = originalDocument; + if (originalWindow === undefined) delete (globalThis as any).window; + else (globalThis as any).window = originalWindow; + }; + try { + const result = fn(); + if (result && typeof (result as any).then === "function") { + return (result as Promise).finally(cleanup); + } + cleanup(); + return result; + } catch (e) { + cleanup(); + throw e; + } + } + }; + it("Test A: different browser origin rejects bare scheme-less host targeting other origin", () => { + withBrowserBaseUrl(browserOrigin, () => { const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); // On https://other.example/app/, 'httpbin.org/path' resolves to https://other.example/app/httpbin.org/path // The destination is other.example, NOT httpbin.org, so httpbinValidator must return false. @@ -323,79 +375,39 @@ describe("AllowedHostsValidator", () => { // Conversely, an allowlist matching other.example accepts the resolved destination. const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); expect(otherValidator.isUrlHostValid("httpbin.org/path")).to.be.true; - } finally { - if (originalDocument === undefined) delete (globalThis as any).document; - else (globalThis as any).document = originalDocument; - if (originalWindow === undefined) delete (globalThis as any).window; - else (globalThis as any).window = originalWindow; - } + }); }); it("Test B: explicit absolute URL is approved regardless of browser base URL", () => { - const originalDocument = (globalThis as any).document; - const originalWindow = (globalThis as any).window; - try { - (globalThis as any).document = { baseURI: browserOrigin }; - (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; - + withBrowserBaseUrl(browserOrigin, () => { const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); expect(httpbinValidator.isUrlHostValid("https://httpbin.org/path")).to.be.true; - } finally { - if (originalDocument === undefined) delete (globalThis as any).document; - else (globalThis as any).document = originalDocument; - if (originalWindow === undefined) delete (globalThis as any).window; - else (globalThis as any).window = originalWindow; - } + }); }); it("Test C: protocol-relative URL resolves with browser base protocol and target host", () => { - const originalDocument = (globalThis as any).document; - const originalWindow = (globalThis as any).window; - try { - (globalThis as any).document = { baseURI: browserOrigin }; - (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; - + withBrowserBaseUrl(browserOrigin, () => { const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); // //httpbin.org/path replaces authority with httpbin.org, using https: from browser base expect(httpbinValidator.isUrlHostValid("//httpbin.org/path")).to.be.true; expect(otherValidator.isUrlHostValid("//httpbin.org/path")).to.be.false; - } finally { - if (originalDocument === undefined) delete (globalThis as any).document; - else (globalThis as any).document = originalDocument; - if (originalWindow === undefined) delete (globalThis as any).window; - else (globalThis as any).window = originalWindow; - } + }); }); it("Test D: root-relative URL resolves against browser base origin", () => { - const originalDocument = (globalThis as any).document; - const originalWindow = (globalThis as any).window; - try { - (globalThis as any).document = { baseURI: browserOrigin }; - (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; - + withBrowserBaseUrl(browserOrigin, () => { const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); expect(otherValidator.isUrlHostValid("/api")).to.be.true; expect(httpbinValidator.isUrlHostValid("/api")).to.be.false; - } finally { - if (originalDocument === undefined) delete (globalThis as any).document; - else (globalThis as any).document = originalDocument; - if (originalWindow === undefined) delete (globalThis as any).window; - else (globalThis as any).window = originalWindow; - } + }); }); it("Test E: path-relative URL resolves against browser base URL", () => { - const originalDocument = (globalThis as any).document; - const originalWindow = (globalThis as any).window; - try { - (globalThis as any).document = { baseURI: browserOrigin }; - (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; - + withBrowserBaseUrl(browserOrigin, () => { const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); @@ -408,15 +420,10 @@ describe("AllowedHostsValidator", () => { expect(httpbinValidator.isUrlHostValid("api/users")).to.be.false; expect(httpbinValidator.isUrlHostValid("./api")).to.be.false; expect(httpbinValidator.isUrlHostValid("../api")).to.be.false; - } finally { - if (originalDocument === undefined) delete (globalThis as any).document; - else (globalThis as any).document = originalDocument; - if (originalWindow === undefined) delete (globalThis as any).window; - else (globalThis as any).window = originalWindow; - } + }); }); - it("Test F: existing non-browser bare-host behavior is preserved in Node.js", () => { + it.runIf(utils.inNodeEnv())("Test F: existing non-browser bare-host behavior is preserved in Node.js", () => { const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); const exampleValidator = new AllowedHostsValidator(new Set(["example.com"])); @@ -453,16 +460,16 @@ describe("AllowedHostsValidator", () => { expect(emptyValidator.isUrlHostValid("https:allowed.example/api")).to.be.false; expect(emptyValidator.isUrlHostValid("https:/allowed.example/api")).to.be.false; expect(emptyValidator.isUrlHostValid("http%")).to.be.false; + + // Regression tests for Copilot review finding: + // Literal percent signs in paths and queries are valid and should NOT be rejected + expect(allowedValidator.isUrlHostValid("https://allowed.example/items/100%?q=50%")).to.be.true; + expect(emptyValidator.isUrlHostValid("https://example.com/items/100%?q=50%")).to.be.true; + expect(allowedValidator.isUrlHostValid("https://other.example/items/100%?q=50%")).to.be.false; }); it("Test H: actual fetch destination consistency between authentication and request execution", async () => { - const originalDocument = (globalThis as any).document; - const originalWindow = (globalThis as any).window; - const inNodeSpy = vi.spyOn(utils, "inNodeEnv").mockReturnValue(false); - try { - (globalThis as any).document = { baseURI: browserOrigin }; - (globalThis as any).window = { location: { href: browserOrigin, protocol: "https:", host: "other.example", hostname: "other.example" } }; - + await withBrowserBaseUrl(browserOrigin, async () => { // 1. Provider with allowlist containing ONLY httpbin.org const httpbinProvider = new ApiKeyAuthenticationProvider("secret-api-key", "X-API-KEY", ApiKeyLocation.Header, new Set(["httpbin.org"])); const req1 = new RequestInformation(); @@ -479,19 +486,18 @@ describe("AllowedHostsValidator", () => { expect(actualDestination1.href).to.equal("https://other.example/app/httpbin.org/path"); // 2. Provider with allowlist containing other.example (the actual destination) - const otherProvider = new ApiKeyAuthenticationProvider("secret-api-key", "X-API-KEY", ApiKeyLocation.Header, new Set(["other.example"])); - const req2 = new RequestInformation(); - req2.URL = "httpbin.org/path"; - - await otherProvider.authenticateRequest(req2); + const otherValidator = new AllowedHostsValidator(new Set(["other.example"])); + const httpbinValidator = new AllowedHostsValidator(new Set(["httpbin.org"])); - // Prove: credentials WERE attached because the browser destination is other.example - expect(req2.headers.tryGetValue("X-API-KEY")).to.deep.equal(["secret-api-key"]); + // On https://other.example/app/, the bare-host input resolves to other.example + expect(httpbinValidator.isUrlHostValid("httpbin.org/path")).to.be.false; + expect(otherValidator.isUrlHostValid("httpbin.org/path")).to.be.true; // Verify actual destination matches the validated host - const actualDestination2 = new URL(req2.URL, browserOrigin); + const actualDestination2 = new URL("httpbin.org/path", browserOrigin); expect(actualDestination2.hostname).to.equal("other.example"); - expect(otherProvider["validator"].isUrlHostValid(actualDestination2.href)).to.be.true; + expect(otherValidator.isUrlHostValid(actualDestination2.href)).to.be.true; + expect(httpbinValidator.isUrlHostValid(actualDestination2.href)).to.be.false; // 3. Explicit absolute URL to httpbin.org const req3 = new RequestInformation(); @@ -503,14 +509,8 @@ describe("AllowedHostsValidator", () => { expect(req3.headers.tryGetValue("X-API-KEY")).to.deep.equal(["secret-api-key"]); const actualDestination3 = new URL(req3.URL, browserOrigin); expect(actualDestination3.hostname).to.equal("httpbin.org"); - expect(httpbinProvider["validator"].isUrlHostValid(actualDestination3.href)).to.be.true; - } finally { - inNodeSpy.mockRestore(); - if (originalDocument === undefined) delete (globalThis as any).document; - else (globalThis as any).document = originalDocument; - if (originalWindow === undefined) delete (globalThis as any).window; - else (globalThis as any).window = originalWindow; - } + expect(httpbinValidator.isUrlHostValid(actualDestination3.href)).to.be.true; + }); }); }); }); From d75038f1d4ada82d3501f1e03ceea58f50aae0a0 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Tue, 17 Nov 2026 18:57:33 +0530 Subject: [PATCH 09/10] test(abstractions): add regression tests for percent-encoded components and credential behavior --- .../authentication/allowedHostsValidator.ts | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 64e389625..7a82af246 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -466,6 +466,15 @@ describe("AllowedHostsValidator", () => { expect(allowedValidator.isUrlHostValid("https://allowed.example/items/100%?q=50%")).to.be.true; expect(emptyValidator.isUrlHostValid("https://example.com/items/100%?q=50%")).to.be.true; expect(allowedValidator.isUrlHostValid("https://other.example/items/100%?q=50%")).to.be.false; + + // Valid percent-encoded components in paths and query strings (%20, %2F, %25, %3F, %23) + expect(allowedValidator.isUrlHostValid("https://allowed.example/path/with%20space/and%2Fslash/and%25percent/and%3Fquestion/and%23hash?query=val%201&slash=a%2Fb&pct=100%25&q=a%3Fb&h=a%23b")).to.be.true; + expect(allowedValidator.isUrlHostValid("https://allowed.example/items/100%20test")).to.be.true; + expect(allowedValidator.isUrlHostValid("https://allowed.example/items/100%2Ftest")).to.be.true; + expect(allowedValidator.isUrlHostValid("https://allowed.example/items/100%25test")).to.be.true; + expect(allowedValidator.isUrlHostValid("https://allowed.example/items/100%3Ftest")).to.be.true; + expect(allowedValidator.isUrlHostValid("https://allowed.example/items/100%23test")).to.be.true; + expect(allowedValidator.isUrlHostValid("https://allowed.example/path?space=val%201&slash=a%2Fb&pct=100%25&q=a%3Fb&h=a%23b")).to.be.true; }); it("Test H: actual fetch destination consistency between authentication and request execution", async () => { @@ -510,6 +519,48 @@ describe("AllowedHostsValidator", () => { const actualDestination3 = new URL(req3.URL, browserOrigin); expect(actualDestination3.hostname).to.equal("httpbin.org"); expect(httpbinValidator.isUrlHostValid(actualDestination3.href)).to.be.true; + + // 4. Same-origin browser-relative request with percent-encoded components (%20, %2F, %25, %3F, %23) + expect(otherValidator.isUrlHostValid("api/items/100%25/sub%20item?q=val%201&slash=a%2Fb&pct=50%25&qmark=%3F&hash=%23")).to.be.true; + expect(httpbinValidator.isUrlHostValid("api/items/100%25/sub%20item?q=val%201&slash=a%2Fb&pct=50%25&qmark=%3F&hash=%23")).to.be.false; + + const otherProvider = new ApiKeyAuthenticationProvider("other-api-key", "X-OTHER-KEY", ApiKeyLocation.Header, new Set(["other.example"])); + if (!utils.inNodeEnv()) { + const reqRelative = new RequestInformation(); + reqRelative.URL = "api/items/100%25/sub%20item?q=val%201&slash=a%2Fb&pct=50%25&qmark=%3F&hash=%23"; + await otherProvider.authenticateRequest(reqRelative); + expect(reqRelative.headers.tryGetValue("X-OTHER-KEY")).to.deep.equal(["other-api-key"]); + const actualRelDestination = new URL(reqRelative.URL, browserOrigin); + expect(actualRelDestination.hostname).to.equal("other.example"); + } + + const req4 = new RequestInformation(); + req4.URL = "https://other.example/app/api/items/100%25/sub%20item?q=val%201&slash=a%2Fb&pct=50%25&qmark=%3F&hash=%23"; + + await otherProvider.authenticateRequest(req4); + + // Prove: credentials WERE attached because the resolved host other.example is in the allowlist + expect(req4.headers.tryGetValue("X-OTHER-KEY")).to.deep.equal(["other-api-key"]); + const actualDestination4 = new URL(req4.URL, browserOrigin); + expect(actualDestination4.hostname).to.equal("other.example"); + expect(actualDestination4.href).to.equal("https://other.example/app/api/items/100%25/sub%20item?q=val%201&slash=a%2Fb&pct=50%25&qmark=%3F&hash=%23"); + expect(otherValidator.isUrlHostValid(actualDestination4.href)).to.be.true; + + // 5. Same percent-encoded request with httpbinProvider (unallowlisted resolved host) + const req5 = new RequestInformation(); + req5.URL = "api/items/100%25/sub%20item?q=val%201&slash=a%2Fb&pct=50%25&qmark=%3F&hash=%23"; + await httpbinProvider.authenticateRequest(req5); + // Prove: credentials NOT attached to unallowlisted host even with encoded components + expect(req5.headers.tryGetValue("X-API-KEY")).to.be.null; + + // 6. Explicit allowlisted absolute URL with percent-encoded components receives credentials + const req6 = new RequestInformation(); + req6.URL = "https://httpbin.org/items/100%25/sub%20item?q=val%201&pct=50%25"; + await httpbinProvider.authenticateRequest(req6); + expect(req6.headers.tryGetValue("X-API-KEY")).to.deep.equal(["secret-api-key"]); + const actualDestination6 = new URL(req6.URL, browserOrigin); + expect(actualDestination6.hostname).to.equal("httpbin.org"); + expect(httpbinValidator.isUrlHostValid(actualDestination6.href)).to.be.true; }); }); }); From 52694e3843077a3b6093af2d8b7a59d80f3946a3 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Fri, 20 Nov 2026 23:19:51 +0530 Subject: [PATCH 10/10] test(abstractions): make relative authentication expectation protocol-aware in browser tests --- .../test/common/authentication/allowedHostsValidator.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts index 7a82af246..da55808cf 100644 --- a/packages/abstractions/test/common/authentication/allowedHostsValidator.ts +++ b/packages/abstractions/test/common/authentication/allowedHostsValidator.ts @@ -528,8 +528,13 @@ describe("AllowedHostsValidator", () => { if (!utils.inNodeEnv()) { const reqRelative = new RequestInformation(); reqRelative.URL = "api/items/100%25/sub%20item?q=val%201&slash=a%2Fb&pct=50%25&qmark=%3F&hash=%23"; - await otherProvider.authenticateRequest(reqRelative); - expect(reqRelative.headers.tryGetValue("X-OTHER-KEY")).to.deep.equal(["other-api-key"]); + if (typeof window !== "undefined" && window.location?.protocol?.toLowerCase() === "https:") { + await otherProvider.authenticateRequest(reqRelative); + expect(reqRelative.headers.tryGetValue("X-OTHER-KEY")).to.deep.equal(["other-api-key"]); + } else { + await expect(otherProvider.authenticateRequest(reqRelative)).rejects.toThrow("Authentication scheme can only be used with https requests"); + expect(reqRelative.headers.tryGetValue("X-OTHER-KEY")).to.be.null; + } const actualRelDestination = new URL(reqRelative.URL, browserOrigin); expect(actualRelDestination.hostname).to.equal("other.example"); }