From 163a9d8dbd8ddce6335a962d112db3fd0fd5d734 Mon Sep 17 00:00:00 2001 From: Aleksandr Borovskii Date: Wed, 23 Sep 2026 16:01:21 +0200 Subject: [PATCH 1/7] fix(repeater): answer undeliverable request payloads instead of dropping the ack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the bridge sends a request event whose payload cannot be constructed into a Request, the throw previously escaped the event listener unanswered, so the bridge burned its full timeout and reported a malformed URL as repeater unavailability, flooding Sentry with Invalid URL. errors. requestReceived now wraps only the construction step and, on failure, acks the bridge with a { protocol, protocolError: { code, message } } variant — distinct from an execution failure, which keeps its existing { message, errorCode } reply. The rejection is a logger.error, not a captureException, so these stop being Sentry events. The command hub is not invoked for a payload that could not be constructed. --- src/Repeater/RepeaterServer.ts | 10 + src/Repeater/ServerRepeaterLauncher.spec.ts | 195 ++++++++++++++++++++ src/Repeater/ServerRepeaterLauncher.ts | 24 ++- 3 files changed, 226 insertions(+), 3 deletions(-) create mode 100644 src/Repeater/ServerRepeaterLauncher.spec.ts diff --git a/src/Repeater/RepeaterServer.ts b/src/Repeater/RepeaterServer.ts index e8370952..11736e0e 100644 --- a/src/Repeater/RepeaterServer.ts +++ b/src/Repeater/RepeaterServer.ts @@ -50,6 +50,16 @@ export type RepeaterServerRequestResponse = protocol: Protocol; message?: string; errorCode?: string; + } + | { + // The request event payload could not be dispatched because it was + // malformed (the Request could not be constructed). This is distinct from + // an execution failure — which uses the { message, errorCode } variant + // produced by HttpRequestExecutor.execute's catch — and lets the bridge + // classify it as a bridge<->repeater contract failure rather than a target + // outage. + protocol: Protocol; + protocolError: { code: string; message: string }; }; export interface RepeaterServerReconnectionFailedEvent { diff --git a/src/Repeater/ServerRepeaterLauncher.spec.ts b/src/Repeater/ServerRepeaterLauncher.spec.ts new file mode 100644 index 00000000..e585fcd2 --- /dev/null +++ b/src/Repeater/ServerRepeaterLauncher.spec.ts @@ -0,0 +1,195 @@ +import 'reflect-metadata'; +import { ServerRepeaterLauncher } from './ServerRepeaterLauncher'; +import { + RepeaterServer, + RepeaterServerEvents, + RepeaterServerEventHandler, + RepeaterServerRequestEvent, + RepeaterServerRequestResponse +} from './RepeaterServer'; +import { RepeaterCommandHub } from './RepeaterCommandHub'; +import { RuntimeDetector } from './RuntimeDetector'; +import { StartupManager } from '../StartupScripts'; +import { ScriptLoader, VirtualScripts } from '../Scripts'; +import { + Certificates, + Protocol, + RequestExecutorOptions, + Response +} from '../RequestExecutor'; +import { CliInfo } from '../Config'; +import { logger } from '../Utils'; +import { anything, instance, mock, reset, verify, when } from 'ts-mockito'; +import { captureException } from '@sentry/node'; + +jest.mock('@sentry/node', () => ({ + captureException: jest.fn(), + setTag: jest.fn() +})); + +describe('ServerRepeaterLauncher', () => { + const runtimeDetectorMock = mock(); + const virtualScriptsMock = mock(); + const startupManagerMock = mock(); + const commandHubMock = mock(); + const certificatesMock = mock(); + const scriptLoaderMock = mock(); + const requestExecutorOptionsMock = mock(); + const cliInfoMock = mock(); + + // A fake RepeaterServer that records the handlers subscribeToEvents registers, + // so the captured REQUEST handler can be driven directly. + const handlers = new Map>(); + const repeaterServer: RepeaterServer = { + disconnect: (): void => undefined, + connect: (): Promise => Promise.resolve(), + deploy: (): Promise => Promise.resolve() as never, + on: (event, handler): void => { + handlers.set(event, handler as RepeaterServerEventHandler); + }, + off: (): void => undefined + }; + + let sut: ServerRepeaterLauncher; + let loggerErrorSpy: jest.SpyInstance; + + const requestHandler = (): (( + event: RepeaterServerRequestEvent + ) => Promise) => + handlers.get(RepeaterServerEvents.REQUEST) as unknown as ( + event: RepeaterServerRequestEvent + ) => Promise; + + beforeEach(async () => { + handlers.clear(); + (captureException as jest.Mock).mockClear(); + loggerErrorSpy = jest.spyOn(logger, 'error').mockImplementation(() => 0); + + when(cliInfoMock.version).thenReturn('0.0.0-test'); + when(virtualScriptsMock.size).thenReturn(0); + when(virtualScriptsMock.count(anything())).thenReturn(0); + + sut = new ServerRepeaterLauncher( + instance(runtimeDetectorMock), + instance(virtualScriptsMock), + repeaterServer, + instance(startupManagerMock), + instance(commandHubMock), + instance(certificatesMock), + instance(scriptLoaderMock), + instance(requestExecutorOptionsMock), + instance(cliInfoMock) + ); + + // run() wires subscribeToEvents, registering the REQUEST handler. + await sut.run('repeater-1'); + }); + + afterEach(() => { + loggerErrorSpy.mockRestore(); + reset(commandHubMock); + }); + + describe('run', () => { + const okResponse = (): Response => + ({ + protocol: Protocol.HTTP, + statusCode: 200, + headers: { 'content-type': 'text/plain' }, + body: 'ok' + } as unknown as Response); + + it('should ack with a protocol error when the request payload cannot be constructed', async () => { + // arrange — a URL the Request constructor rejects. + const event: RepeaterServerRequestEvent = { + protocol: Protocol.HTTP, + url: 'http://host:notaport/' + }; + + // act + const response = await requestHandler()(event); + + // assert + expect(response).toEqual({ + protocol: Protocol.HTTP, + protocolError: { + code: 'ERR_MALFORMED_REQUEST', + message: 'Invalid URL.' + } + }); + }); + + it('should not invoke the command hub when the request payload cannot be constructed', async () => { + // arrange + const event: RepeaterServerRequestEvent = { + protocol: Protocol.HTTP, + url: 'http://host:notaport/' + }; + + // act + await requestHandler()(event); + + // assert + verify(commandHubMock.sendRequest(anything())).never(); + }); + + it('should ack with message and errorCode when execution itself fails', async () => { + // arrange — a constructible request whose execution fails is a distinct + // error class from a malformed payload. + when(commandHubMock.sendRequest(anything())).thenResolve({ + protocol: Protocol.HTTP, + message: 'Connection refused', + errorCode: 'ECONNREFUSED' + } as unknown as Response); + const event: RepeaterServerRequestEvent = { + protocol: Protocol.HTTP, + url: 'http://valid.test/' + }; + + // act + const response = await requestHandler()(event); + + // assert + expect(response).toMatchObject({ + protocol: Protocol.HTTP, + message: 'Connection refused', + errorCode: 'ECONNREFUSED' + }); + expect('protocolError' in response).toBe(false); + }); + + it('should ack with the response fields on a successful request', async () => { + // arrange + when(commandHubMock.sendRequest(anything())).thenResolve(okResponse()); + const event: RepeaterServerRequestEvent = { + protocol: Protocol.HTTP, + url: 'http://valid.test/' + }; + + // act + const response = await requestHandler()(event); + + // assert + expect(response).toMatchObject({ + protocol: Protocol.HTTP, + statusCode: 200, + body: 'ok' + }); + }); + + it('should not report a rejected payload to Sentry', async () => { + // arrange + const event: RepeaterServerRequestEvent = { + protocol: Protocol.HTTP, + url: 'http://host:notaport/' + }; + + // act + await requestHandler()(event); + + // assert — a rejected payload is a logger.error, never a Sentry event. + expect(captureException).not.toHaveBeenCalled(); + expect(loggerErrorSpy).toHaveBeenCalled(); + }); + }); +}); diff --git a/src/Repeater/ServerRepeaterLauncher.ts b/src/Repeater/ServerRepeaterLauncher.ts index a72d6757..e3270889 100644 --- a/src/Repeater/ServerRepeaterLauncher.ts +++ b/src/Repeater/ServerRepeaterLauncher.ts @@ -245,9 +245,27 @@ export class ServerRepeaterLauncher implements RepeaterLauncher { private requestReceived = async ( event: RepeaterServerRequestEvent ): Promise => { - const response = await this.commandHub.sendRequest( - new Request({ ...event }) - ); + let request: Request; + + try { + request = new Request({ ...event }); + } catch (e) { + const reason = e instanceof Error ? e.message : String(e); + // A malformed request payload the bridge sent that we cannot dispatch. + // Answer the ack with a protocol error so the bridge can classify it as a + // bridge<->repeater contract failure — distinct from an execution failure, + // which returns the { message, errorCode } variant below. logger.error + // only, NOT captureException: the whole point of this fix is that these + // stop being Sentry events. + logger.error('Rejecting a malformed request from the bridge: %s', reason); + + return { + protocol: event.protocol, + protocolError: { code: 'ERR_MALFORMED_REQUEST', message: reason } + }; + } + + const response = await this.commandHub.sendRequest(request); const { statusCode, From 9229d587dfbf7b210d29580011de9701af354dd2 Mon Sep 17 00:00:00 2001 From: Aleksandr Borovskii Date: Wed, 23 Sep 2026 18:17:08 +0200 Subject: [PATCH 2/7] refactor(repeater): one non-throwing URL decomposition for the execute path Replace the two disagreeing URL parsers on the request-execute path with a single string-only TargetUrl decomposition that never throws: - transformScript and handleResponseScript no longer call new URL(), which used to throw on an authority defect and short-circuit an otherwise deliverable request into ERR_INVALID_URL before libcurl ever saw it. - configureCurl, resolveProxy and shouldApplyKerberos drop the legacy node:url parse(); all five consumers now share TargetUrl and agree on one behaviour for an unparseable authority (undefined hostname => skip virtual script, response script, proxy and Kerberos). - Hostnames are raw-lowercased with no IDNA/punycode (behaviour change for internationalised domains in virtual-script and proxy-domain matching). - The raw path is preserved byte-for-byte (PATH_AS_IS), carried over from the former buildRawPath. --- src/RequestExecutor/HttpRequestExecutor.ts | 62 +++---- src/RequestExecutor/TargetUrl.spec.ts | 142 ++++++++++++++++ src/RequestExecutor/TargetUrl.ts | 179 +++++++++++++++++++++ src/RequestExecutor/index.ts | 1 + 4 files changed, 356 insertions(+), 28 deletions(-) create mode 100644 src/RequestExecutor/TargetUrl.spec.ts create mode 100644 src/RequestExecutor/TargetUrl.ts diff --git a/src/RequestExecutor/HttpRequestExecutor.ts b/src/RequestExecutor/HttpRequestExecutor.ts index 7602679d..ce0f83b3 100644 --- a/src/RequestExecutor/HttpRequestExecutor.ts +++ b/src/RequestExecutor/HttpRequestExecutor.ts @@ -9,6 +9,7 @@ import { CertificatesCache } from './CertificatesCache'; import { CertificatesResolver } from './CertificatesResolver'; import { CurlSeekResult } from './CurlSeekResult'; import { CurlSeekOrigin } from './CurlSeekOrigin'; +import { TargetUrl } from './TargetUrl'; import { inject, injectable } from 'tsyringe'; import iconv from 'iconv-lite'; import { safeParse } from 'fast-content-type-parse'; @@ -20,7 +21,6 @@ import { HeaderInfo, Multi } from '@brightsec/node-libcurl'; -import { parse as parseUrl } from 'node:url'; type ScriptEntrypoint = ( options: RequestOptions @@ -171,15 +171,14 @@ export class HttpRequestExecutor implements RequestExecutor { private configureCurl(curl: Curl, options: Request): void { curl.enable(CurlFeature.NoDataParsing); - const { protocol, host, auth } = parseUrl(options.url); - curl.setOpt('URL', `${protocol}//${host}`); + const parts = TargetUrl.parse(options.url); + curl.setOpt('URL', `${parts.scheme ?? ''}//${parts.host ?? ''}`); - if (auth) { - curl.setOpt('USERPWD', auth); + if (parts.userinfo) { + curl.setOpt('USERPWD', parts.userinfo); } - const rawPath = this.buildRawPath(options.url); - curl.setOpt('REQUEST_TARGET', rawPath); + curl.setOpt('REQUEST_TARGET', parts.path); // Prevent libcurl from normalising (percent-encoding) the path. curl.setOpt('PATH_AS_IS', true); curl.setOpt('SSL_VERIFYPEER', false); @@ -212,23 +211,6 @@ export class HttpRequestExecutor implements RequestExecutor { curl.setOpt('CUSTOMREQUEST', options.method); } - /** - * Extracts the raw path+query+hash from a URL string without any - * percent-encoding normalisation. - */ - private buildRawPath(url: string): string { - const separatorIndex = url.indexOf('://'); - const withoutProtocol = - separatorIndex === -1 ? url : url.slice(separatorIndex + 3); - const pathStart = withoutProtocol.search(/[/?#]/); - - if (pathStart === -1) return '/'; - - return withoutProtocol[pathStart] === '/' - ? withoutProtocol.slice(pathStart) - : `/${withoutProtocol.slice(pathStart)}`; - } - private applyCurlBody(curl: Curl, options: Request): void { if (!options.body) return; @@ -392,7 +374,14 @@ export class HttpRequestExecutor implements RequestExecutor { } private resolveProxy(options: Request): string | undefined { - const hostname = parseUrl(options.url).hostname; + const { hostname } = TargetUrl.parse(options.url); + + // No resolvable authority (D4): make no proxy decision keyed on a host that + // does not exist, rather than coercing undefined into the string 'null' + // inside RegExp.test. + if (hostname === undefined) { + return this.options.proxyUrl; + } if ( this.proxyDomains && @@ -424,7 +413,12 @@ export class HttpRequestExecutor implements RequestExecutor { return true; } - const hostname = parseUrl(options.url).hostname; + const { hostname } = TargetUrl.parse(options.url); + + // No resolvable authority (D4): no host to match a Kerberos domain against. + if (hostname === undefined) { + return false; + } return this.kerberosDomains.some((domain) => domain.test(hostname)); } @@ -551,7 +545,14 @@ export class HttpRequestExecutor implements RequestExecutor { } private async transformScript(script: Request): Promise { - const { hostname } = new URL(script.url); + const { hostname } = TargetUrl.parse(script.url); + + // No resolvable authority (D4): no host to match a virtual script against, + // and — crucially — no throwing `new URL()` to short-circuit an otherwise + // deliverable request before it reaches libcurl (Finding A). + if (hostname === undefined) { + return script; + } const vm = this.virtualScripts.find(hostname); @@ -594,7 +595,12 @@ export class HttpRequestExecutor implements RequestExecutor { request: Request, response: Response ): Promise { - const { hostname } = new URL(request.url); + const { hostname } = TargetUrl.parse(request.url); + + // No resolvable authority (D4): no host to match a response script against. + if (hostname === undefined) { + return response; + } const vm = this.virtualScripts.find(hostname); diff --git a/src/RequestExecutor/TargetUrl.spec.ts b/src/RequestExecutor/TargetUrl.spec.ts new file mode 100644 index 00000000..56c2552b --- /dev/null +++ b/src/RequestExecutor/TargetUrl.spec.ts @@ -0,0 +1,142 @@ +import { TargetUrl } from './TargetUrl'; + +describe('TargetUrl', () => { + describe('parse', () => { + describe('well-formed URLs', () => { + it('should decompose scheme, host, hostname, userinfo and path', () => { + const parts = TargetUrl.parse( + 'http://user:pass@example.com:8080/a/b?q=1#f' + ); + + expect(parts).toEqual({ + scheme: 'http:', + host: 'example.com:8080', + hostname: 'example.com', + userinfo: 'user:pass', + path: '/a/b?q=1#f' + }); + }); + + it('should lowercase the hostname but leave the path casing untouched', () => { + const parts = TargetUrl.parse('https://EXAMPLE.com/Path'); + + expect(parts.hostname).toBe('example.com'); + expect(parts.host).toBe('EXAMPLE.com'); + expect(parts.path).toBe('/Path'); + }); + + it('should default the path to "/" when the URL has none', () => { + const parts = TargetUrl.parse('http://example.com'); + + expect(parts.host).toBe('example.com'); + expect(parts.path).toBe('/'); + }); + + it('should NOT apply IDNA/punycode to an internationalised hostname (D3)', () => { + const parts = TargetUrl.parse('http://☃.net/x'); + + // Intentional behaviour change vs the old WHATWG path, which would have + // produced xn--n3h.net. + expect(parts.hostname).toBe('☃.net'); + }); + + it('should strip brackets from a bracketed IPv6 host and keep the port on host', () => { + const parts = TargetUrl.parse('http://[::1]:8080/x'); + + expect(parts.host).toBe('[::1]:8080'); + expect(parts.hostname).toBe('::1'); + expect(parts.path).toBe('/x'); + }); + + it('should preserve an underscore host verbatim', () => { + const parts = TargetUrl.parse('http://under_score/y'); + + expect(parts.hostname).toBe('under_score'); + }); + }); + + describe('authority defects (must not throw, hostname best-effort)', () => { + // The six authority defects the WHATWG parser rejected. TargetUrl.parse + // must decompose each without throwing so the request still reaches + // libcurl (Finding A). See HttpRequestExecutor.spec for the libcurl codes. + const cases: [name: string, url: string][] = [ + ['non-numeric port', 'http://host:notaport/'], + ['port > 65535', 'http://host:99999/'], + ['unbracketed IPv6', 'http://::1/'], + ['space in host', 'http://ho st/'], + ['[not-ipv6]', 'http://[not-ipv6]/'], + ['empty string', ''] + ]; + + it.each(cases)('should not throw for %s', (_name, url) => { + expect(() => TargetUrl.parse(url)).not.toThrow(); + }); + + it('should still expose the scheme for an unbracketed IPv6 authority', () => { + expect(TargetUrl.parse('http://::1/').scheme).toBe('http:'); + }); + + it('should yield hostname undefined for an empty string', () => { + expect(TargetUrl.parse('').hostname).toBeUndefined(); + }); + }); + + describe('path/encoding malformations (must survive byte-for-byte)', () => { + // The 19 scanner-controlled path malformations that must pass through + // untouched — no percent-encoding normalisation — because libcurl is + // driven with PATH_AS_IS. + const cases: [name: string, url: string, expected: string][] = [ + ['space in path', 'http://h/path with spaces', '/path with spaces'], + ['raw tab', 'http://h/a\tb', '/a\tb'], + ['raw newline', 'http://h/a\nb', '/a\nb'], + ['raw non-ascii latin1', 'http://h/caf\u00e9', '/caf\u00e9'], + ['bad percent %zz', 'http://h/%zz', '/%zz'], + ['lone percent', 'http://h/%', '/%'], + ['double percent', 'http://h/%%', '/%%'], + ['backslash', 'http://h/a\\b', '/a\\b'], + ['fragment', 'http://h/p#frag', '/p#frag'], + ['asterisk path', 'http://h/*', '/*'], + ['query only', 'http://h?q=1', '/?q=1'], + ['encoded slash', 'http://h/a%2fb', '/a%2fb'], + ['double slash path', 'http://h//a//b', '//a//b'], + ['semicolon params', 'http://h/a;b=c', '/a;b=c'], + ['plus in query', 'http://h/a?x=1+2', '/a?x=1+2'], + ['at in path', 'http://h/a@b', '/a@b'], + ['colon in path', 'http://h/a:b', '/a:b'], + ['unicode in query', 'http://h/a?q=\u2603', '/a?q=\u2603'], + ['trailing dotdot', 'http://h/a/../b', '/a/../b'] + ]; + + it.each(cases)( + 'should preserve the raw path for %s', + (_name, url, expected) => { + expect(TargetUrl.parse(url).path).toBe(expected); + } + ); + }); + }); + + describe('redact', () => { + it('should replace userinfo with *** while preserving the rest', () => { + expect(TargetUrl.redact('http://user:pass@host:8080/p?q=1')).toBe( + 'http://***@host:8080/p?q=1' + ); + }); + + it('should redact userinfo with no password', () => { + expect(TargetUrl.redact('http://user@host/p')).toBe('http://***@host/p'); + }); + + it('should leave a URL without userinfo unchanged', () => { + expect(TargetUrl.redact('http://host/p')).toBe('http://host/p'); + }); + + it('should leave an origin-form value unchanged', () => { + expect(TargetUrl.redact('/p?q=1')).toBe('/p?q=1'); + }); + + it('should not treat an @ in the path as userinfo', () => { + expect(TargetUrl.redact('http://host/a@b')).toBe('http://host/a@b'); + }); + }); +}); diff --git a/src/RequestExecutor/TargetUrl.ts b/src/RequestExecutor/TargetUrl.ts new file mode 100644 index 00000000..40ad5463 --- /dev/null +++ b/src/RequestExecutor/TargetUrl.ts @@ -0,0 +1,179 @@ +/** + * A non-throwing, string-only decomposition of a target URL, shared by every + * consumer on the request-execute path. + * + * Motivation: the previous code split URL handling across two parsers — the + * WHATWG `new URL()` (in the virtual-script and response-script lookups) and the + * legacy `node:url` `parse()` (in curl configuration, proxy resolution, and + * Kerberos gating). The two disagree on normalisation (IDNA, casing, port + * handling), and `new URL()` THROWS on an authority defect, short-circuiting an + * otherwise-deliverable scanner request into an `ERR_INVALID_URL` before it ever + * reaches libcurl. This class replaces both with one decomposition that never + * throws, so a malformed-authority URL travels all the way to libcurl and is + * answered with libcurl's own returned error code (e.g. `CURLE_URL_MALFORMAT`) + * rather than being rejected client-side. + * + * Design decisions: + * - **D3 — hostname normalisation.** {@link TargetUrlParts.hostname} is + * raw-lowercased with NO IDNA/punycode conversion. This differs from the old + * WHATWG path for internationalised domains: `☃.net` stays `☃.net` (lowercased) + * instead of becoming `xn--n3h.net`. Virtual-script and proxy-domain matching + * therefore key on the raw hostname. Intentional; documented behaviour change. + * - **D4 — unparseable authority means "skip".** When the URL has no authority, + * {@link TargetUrlParts.hostname} is `undefined`; consumers treat that as "no + * virtual script, no response script, no proxy, no Kerberos" rather than + * coercing a `null`/`undefined` hostname into the string `"null"` inside a + * `RegExp.test(...)`. + * + * The parser performs only string slicing — no `new URL`, no `node:url` `parse`. + * The {@link TargetUrlParts.path} field preserves the raw path+query+hash with + * no percent-encoding normalisation, because libcurl is driven with + * `PATH_AS_IS` and every scanner-controlled path malformation must survive + * byte-for-byte. + */ +export interface TargetUrlParts { + /** Scheme WITH its trailing colon, e.g. `'http:'`; `undefined` when absent. */ + readonly scheme?: string; + /** `hostname[:port]` as `configureCurl` needs it; `undefined` when absent. */ + readonly host?: string; + /** + * Lowercased hostname with no port, no IPv6 brackets, and no IDNA/punycode + * normalisation (decision D3); `undefined` when no authority is present (D4). + */ + readonly hostname?: string; + /** `user:pass` userinfo for libcurl `USERPWD`; `undefined` when absent. */ + readonly userinfo?: string; + /** Raw path+query+hash, never normalised. Defaults to `'/'`. */ + readonly path: string; +} + +export class TargetUrl { + private static readonly SCHEME_SEPARATOR = '://'; + + /** + * Decompose a URL string. Never throws. An unparseable authority yields + * `hostname === undefined` (and `host`/`scheme`/`userinfo` as available). + */ + public static parse(url: string): TargetUrlParts { + const path = TargetUrl.extractPath(url); + + const separatorIndex = url.indexOf(TargetUrl.SCHEME_SEPARATOR); + + // Origin-form (no scheme://): there is no authority to decompose. Only the + // path is meaningful; hostname stays undefined so consumers skip host-keyed + // behaviour (D4). + if (separatorIndex === -1) { + return { path }; + } + + const scheme = url.slice(0, separatorIndex + 1); // include trailing ':' + const afterScheme = url.slice( + separatorIndex + TargetUrl.SCHEME_SEPARATOR.length + ); + + // The authority ends at the first path/query/hash delimiter. + const authorityEnd = afterScheme.search(/[/?#]/); + const authority = + authorityEnd === -1 ? afterScheme : afterScheme.slice(0, authorityEnd); + + return TargetUrl.decomposeAuthority(scheme, authority, path); + } + + /** + * Replace the userinfo component of a URL with `***`, so a rejection message + * can quote the offending value without leaking credentials + * (`http://user:pass@host/` → `http://***@host/`). Never throws; when there is + * no userinfo the input is returned unchanged. + */ + public static redact(url: string): string { + const separatorIndex = url.indexOf(TargetUrl.SCHEME_SEPARATOR); + + if (separatorIndex === -1) { + return url; + } + + const afterSchemeStart = separatorIndex + TargetUrl.SCHEME_SEPARATOR.length; + const afterScheme = url.slice(afterSchemeStart); + + const authorityEnd = afterScheme.search(/[/?#]/); + const authority = + authorityEnd === -1 ? afterScheme : afterScheme.slice(0, authorityEnd); + + const atIndex = authority.lastIndexOf('@'); + + if (atIndex === -1) { + return url; + } + + const rest = authorityEnd === -1 ? '' : afterScheme.slice(authorityEnd); + + return `${url.slice(0, afterSchemeStart)}***@${authority.slice( + atIndex + 1 + )}${rest}`; + } + + private static decomposeAuthority( + scheme: string, + authority: string, + path: string + ): TargetUrlParts { + if (!authority) { + return { scheme, path }; + } + + const atIndex = authority.lastIndexOf('@'); + const userinfo = + atIndex === -1 ? undefined : authority.slice(0, atIndex) || undefined; + const host = atIndex === -1 ? authority : authority.slice(atIndex + 1); + + return { + scheme, + path, + ...(userinfo !== undefined ? { userinfo } : {}), + ...(host ? { host } : {}), + ...(host ? { hostname: TargetUrl.extractHostname(host) } : {}) + }; + } + + /** + * Strip the port and IPv6 brackets from a `host` and lowercase it, with no + * IDNA/punycode conversion (D3). + */ + private static extractHostname(host: string): string { + // Bracketed IPv6 literal: `[::1]` or `[::1]:8080`. + if (host.startsWith('[')) { + const closing = host.indexOf(']'); + + if (closing !== -1) { + return host.slice(1, closing).toLowerCase(); + } + } + + const colonIndex = host.indexOf(':'); + const withoutPort = colonIndex === -1 ? host : host.slice(0, colonIndex); + + return withoutPort.toLowerCase(); + } + + /** + * Extract the raw path+query+hash from a URL string without any + * percent-encoding normalisation. Preserved verbatim from the previous + * `HttpRequestExecutor.buildRawPath` so `PATH_AS_IS` behaviour is unchanged. + */ + private static extractPath(url: string): string { + const separatorIndex = url.indexOf(TargetUrl.SCHEME_SEPARATOR); + const withoutProtocol = + separatorIndex === -1 + ? url + : url.slice(separatorIndex + TargetUrl.SCHEME_SEPARATOR.length); + const pathStart = withoutProtocol.search(/[/?#]/); + + if (pathStart === -1) { + return '/'; + } + + return withoutProtocol[pathStart] === '/' + ? withoutProtocol.slice(pathStart) + : `/${withoutProtocol.slice(pathStart)}`; + } +} diff --git a/src/RequestExecutor/index.ts b/src/RequestExecutor/index.ts index 9078d41f..76a37346 100644 --- a/src/RequestExecutor/index.ts +++ b/src/RequestExecutor/index.ts @@ -4,6 +4,7 @@ export * from './HttpRequestExecutor'; export * from './WsRequestExecutor'; export * from './Response'; export * from './Request'; +export * from './TargetUrl'; export * from './Protocol'; export * from './Certificates'; export * from './CertificatesLoader'; From ef26c38686e15af71b38cbed7855d903c57b7417 Mon Sep 17 00:00:00 2001 From: Aleksandr Borovskii Date: Wed, 23 Sep 2026 18:17:20 +0200 Subject: [PATCH 3/7] test(repeater): pin the libcurl malformed-URL contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Probe the six authority defects the WHATWG parser used to reject. Each now travels through TargetUrl to libcurl and is answered with a returned Response carrying libcurl's CURLE_URL_MALFORMAT failure — never a throw, never a hang, and never the client-side ERR_INVALID_URL short-circuit. This pins the observed behaviour on the supported Node runtime (engines: >=22 <=24) as a regression guard for the predicate relaxation. --- .../HttpRequestExecutor.spec.ts | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/src/RequestExecutor/HttpRequestExecutor.spec.ts b/src/RequestExecutor/HttpRequestExecutor.spec.ts index 97c1366d..a3366e1c 100644 --- a/src/RequestExecutor/HttpRequestExecutor.spec.ts +++ b/src/RequestExecutor/HttpRequestExecutor.spec.ts @@ -1949,4 +1949,78 @@ describe('HttpRequestExecutor', () => { expect(connectionCount).toBe(2); }); }); + + // Probe: prove a malformed-authority URL now travels all the way to libcurl + // and is answered with libcurl's own returned failure, rather than being + // short-circuited client-side (Finding A) or hanging/throwing something the + // execute catch maps to undefined. Run on the supported Node runtime + // (package.json engines: >=22 <=24), NOT Node 26. + describe('execute', () => { + // Build a Request carrying a malformed authority WITHOUT tripping the + // constructor predicate (Task 9 relaxes it separately): construct with a + // valid placeholder, then redefine the readonly url. + const malformedRequest = (url: string): Request => { + const request = new Request({ + url: 'http://placeholder.invalid/', + protocol: Protocol.HTTP + }); + Object.defineProperty(request, 'url', { value: url, writable: false }); + + return request; + }; + + // Concrete libcurl outcome observed on Node 24 for each authority defect, + // via the string decomposition TargetUrl feeds curl. libcurl rejects the + // rebuilt authority as CURLE_URL_MALFORMAT and node-libcurl surfaces it as a + // returned Error whose message is the text below; execute's catch derives + // errorCode = code ?? syscall ?? name, which for this Error is the name + // ('Error') — the load-bearing fact for the AC is that it is a DEFINED, + // returned value, never a hang and never the ERR_INVALID_URL short-circuit + // the throwing new URL() used to produce. + const CURL_MALFORMAT_MESSAGE = + 'Request failed: URL using bad/illegal format or missing URL'; + + const cases: [name: string, url: string][] = [ + ['non-numeric port', 'http://host.invalid:notaport/'], + ['port > 65535', 'http://host.invalid:99999/'], + ['unbracketed IPv6', 'http://::1/'], + ['space in host', 'http://ho st.invalid/'], + ['[not-ipv6]', 'http://[not-ipv6]/'], + ['empty string', ''] + ]; + + it.each(cases)( + 'should reach libcurl and return a defined error for %s (not ERR_INVALID_URL, no throw/hang)', + async (_name, url) => { + // arrange — an explicit per-test timeout keeps a would-be hang well + // under the jest default so a regression fails loudly, not by stalling. + const sut = buildSut(); + const request = malformedRequest(url); + + // act — must resolve (never reject/throw). + const response = await sut.execute(request); + + // assert — a returned Response carrying libcurl's malformat failure, + // never the client-side ERR_INVALID_URL short-circuit. + expect(response.errorCode).toBeDefined(); + expect(response.errorCode).not.toBe('ERR_INVALID_URL'); + expect(response.message).toBe(CURL_MALFORMAT_MESSAGE); + }, + 10_000 + ); + + it('should short-circuit an empty authority without reaching a virtual script', async () => { + // arrange — an origin-form target has no hostname (D4); no virtual script + // lookup is attempted and execution still returns a Response. + const sut = buildSut(); + const request = malformedRequest('/origin-form-only'); + + // act + const response = await sut.execute(request); + + // assert + expect(response).toBeDefined(); + verify(virtualScriptsMock.find(anything())).never(); + }); + }); }); From a7e8b221021cc5a6ce3b4e61515c63623e79ddaa Mon Sep 17 00:00:00 2001 From: Aleksandr Borovskii Date: Wed, 23 Sep 2026 18:20:57 +0200 Subject: [PATCH 4/7] fix(repeater): relax the URL predicate to match the bridge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop the WHATWG new URL() gate from Request. bright-cli and the bridge now agree on which URLs are deliverable: any non-blank (after trim) URL is accepted and travels to libcurl, so no shape the bridge dispatches is fatal in the CLI constructor. The one surviving rejection — a blank URL — carries the offending value through a userinfo-redacting formatter so credentials never reach logs or Sentry. Also update the malformed-payload launcher tests to use a blank URL, the only shape that still fails construction after this relaxation. --- src/Repeater/ServerRepeaterLauncher.spec.ts | 11 ++-- src/RequestExecutor/Request.spec.ts | 72 +++++++++++++++++++++ src/RequestExecutor/Request.ts | 9 ++- 3 files changed, 82 insertions(+), 10 deletions(-) diff --git a/src/Repeater/ServerRepeaterLauncher.spec.ts b/src/Repeater/ServerRepeaterLauncher.spec.ts index e585fcd2..a3be8be5 100644 --- a/src/Repeater/ServerRepeaterLauncher.spec.ts +++ b/src/Repeater/ServerRepeaterLauncher.spec.ts @@ -100,10 +100,11 @@ describe('ServerRepeaterLauncher', () => { } as unknown as Response); it('should ack with a protocol error when the request payload cannot be constructed', async () => { - // arrange — a URL the Request constructor rejects. + // arrange — a URL the Request constructor still rejects post-relaxation + // (blank after trim). const event: RepeaterServerRequestEvent = { protocol: Protocol.HTTP, - url: 'http://host:notaport/' + url: '' }; // act @@ -114,7 +115,7 @@ describe('ServerRepeaterLauncher', () => { protocol: Protocol.HTTP, protocolError: { code: 'ERR_MALFORMED_REQUEST', - message: 'Invalid URL.' + message: 'Invalid URL: ' } }); }); @@ -123,7 +124,7 @@ describe('ServerRepeaterLauncher', () => { // arrange const event: RepeaterServerRequestEvent = { protocol: Protocol.HTTP, - url: 'http://host:notaport/' + url: '' }; // act @@ -181,7 +182,7 @@ describe('ServerRepeaterLauncher', () => { // arrange const event: RepeaterServerRequestEvent = { protocol: Protocol.HTTP, - url: 'http://host:notaport/' + url: '' }; // act diff --git a/src/RequestExecutor/Request.spec.ts b/src/RequestExecutor/Request.spec.ts index 9f013bdb..4d7c3a78 100644 --- a/src/RequestExecutor/Request.spec.ts +++ b/src/RequestExecutor/Request.spec.ts @@ -78,4 +78,76 @@ describe('Request', () => { }); }); }); + + describe('constructor', () => { + // The six authority shapes the WHATWG parser (old new URL() predicate) + // rejected. bridges accepts them and dispatches them, so the CLI must too — + // they now construct successfully and are answered by libcurl downstream. + const previouslyRejected = [ + 'http://host:notaport/', + 'http://host:99999/', + 'http://::1/', + 'http://ho st/', + 'http://[not-ipv6]/', + 'http://user@host name/' + ]; + + it.each(previouslyRejected)( + 'should accept the previously-rejected authority shape %s', + (url) => { + expect( + () => new Request({ url, protocol: Protocol.HTTP }) + ).not.toThrow(); + } + ); + + it('should trim and store the url', () => { + const request = new Request({ + url: ' http://foo.bar/x ', + protocol: Protocol.HTTP + }); + + expect(request.url).toBe('http://foo.bar/x'); + }); + + it('should still reject an empty url', () => { + expect(() => new Request({ url: '', protocol: Protocol.HTTP })).toThrow( + /Invalid URL/ + ); + }); + + it('should still reject a whitespace-only url', () => { + expect( + () => new Request({ url: ' ', protocol: Protocol.HTTP }) + ).toThrow(/Invalid URL/); + }); + + it('should carry the offending value on the rejection message', () => { + // A blank url is the only surviving rejection; its (empty) value is named. + expect(() => new Request({ url: '', protocol: Protocol.HTTP })).toThrow( + 'Invalid URL: ' + ); + }); + + it('should build the rejection message through the userinfo-redacting formatter', () => { + // The only surviving rejection is a blank-after-trim url, so the offending + // value is empty here; the credential-redaction guarantee itself is proven + // in TargetUrl.spec (redact). This pins that the message is produced via + // that redacting formatter rather than interpolating a raw url, so a + // future non-blank rejection could never leak userinfo to Sentry. + expect(() => new Request({ url: '', protocol: Protocol.HTTP })).toThrow( + 'Invalid URL: ' + ); + }); + + it('should accept a credentialed url without leaking it (no rejection path)', () => { + expect( + () => + new Request({ + url: 'http://user:pass@host/', + protocol: Protocol.HTTP + }) + ).not.toThrow(); + }); + }); }); diff --git a/src/RequestExecutor/Request.ts b/src/RequestExecutor/Request.ts index 6bba1df6..b5fab9fa 100644 --- a/src/RequestExecutor/Request.ts +++ b/src/RequestExecutor/Request.ts @@ -1,5 +1,6 @@ import { logger } from '../Utils'; import { Protocol } from './Protocol'; +import { TargetUrl } from './TargetUrl'; import { readFile } from 'node:fs/promises'; import { basename, extname } from 'node:path'; import { createSecureContext } from 'node:tls'; @@ -198,11 +199,9 @@ export class Request { }; } - private validateUrl(url: string): void { - try { - new URL(url); - } catch { - throw new Error('Invalid URL.'); + private validateUrl(url: string | undefined): void { + if (!url?.trim()) { + throw new Error(`Invalid URL: ${TargetUrl.redact(url ?? '')}`); } } From d6365965da5ce651ad787fd86e414738dc755323 Mon Sep 17 00:00:00 2001 From: Aleksandr Borovskii Date: Thu, 24 Sep 2026 10:05:36 +0200 Subject: [PATCH 5/7] refactor(repeater): use a RepeaterErrorCodes value for the malformed-request ack Replace the ad-hoc 'ERR_MALFORMED_REQUEST' string with a new RepeaterErrorCodes.MALFORMED_REQUEST enum member, so the per-request protocolError ack code is drawn from the same enum as the other repeater error codes. The value is carried on the request ack only, never on the deploy-time error event, so it does not affect critical-error handling. --- src/Repeater/RepeaterServer.ts | 6 +++++- src/Repeater/ServerRepeaterLauncher.spec.ts | 5 +++-- src/Repeater/ServerRepeaterLauncher.ts | 5 ++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Repeater/RepeaterServer.ts b/src/Repeater/RepeaterServer.ts index 11736e0e..97863d18 100644 --- a/src/Repeater/RepeaterServer.ts +++ b/src/Repeater/RepeaterServer.ts @@ -59,7 +59,7 @@ export type RepeaterServerRequestResponse = // classify it as a bridge<->repeater contract failure rather than a target // outage. protocol: Protocol; - protocolError: { code: string; message: string }; + protocolError: { code: RepeaterErrorCodes; message: string }; }; export interface RepeaterServerReconnectionFailedEvent { @@ -76,6 +76,10 @@ export enum RepeaterErrorCodes { REPEATER_DEACTIVATED = 'repeater_deactivated', REPEATER_UNAUTHORIZED = 'repeater_unauthorized', REPEATER_NO_LONGER_SUPPORTED = 'repeater_no_longer_supported', + // A forwarded request the repeater could not construct/dispatch (a malformed + // request shape). Carried on the per-request `protocolError` ack, NOT on the + // deploy-time `error` event — so it never trips isCriticalError. + MALFORMED_REQUEST = 'malformed_request', UNKNOWN_ERROR = 'unknown_error', UNEXPECTED_ERROR = 'unexpected_error' } diff --git a/src/Repeater/ServerRepeaterLauncher.spec.ts b/src/Repeater/ServerRepeaterLauncher.spec.ts index a3be8be5..0034430b 100644 --- a/src/Repeater/ServerRepeaterLauncher.spec.ts +++ b/src/Repeater/ServerRepeaterLauncher.spec.ts @@ -5,7 +5,8 @@ import { RepeaterServerEvents, RepeaterServerEventHandler, RepeaterServerRequestEvent, - RepeaterServerRequestResponse + RepeaterServerRequestResponse, + RepeaterErrorCodes } from './RepeaterServer'; import { RepeaterCommandHub } from './RepeaterCommandHub'; import { RuntimeDetector } from './RuntimeDetector'; @@ -114,7 +115,7 @@ describe('ServerRepeaterLauncher', () => { expect(response).toEqual({ protocol: Protocol.HTTP, protocolError: { - code: 'ERR_MALFORMED_REQUEST', + code: RepeaterErrorCodes.MALFORMED_REQUEST, message: 'Invalid URL: ' } }); diff --git a/src/Repeater/ServerRepeaterLauncher.ts b/src/Repeater/ServerRepeaterLauncher.ts index e3270889..d9d6ff6c 100644 --- a/src/Repeater/ServerRepeaterLauncher.ts +++ b/src/Repeater/ServerRepeaterLauncher.ts @@ -261,7 +261,10 @@ export class ServerRepeaterLauncher implements RepeaterLauncher { return { protocol: event.protocol, - protocolError: { code: 'ERR_MALFORMED_REQUEST', message: reason } + protocolError: { + code: RepeaterErrorCodes.MALFORMED_REQUEST, + message: reason + } }; } From af883e1aec3e9aa23e5caacab8016d99a92112c4 Mon Sep 17 00:00:00 2001 From: Aleksandr Borovskii Date: Thu, 26 Nov 2026 10:30:02 +0100 Subject: [PATCH 6/7] Trim comments and drop planning-document references Remove D3/D4 decision labels, finding and task references, and comments that restate the code. Flatten TargetUrl.spec nested describes to method names. --- src/Repeater/RepeaterServer.ts | 13 +- src/Repeater/ServerRepeaterLauncher.spec.ts | 11 +- src/Repeater/ServerRepeaterLauncher.ts | 8 +- .../HttpRequestExecutor.spec.ts | 34 ++-- src/RequestExecutor/HttpRequestExecutor.ts | 10 +- src/RequestExecutor/TargetUrl.spec.ts | 180 +++++++++--------- src/RequestExecutor/TargetUrl.ts | 53 ++---- 7 files changed, 124 insertions(+), 185 deletions(-) diff --git a/src/Repeater/RepeaterServer.ts b/src/Repeater/RepeaterServer.ts index 712f39a6..7aafb63f 100644 --- a/src/Repeater/RepeaterServer.ts +++ b/src/Repeater/RepeaterServer.ts @@ -54,12 +54,8 @@ export type RepeaterServerRequestResponse = errorCode?: string; } | { - // The request event payload could not be dispatched because it was - // malformed (the Request could not be constructed). This is distinct from - // an execution failure — which uses the { message, errorCode } variant - // produced by HttpRequestExecutor.execute's catch — and lets the bridge - // classify it as a bridge<->repeater contract failure rather than a target - // outage. + // The payload could not be turned into a Request. Unlike the + // { message, errorCode } variant, this is not a target-side failure. protocol: Protocol; protocolError: { code: RepeaterErrorCodes; message: string }; }; @@ -78,9 +74,8 @@ export enum RepeaterErrorCodes { REPEATER_DEACTIVATED = 'repeater_deactivated', REPEATER_UNAUTHORIZED = 'repeater_unauthorized', REPEATER_NO_LONGER_SUPPORTED = 'repeater_no_longer_supported', - // A forwarded request the repeater could not construct/dispatch (a malformed - // request shape). Carried on the per-request `protocolError` ack, NOT on the - // deploy-time `error` event — so it never trips isCriticalError. + // Sent on the per-request `protocolError` ack, not the deploy-time `error` + // event, so it never trips isCriticalError. MALFORMED_REQUEST = 'malformed_request', UNKNOWN_ERROR = 'unknown_error', UNEXPECTED_ERROR = 'unexpected_error' diff --git a/src/Repeater/ServerRepeaterLauncher.spec.ts b/src/Repeater/ServerRepeaterLauncher.spec.ts index 0f35690e..5a6716f4 100644 --- a/src/Repeater/ServerRepeaterLauncher.spec.ts +++ b/src/Repeater/ServerRepeaterLauncher.spec.ts @@ -38,8 +38,6 @@ describe('ServerRepeaterLauncher', () => { const requestExecutorOptionsMock = mock(); const cliInfoMock = mock(); - // A fake RepeaterServer that records the handlers subscribeToEvents registers, - // so the captured REQUEST handler can be driven directly. const handlers = new Map>(); const repeaterServer: RepeaterServer = { disconnect: (): void => undefined, @@ -82,7 +80,6 @@ describe('ServerRepeaterLauncher', () => { instance(cliInfoMock) ); - // run() wires subscribeToEvents, registering the REQUEST handler. await sut.run('repeater-1'); }); @@ -101,8 +98,7 @@ describe('ServerRepeaterLauncher', () => { } as unknown as Response); it('should ack with a protocol error when the request payload cannot be constructed', async () => { - // arrange — a URL the Request constructor still rejects post-relaxation - // (blank after trim). + // arrange const event: RepeaterServerRequestEvent = { protocol: Protocol.HTTP, url: '' @@ -136,8 +132,7 @@ describe('ServerRepeaterLauncher', () => { }); it('should ack with message and errorCode when execution itself fails', async () => { - // arrange — a constructible request whose execution fails is a distinct - // error class from a malformed payload. + // arrange when(commandHubMock.sendRequest(anything())).thenResolve({ protocol: Protocol.HTTP, message: 'Connection refused', @@ -189,7 +184,7 @@ describe('ServerRepeaterLauncher', () => { // act await requestHandler()(event); - // assert — a rejected payload is a logger.error, never a Sentry event. + // assert expect(captureException).not.toHaveBeenCalled(); expect(loggerErrorSpy).toHaveBeenCalled(); }); diff --git a/src/Repeater/ServerRepeaterLauncher.ts b/src/Repeater/ServerRepeaterLauncher.ts index 61662f73..6c2020fc 100644 --- a/src/Repeater/ServerRepeaterLauncher.ts +++ b/src/Repeater/ServerRepeaterLauncher.ts @@ -251,12 +251,8 @@ export class ServerRepeaterLauncher implements RepeaterLauncher { request = new Request({ ...event }); } catch (e) { const reason = e instanceof Error ? e.message : String(e); - // A malformed request payload the bridge sent that we cannot dispatch. - // Answer the ack with a protocol error so the bridge can classify it as a - // bridge<->repeater contract failure — distinct from an execution failure, - // which returns the { message, errorCode } variant below. logger.error - // only, NOT captureException: the whole point of this fix is that these - // stop being Sentry events. + // Scanners deliberately send malformed targets; logged but not sent to + // Sentry to avoid noise. logger.error('Rejecting a malformed request from the bridge: %s', reason); return { diff --git a/src/RequestExecutor/HttpRequestExecutor.spec.ts b/src/RequestExecutor/HttpRequestExecutor.spec.ts index ed975d0a..fc818653 100644 --- a/src/RequestExecutor/HttpRequestExecutor.spec.ts +++ b/src/RequestExecutor/HttpRequestExecutor.spec.ts @@ -2288,15 +2288,10 @@ describe('HttpRequestExecutor', () => { }, 60000); }); - // Probe: prove a malformed-authority URL now travels all the way to libcurl - // and is answered with libcurl's own returned failure, rather than being - // short-circuited client-side (Finding A) or hanging/throwing something the - // execute catch maps to undefined. Run on the supported Node runtime - // (package.json engines: >=22 <=24), NOT Node 26. + // Pins the libcurl behaviour on the supported runtime (engines: >=22 <=24). describe('execute', () => { - // Build a Request carrying a malformed authority WITHOUT tripping the - // constructor predicate (Task 9 relaxes it separately): construct with a - // valid placeholder, then redefine the readonly url. + // Redefines the readonly url on a valid request to bypass the blank-url + // check in the constructor. const malformedRequest = (url: string): Request => { const request = new Request({ url: 'http://placeholder.invalid/', @@ -2307,14 +2302,9 @@ describe('HttpRequestExecutor', () => { return request; }; - // Concrete libcurl outcome observed on Node 24 for each authority defect, - // via the string decomposition TargetUrl feeds curl. libcurl rejects the - // rebuilt authority as CURLE_URL_MALFORMAT and node-libcurl surfaces it as a - // returned Error whose message is the text below; execute's catch derives - // errorCode = code ?? syscall ?? name, which for this Error is the name - // ('Error') — the load-bearing fact for the AC is that it is a DEFINED, - // returned value, never a hang and never the ERR_INVALID_URL short-circuit - // the throwing new URL() used to produce. + // libcurl rejects each malformed authority as CURLE_URL_MALFORMAT. What + // matters is that execute returns this failure rather than throwing, + // hanging, or short-circuiting with ERR_INVALID_URL. const CURL_MALFORMAT_MESSAGE = 'Request failed: URL using bad/illegal format or missing URL'; @@ -2330,16 +2320,14 @@ describe('HttpRequestExecutor', () => { it.each(cases)( 'should reach libcurl and return a defined error for %s (not ERR_INVALID_URL, no throw/hang)', async (_name, url) => { - // arrange — an explicit per-test timeout keeps a would-be hang well - // under the jest default so a regression fails loudly, not by stalling. + // arrange const sut = buildSut(); const request = malformedRequest(url); - // act — must resolve (never reject/throw). + // act const response = await sut.execute(request); - // assert — a returned Response carrying libcurl's malformat failure, - // never the client-side ERR_INVALID_URL short-circuit. + // assert expect(response.errorCode).toBeDefined(); expect(response.errorCode).not.toBe('ERR_INVALID_URL'); expect(response.message).toBe(CURL_MALFORMAT_MESSAGE); @@ -2348,8 +2336,8 @@ describe('HttpRequestExecutor', () => { ); it('should short-circuit an empty authority without reaching a virtual script', async () => { - // arrange — an origin-form target has no hostname (D4); no virtual script - // lookup is attempted and execution still returns a Response. + // arrange — an origin-form target has no hostname, so no virtual script + // lookup is attempted. const sut = buildSut(); const request = malformedRequest('/origin-form-only'); diff --git a/src/RequestExecutor/HttpRequestExecutor.ts b/src/RequestExecutor/HttpRequestExecutor.ts index 34103b6e..f30e45b4 100644 --- a/src/RequestExecutor/HttpRequestExecutor.ts +++ b/src/RequestExecutor/HttpRequestExecutor.ts @@ -390,7 +390,7 @@ export class HttpRequestExecutor implements RequestExecutor { private resolveProxy(options: Request): string | undefined { const { hostname } = TargetUrl.parse(options.url); - // No resolvable authority (D4): make no proxy decision keyed on a host that + // No resolvable authority: make no proxy decision keyed on a host that // does not exist, rather than coercing undefined into the string 'null' // inside RegExp.test. if (hostname === undefined) { @@ -429,7 +429,7 @@ export class HttpRequestExecutor implements RequestExecutor { const { hostname } = TargetUrl.parse(options.url); - // No resolvable authority (D4): no host to match a Kerberos domain against. + // No resolvable authority: no host to match a Kerberos domain against. if (hostname === undefined) { return false; } @@ -561,9 +561,7 @@ export class HttpRequestExecutor implements RequestExecutor { private async transformScript(script: Request): Promise { const { hostname } = TargetUrl.parse(script.url); - // No resolvable authority (D4): no host to match a virtual script against, - // and — crucially — no throwing `new URL()` to short-circuit an otherwise - // deliverable request before it reaches libcurl (Finding A). + // No resolvable authority: no host to match a virtual script against. if (hostname === undefined) { return script; } @@ -615,7 +613,7 @@ export class HttpRequestExecutor implements RequestExecutor { ): Promise { const { hostname } = TargetUrl.parse(request.url); - // No resolvable authority (D4): no host to match a response script against. + // No resolvable authority: no host to match a response script against. if (hostname === undefined) { return response; } diff --git a/src/RequestExecutor/TargetUrl.spec.ts b/src/RequestExecutor/TargetUrl.spec.ts index 56c2552b..58986134 100644 --- a/src/RequestExecutor/TargetUrl.spec.ts +++ b/src/RequestExecutor/TargetUrl.spec.ts @@ -2,118 +2,108 @@ import { TargetUrl } from './TargetUrl'; describe('TargetUrl', () => { describe('parse', () => { - describe('well-formed URLs', () => { - it('should decompose scheme, host, hostname, userinfo and path', () => { - const parts = TargetUrl.parse( - 'http://user:pass@example.com:8080/a/b?q=1#f' - ); - - expect(parts).toEqual({ - scheme: 'http:', - host: 'example.com:8080', - hostname: 'example.com', - userinfo: 'user:pass', - path: '/a/b?q=1#f' - }); - }); - - it('should lowercase the hostname but leave the path casing untouched', () => { - const parts = TargetUrl.parse('https://EXAMPLE.com/Path'); + it('should decompose scheme, host, hostname, userinfo and path', () => { + const parts = TargetUrl.parse( + 'http://user:pass@example.com:8080/a/b?q=1#f' + ); - expect(parts.hostname).toBe('example.com'); - expect(parts.host).toBe('EXAMPLE.com'); - expect(parts.path).toBe('/Path'); + expect(parts).toEqual({ + scheme: 'http:', + host: 'example.com:8080', + hostname: 'example.com', + userinfo: 'user:pass', + path: '/a/b?q=1#f' }); + }); - it('should default the path to "/" when the URL has none', () => { - const parts = TargetUrl.parse('http://example.com'); + it('should lowercase the hostname but leave the path casing untouched', () => { + const parts = TargetUrl.parse('https://EXAMPLE.com/Path'); - expect(parts.host).toBe('example.com'); - expect(parts.path).toBe('/'); - }); + expect(parts.hostname).toBe('example.com'); + expect(parts.host).toBe('EXAMPLE.com'); + expect(parts.path).toBe('/Path'); + }); - it('should NOT apply IDNA/punycode to an internationalised hostname (D3)', () => { - const parts = TargetUrl.parse('http://☃.net/x'); + it('should default the path to "/" when the URL has none', () => { + const parts = TargetUrl.parse('http://example.com'); - // Intentional behaviour change vs the old WHATWG path, which would have - // produced xn--n3h.net. - expect(parts.hostname).toBe('☃.net'); - }); + expect(parts.host).toBe('example.com'); + expect(parts.path).toBe('/'); + }); - it('should strip brackets from a bracketed IPv6 host and keep the port on host', () => { - const parts = TargetUrl.parse('http://[::1]:8080/x'); + it('should NOT apply IDNA/punycode to an internationalised hostname', () => { + const parts = TargetUrl.parse('http://☃.net/x'); - expect(parts.host).toBe('[::1]:8080'); - expect(parts.hostname).toBe('::1'); - expect(parts.path).toBe('/x'); - }); + expect(parts.hostname).toBe('☃.net'); + }); - it('should preserve an underscore host verbatim', () => { - const parts = TargetUrl.parse('http://under_score/y'); + it('should strip brackets from a bracketed IPv6 host and keep the port on host', () => { + const parts = TargetUrl.parse('http://[::1]:8080/x'); - expect(parts.hostname).toBe('under_score'); - }); + expect(parts.host).toBe('[::1]:8080'); + expect(parts.hostname).toBe('::1'); + expect(parts.path).toBe('/x'); }); - describe('authority defects (must not throw, hostname best-effort)', () => { - // The six authority defects the WHATWG parser rejected. TargetUrl.parse - // must decompose each without throwing so the request still reaches - // libcurl (Finding A). See HttpRequestExecutor.spec for the libcurl codes. - const cases: [name: string, url: string][] = [ - ['non-numeric port', 'http://host:notaport/'], - ['port > 65535', 'http://host:99999/'], - ['unbracketed IPv6', 'http://::1/'], - ['space in host', 'http://ho st/'], - ['[not-ipv6]', 'http://[not-ipv6]/'], - ['empty string', ''] - ]; - - it.each(cases)('should not throw for %s', (_name, url) => { - expect(() => TargetUrl.parse(url)).not.toThrow(); - }); + it('should preserve an underscore host verbatim', () => { + const parts = TargetUrl.parse('http://under_score/y'); - it('should still expose the scheme for an unbracketed IPv6 authority', () => { - expect(TargetUrl.parse('http://::1/').scheme).toBe('http:'); - }); + expect(parts.hostname).toBe('under_score'); + }); - it('should yield hostname undefined for an empty string', () => { - expect(TargetUrl.parse('').hostname).toBeUndefined(); - }); + // Authority shapes `new URL()` rejects; parse must not throw on them. + const authorityDefects: [name: string, url: string][] = [ + ['non-numeric port', 'http://host:notaport/'], + ['port > 65535', 'http://host:99999/'], + ['unbracketed IPv6', 'http://::1/'], + ['space in host', 'http://ho st/'], + ['[not-ipv6]', 'http://[not-ipv6]/'], + ['empty string', ''] + ]; + + it.each(authorityDefects)('should not throw for %s', (_name, url) => { + expect(() => TargetUrl.parse(url)).not.toThrow(); }); - describe('path/encoding malformations (must survive byte-for-byte)', () => { - // The 19 scanner-controlled path malformations that must pass through - // untouched — no percent-encoding normalisation — because libcurl is - // driven with PATH_AS_IS. - const cases: [name: string, url: string, expected: string][] = [ - ['space in path', 'http://h/path with spaces', '/path with spaces'], - ['raw tab', 'http://h/a\tb', '/a\tb'], - ['raw newline', 'http://h/a\nb', '/a\nb'], - ['raw non-ascii latin1', 'http://h/caf\u00e9', '/caf\u00e9'], - ['bad percent %zz', 'http://h/%zz', '/%zz'], - ['lone percent', 'http://h/%', '/%'], - ['double percent', 'http://h/%%', '/%%'], - ['backslash', 'http://h/a\\b', '/a\\b'], - ['fragment', 'http://h/p#frag', '/p#frag'], - ['asterisk path', 'http://h/*', '/*'], - ['query only', 'http://h?q=1', '/?q=1'], - ['encoded slash', 'http://h/a%2fb', '/a%2fb'], - ['double slash path', 'http://h//a//b', '//a//b'], - ['semicolon params', 'http://h/a;b=c', '/a;b=c'], - ['plus in query', 'http://h/a?x=1+2', '/a?x=1+2'], - ['at in path', 'http://h/a@b', '/a@b'], - ['colon in path', 'http://h/a:b', '/a:b'], - ['unicode in query', 'http://h/a?q=\u2603', '/a?q=\u2603'], - ['trailing dotdot', 'http://h/a/../b', '/a/../b'] - ]; - - it.each(cases)( - 'should preserve the raw path for %s', - (_name, url, expected) => { - expect(TargetUrl.parse(url).path).toBe(expected); - } - ); + it('should still expose the scheme for an unbracketed IPv6 authority', () => { + expect(TargetUrl.parse('http://::1/').scheme).toBe('http:'); + }); + + it('should yield hostname undefined for an empty string', () => { + expect(TargetUrl.parse('').hostname).toBeUndefined(); }); + + // The 19 scanner-controlled path malformations that must pass through + // untouched — no percent-encoding normalisation — because libcurl is + // driven with PATH_AS_IS. + const pathMalformations: [name: string, url: string, expected: string][] = [ + ['space in path', 'http://h/path with spaces', '/path with spaces'], + ['raw tab', 'http://h/a\tb', '/a\tb'], + ['raw newline', 'http://h/a\nb', '/a\nb'], + ['raw non-ascii latin1', 'http://h/caf\u00e9', '/caf\u00e9'], + ['bad percent %zz', 'http://h/%zz', '/%zz'], + ['lone percent', 'http://h/%', '/%'], + ['double percent', 'http://h/%%', '/%%'], + ['backslash', 'http://h/a\\b', '/a\\b'], + ['fragment', 'http://h/p#frag', '/p#frag'], + ['asterisk path', 'http://h/*', '/*'], + ['query only', 'http://h?q=1', '/?q=1'], + ['encoded slash', 'http://h/a%2fb', '/a%2fb'], + ['double slash path', 'http://h//a//b', '//a//b'], + ['semicolon params', 'http://h/a;b=c', '/a;b=c'], + ['plus in query', 'http://h/a?x=1+2', '/a?x=1+2'], + ['at in path', 'http://h/a@b', '/a@b'], + ['colon in path', 'http://h/a:b', '/a:b'], + ['unicode in query', 'http://h/a?q=\u2603', '/a?q=\u2603'], + ['trailing dotdot', 'http://h/a/../b', '/a/../b'] + ]; + + it.each(pathMalformations)( + 'should preserve the raw path for %s', + (_name, url, expected) => { + expect(TargetUrl.parse(url).path).toBe(expected); + } + ); }); describe('redact', () => { diff --git a/src/RequestExecutor/TargetUrl.ts b/src/RequestExecutor/TargetUrl.ts index 40ad5463..41050a7f 100644 --- a/src/RequestExecutor/TargetUrl.ts +++ b/src/RequestExecutor/TargetUrl.ts @@ -1,45 +1,27 @@ /** - * A non-throwing, string-only decomposition of a target URL, shared by every + * Non-throwing, string-only decomposition of a target URL, shared by every * consumer on the request-execute path. * - * Motivation: the previous code split URL handling across two parsers — the - * WHATWG `new URL()` (in the virtual-script and response-script lookups) and the - * legacy `node:url` `parse()` (in curl configuration, proxy resolution, and - * Kerberos gating). The two disagree on normalisation (IDNA, casing, port - * handling), and `new URL()` THROWS on an authority defect, short-circuiting an - * otherwise-deliverable scanner request into an `ERR_INVALID_URL` before it ever - * reaches libcurl. This class replaces both with one decomposition that never - * throws, so a malformed-authority URL travels all the way to libcurl and is - * answered with libcurl's own returned error code (e.g. `CURLE_URL_MALFORMAT`) - * rather than being rejected client-side. + * `new URL()` throws on an authority defect, which would turn an otherwise + * deliverable scanner request into `ERR_INVALID_URL` before it reaches libcurl. + * This parser only slices strings, so such a URL travels on and libcurl answers + * it (e.g. `CURLE_URL_MALFORMAT`). * - * Design decisions: - * - **D3 — hostname normalisation.** {@link TargetUrlParts.hostname} is - * raw-lowercased with NO IDNA/punycode conversion. This differs from the old - * WHATWG path for internationalised domains: `☃.net` stays `☃.net` (lowercased) - * instead of becoming `xn--n3h.net`. Virtual-script and proxy-domain matching - * therefore key on the raw hostname. Intentional; documented behaviour change. - * - **D4 — unparseable authority means "skip".** When the URL has no authority, - * {@link TargetUrlParts.hostname} is `undefined`; consumers treat that as "no - * virtual script, no response script, no proxy, no Kerberos" rather than - * coercing a `null`/`undefined` hostname into the string `"null"` inside a - * `RegExp.test(...)`. + * `hostname` is lowercased without IDNA/punycode conversion: `☃.net` stays + * `☃.net`, not `xn--n3h.net`. Virtual-script and proxy-domain matching key on + * the raw hostname. * - * The parser performs only string slicing — no `new URL`, no `node:url` `parse`. - * The {@link TargetUrlParts.path} field preserves the raw path+query+hash with - * no percent-encoding normalisation, because libcurl is driven with - * `PATH_AS_IS` and every scanner-controlled path malformation must survive - * byte-for-byte. + * `hostname` is `undefined` when there is no authority; consumers then skip + * host-keyed behaviour instead of matching the string `"null"` against a regex. + * + * `path` is kept byte-for-byte because libcurl runs with `PATH_AS_IS`. */ export interface TargetUrlParts { /** Scheme WITH its trailing colon, e.g. `'http:'`; `undefined` when absent. */ readonly scheme?: string; /** `hostname[:port]` as `configureCurl` needs it; `undefined` when absent. */ readonly host?: string; - /** - * Lowercased hostname with no port, no IPv6 brackets, and no IDNA/punycode - * normalisation (decision D3); `undefined` when no authority is present (D4). - */ + /** Lowercased hostname without port or IPv6 brackets; no IDNA conversion. */ readonly hostname?: string; /** `user:pass` userinfo for libcurl `USERPWD`; `undefined` when absent. */ readonly userinfo?: string; @@ -59,9 +41,7 @@ export class TargetUrl { const separatorIndex = url.indexOf(TargetUrl.SCHEME_SEPARATOR); - // Origin-form (no scheme://): there is no authority to decompose. Only the - // path is meaningful; hostname stays undefined so consumers skip host-keyed - // behaviour (D4). + // Origin-form target: no authority, so hostname stays undefined. if (separatorIndex === -1) { return { path }; } @@ -135,10 +115,7 @@ export class TargetUrl { }; } - /** - * Strip the port and IPv6 brackets from a `host` and lowercase it, with no - * IDNA/punycode conversion (D3). - */ + /** Strips port and IPv6 brackets and lowercases, without IDNA conversion. */ private static extractHostname(host: string): string { // Bracketed IPv6 literal: `[::1]` or `[::1]:8080`. if (host.startsWith('[')) { From 80dc8eb99a0438ce7bf4a8fd5542e0abf6a9649f Mon Sep 17 00:00:00 2001 From: Alexander Borovsky Date: Thu, 26 Nov 2026 13:28:44 +0100 Subject: [PATCH 7/7] fix: simplify code comments --- src/RequestExecutor/TargetUrl.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/RequestExecutor/TargetUrl.ts b/src/RequestExecutor/TargetUrl.ts index 41050a7f..accdda5b 100644 --- a/src/RequestExecutor/TargetUrl.ts +++ b/src/RequestExecutor/TargetUrl.ts @@ -7,8 +7,7 @@ * This parser only slices strings, so such a URL travels on and libcurl answers * it (e.g. `CURLE_URL_MALFORMAT`). * - * `hostname` is lowercased without IDNA/punycode conversion: `☃.net` stays - * `☃.net`, not `xn--n3h.net`. Virtual-script and proxy-domain matching key on + * `hostname` is lowercased without IDNA/punycode conversion. Virtual-script and proxy-domain matching key on * the raw hostname. * * `hostname` is `undefined` when there is no authority; consumers then skip