diff --git a/src/Repeater/RepeaterServer.ts b/src/Repeater/RepeaterServer.ts index ab664217..7aafb63f 100644 --- a/src/Repeater/RepeaterServer.ts +++ b/src/Repeater/RepeaterServer.ts @@ -52,6 +52,12 @@ export type RepeaterServerRequestResponse = protocol: Protocol; message?: string; errorCode?: string; + } + | { + // 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 }; }; export interface RepeaterServerReconnectionFailedEvent { @@ -68,6 +74,9 @@ export enum RepeaterErrorCodes { REPEATER_DEACTIVATED = 'repeater_deactivated', REPEATER_UNAUTHORIZED = 'repeater_unauthorized', REPEATER_NO_LONGER_SUPPORTED = 'repeater_no_longer_supported', + // 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 45bd1f5e..5a6716f4 100644 --- a/src/Repeater/ServerRepeaterLauncher.spec.ts +++ b/src/Repeater/ServerRepeaterLauncher.spec.ts @@ -1,60 +1,213 @@ import 'reflect-metadata'; import { ServerRepeaterLauncher } from './ServerRepeaterLauncher'; -import { RepeaterServer, RepeaterServerEvents } from './RepeaterServer'; -import { RuntimeDetector } from './RuntimeDetector'; +import { + RepeaterServer, + RepeaterServerEvents, + RepeaterServerEventHandler, + RepeaterServerRequestEvent, + RepeaterServerRequestResponse, + RepeaterErrorCodes +} from './RepeaterServer'; import { RepeaterCommandHub } from './RepeaterCommandHub'; -import { ScriptLoader, VirtualScripts } from '../Scripts'; +import { RuntimeDetector } from './RuntimeDetector'; import { StartupManager } from '../StartupScripts'; -import { Certificates, RequestExecutorOptions } from '../RequestExecutor'; +import { ScriptLoader, VirtualScripts } from '../Scripts'; +import { + Certificates, + Protocol, + RequestExecutorOptions, + Response +} from '../RequestExecutor'; import { CliInfo } from '../Config'; -import { Logger, logger } from '../Utils'; -import { anything, instance, mock, reset, spy, verify, when } from 'ts-mockito'; +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 mockedRepeaterServer = mock(); - const handlers = new Map unknown>(); - - let loggerSpy: Logger; - let launcher: ServerRepeaterLauncher; - - beforeEach(() => { - loggerSpy = spy(logger); - when(loggerSpy.warn(anything(), anything())).thenReturn(); - when(mockedRepeaterServer.on(anything(), anything())).thenCall( - (event: string, handler: (payload?: unknown) => unknown) => - handlers.set(event, handler) - ); + const runtimeDetectorMock = mock(); + const virtualScriptsMock = mock(); + const startupManagerMock = mock(); + const commandHubMock = mock(); + const certificatesMock = mock(); + const scriptLoaderMock = mock(); + const requestExecutorOptionsMock = mock(); + const cliInfoMock = mock(); + + 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 + }; - launcher = new ServerRepeaterLauncher( - instance(mock()), - instance(mock()), - instance(mockedRepeaterServer), - instance(mock()), - instance(mock()), - instance(mock()), - instance(mock()), - {} as RequestExecutorOptions, - { version: '1.0.0' } as CliInfo + 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) ); + + await sut.run('repeater-1'); }); afterEach(() => { - handlers.clear(); - reset(mockedRepeaterServer, loggerSpy); + loggerErrorSpy.mockRestore(); + reset(commandHubMock); }); describe('run', () => { - it('should log a reconnecting warning on a reconnection attempt', async () => { + 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 + const event: RepeaterServerRequestEvent = { + protocol: Protocol.HTTP, + url: '' + }; + + // act + const response = await requestHandler()(event); + + // assert + expect(response).toEqual({ + protocol: Protocol.HTTP, + protocolError: { + code: RepeaterErrorCodes.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: '' + }; + + // act + await requestHandler()(event); + + // assert + verify(commandHubMock.sendRequest(anything())).never(); + }); + + it('should ack with message and errorCode when execution itself fails', async () => { + // arrange + 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: '' + }; + + // act + await requestHandler()(event); + + // assert + expect(captureException).not.toHaveBeenCalled(); + expect(loggerErrorSpy).toHaveBeenCalled(); + }); + + it('should log a reconnecting warning on a reconnection attempt', () => { // arrange - await launcher.run('8PY6wKetVqmfMC9K9g4A7Y'); + const loggerWarnSpy = jest + .spyOn(logger, 'warn') + .mockImplementation(() => 0); // act - handlers.get(RepeaterServerEvents.RECONNECT_ATTEMPT)?.({ attempt: 2 }); + ( + handlers.get(RepeaterServerEvents.RECONNECT_ATTEMPT) as ( + payload: unknown + ) => unknown + )({ attempt: 2 }); // assert - verify( - loggerSpy.warn('Reconnecting to Bright cloud (attempt %d)', 2) - ).once(); + expect(loggerWarnSpy).toHaveBeenCalledWith( + 'Reconnecting to Bright cloud (attempt %d)', + 2 + ); + loggerWarnSpy.mockRestore(); }); }); }); diff --git a/src/Repeater/ServerRepeaterLauncher.ts b/src/Repeater/ServerRepeaterLauncher.ts index b59ce149..6c2020fc 100644 --- a/src/Repeater/ServerRepeaterLauncher.ts +++ b/src/Repeater/ServerRepeaterLauncher.ts @@ -245,9 +245,26 @@ 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); + // 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 { + protocol: event.protocol, + protocolError: { + code: RepeaterErrorCodes.MALFORMED_REQUEST, + message: reason + } + }; + } + + const response = await this.commandHub.sendRequest(request); const { statusCode, diff --git a/src/RequestExecutor/HttpRequestExecutor.spec.ts b/src/RequestExecutor/HttpRequestExecutor.spec.ts index 6bbdd1f3..fc818653 100644 --- a/src/RequestExecutor/HttpRequestExecutor.spec.ts +++ b/src/RequestExecutor/HttpRequestExecutor.spec.ts @@ -2287,4 +2287,66 @@ describe('HttpRequestExecutor', () => { }).toEqual(expect.objectContaining({ withinBudget: true })); }, 60000); }); + + // Pins the libcurl behaviour on the supported runtime (engines: >=22 <=24). + describe('execute', () => { + // 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/', + protocol: Protocol.HTTP + }); + Object.defineProperty(request, 'url', { value: url, writable: false }); + + return request; + }; + + // 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'; + + 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 + const sut = buildSut(); + const request = malformedRequest(url); + + // act + const response = await sut.execute(request); + + // assert + 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, so no virtual script + // lookup is attempted. + 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(); + }); + }); }); diff --git a/src/RequestExecutor/HttpRequestExecutor.ts b/src/RequestExecutor/HttpRequestExecutor.ts index bb5dc641..f30e45b4 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 { CurlErrorMapper } from './CurlErrorMapper'; import { inject, injectable } from 'tsyringe'; import iconv from 'iconv-lite'; @@ -21,7 +22,6 @@ import { HeaderInfo, Multi } from '@brightsec/node-libcurl'; -import { parse as parseUrl } from 'node:url'; type ScriptEntrypoint = ( options: RequestOptions @@ -185,15 +185,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); @@ -226,23 +225,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; @@ -406,7 +388,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: 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 && @@ -438,7 +427,12 @@ export class HttpRequestExecutor implements RequestExecutor { return true; } - const hostname = parseUrl(options.url).hostname; + const { hostname } = TargetUrl.parse(options.url); + + // No resolvable authority: no host to match a Kerberos domain against. + if (hostname === undefined) { + return false; + } return this.kerberosDomains.some((domain) => domain.test(hostname)); } @@ -565,7 +559,12 @@ 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: no host to match a virtual script against. + if (hostname === undefined) { + return script; + } const vm = this.virtualScripts.find(hostname); @@ -612,7 +611,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: no host to match a response script against. + if (hostname === undefined) { + return response; + } const vm = this.virtualScripts.find(hostname); diff --git a/src/RequestExecutor/Request.spec.ts b/src/RequestExecutor/Request.spec.ts index 2a4feeae..27f884c3 100644 --- a/src/RequestExecutor/Request.spec.ts +++ b/src/RequestExecutor/Request.spec.ts @@ -139,6 +139,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(); + }); + // The trace id must never reach the target. bridges carries it as a `traceId` // DTO field, and the guarantee that an old repeater cannot leak it rests on // this constructor's FIXED destructured param list — an unknown key is diff --git a/src/RequestExecutor/Request.ts b/src/RequestExecutor/Request.ts index 6af503df..37c4f1ad 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'; @@ -109,7 +110,7 @@ export class Request { this.protocol = protocol; this._method = method?.toUpperCase() ?? 'GET'; - this.validateUrl(url); + this.assertUrlNotBlank(url); this.url = url.trim(); this.precheckBody(body); @@ -209,11 +210,9 @@ export class Request { }; } - private validateUrl(url: string): void { - try { - new URL(url); - } catch { - throw new Error('Invalid URL.'); + private assertUrlNotBlank(url: string | undefined): void { + if (!url?.trim()) { + throw new Error(`Invalid URL: ${TargetUrl.redact(url ?? '')}`); } } diff --git a/src/RequestExecutor/TargetUrl.spec.ts b/src/RequestExecutor/TargetUrl.spec.ts new file mode 100644 index 00000000..58986134 --- /dev/null +++ b/src/RequestExecutor/TargetUrl.spec.ts @@ -0,0 +1,132 @@ +import { TargetUrl } from './TargetUrl'; + +describe('TargetUrl', () => { + describe('parse', () => { + 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', () => { + const parts = TargetUrl.parse('http://☃.net/x'); + + 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'); + }); + + // 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(); + }); + + 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', () => { + 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..accdda5b --- /dev/null +++ b/src/RequestExecutor/TargetUrl.ts @@ -0,0 +1,155 @@ +/** + * Non-throwing, string-only decomposition of a target URL, shared by every + * consumer on the request-execute path. + * + * `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`). + * + * `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 + * 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 without port or IPv6 brackets; no IDNA conversion. */ + 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 target: no authority, so hostname stays undefined. + 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) } : {}) + }; + } + + /** 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('[')) { + 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';