diff --git a/package-lock.json b/package-lock.json index 97e50d3a..be92ffb6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -53,6 +53,7 @@ "@types/js-yaml": "^4.0.2", "@types/ms": "^0.7.31", "@types/node": "^22.11.7", + "@types/node-forge": "^1.3.14", "@types/semver": "^7.5.8", "@types/ws": "^7.4.7", "@types/yargs": "~16.0.1", @@ -73,6 +74,7 @@ "jest": "^30.2.0", "lint-staged": "^16.2.7", "nock": "^13.2.9", + "node-forge": "^1.4.1", "prettier": "^2.7.1", "resedit": "3.1.0", "semantic-release": "^25.0.2", @@ -3790,6 +3792,16 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/node-forge": { + "version": "1.3.14", + "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz", + "integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/normalize-package-data": { "version": "2.4.4", "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz", @@ -11573,9 +11585,9 @@ } }, "node_modules/node-forge": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", - "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==", + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.4.tgz", + "integrity": "sha512-T6VRRpF3+czIGcXW/LOeoD7Ej28d8CF1UMEAbJyJRUtYMvyXAgxUPW2kbUibumvV9LiUQAznJOFyeYclzSJMMg==", "license": "(BSD-3-Clause OR GPL-2.0)", "engines": { "node": ">= 6.13.0" @@ -20728,6 +20740,15 @@ "undici-types": "~6.21.0" } }, + "@types/node-forge": { + "version": "1.3.14", + "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz", + "integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, "@types/normalize-package-data": { "version": "2.4.4", "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz", @@ -26038,9 +26059,9 @@ } }, "node-forge": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", - "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==" + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.4.tgz", + "integrity": "sha512-T6VRRpF3+czIGcXW/LOeoD7Ej28d8CF1UMEAbJyJRUtYMvyXAgxUPW2kbUibumvV9LiUQAznJOFyeYclzSJMMg==" }, "node-gyp": { "version": "13.0.0", diff --git a/package.json b/package.json index 38f9b5d7..a22ee542 100644 --- a/package.json +++ b/package.json @@ -67,6 +67,7 @@ "@types/js-yaml": "^4.0.2", "@types/ms": "^0.7.31", "@types/node": "^22.11.7", + "@types/node-forge": "^1.3.14", "@types/semver": "^7.5.8", "@types/ws": "^7.4.7", "@types/yargs": "~16.0.1", @@ -87,6 +88,7 @@ "jest": "^30.2.0", "lint-staged": "^16.2.7", "nock": "^13.2.9", + "node-forge": "^1.4.1", "prettier": "^2.7.1", "resedit": "3.1.0", "semantic-release": "^25.0.2", diff --git a/src/RequestExecutor/CurlHeadersParser.spec.ts b/src/RequestExecutor/CurlHeadersParser.spec.ts new file mode 100644 index 00000000..8ff8f7bb --- /dev/null +++ b/src/RequestExecutor/CurlHeadersParser.spec.ts @@ -0,0 +1,219 @@ +import { CurlHeadersParser } from './CurlHeadersParser'; + +const raw = (...lines: string[]) => + Buffer.from(lines.join('\r\n') + '\r\n\r\n', 'latin1'); + +describe('CurlHeadersParser', () => { + describe('parse', () => { + it.each([ + ['name:', 'name'], + ['name: ', 'name'], + ['name: ', 'name'] + ])('should return an empty string for "%s"', (line, name) => { + // arrange + const input = raw('HTTP/1.1 200 OK', line); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ [name]: '' }); + }); + + it('should accept a value without a space after the colon', () => { + // arrange + const input = raw('HTTP/1.1 200 OK', 'name:value'); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ name: 'value' }); + }); + + it('should trim optional whitespace around the value', () => { + // arrange + const input = raw('HTTP/1.1 200 OK', 'name: \t value \t '); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ name: 'value' }); + }); + + it('should keep colons inside the value', () => { + // arrange + const input = raw( + 'HTTP/1.1 302 Found', + 'location: https://a.test:8443/x' + ); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ location: 'https://a.test:8443/x' }); + }); + + it('should collect repeated names into an array in order', () => { + // arrange + const input = raw( + 'HTTP/1.1 200 OK', + 'Link: ; rel=1', + 'Vary: accept', + 'Link: ; rel=2' + ); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ + link: ['; rel=1', '; rel=2'], + vary: 'accept' + }); + }); + + it('should merge names that differ only by case', () => { + // arrange + const input = raw('HTTP/1.1 200 OK', 'X-Test: one', 'x-test: two'); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ 'x-test': ['one', 'two'] }); + }); + + it('should return set-cookie as an array even for a single field', () => { + // arrange + const input = raw('HTTP/1.1 200 OK', 'Set-Cookie: a=1'); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ 'set-cookie': ['a=1'] }); + }); + + it('should decode valid UTF-8 values so they round-trip', () => { + // arrange + const input = Buffer.from( + 'HTTP/1.1 200 OK\r\nset-cookie: n=é\r\ncontent-disposition: attachment; filename="日本.txt"\r\n\r\n', + 'utf8' + ); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ + 'set-cookie': ['n=é'], + 'content-disposition': 'attachment; filename="日本.txt"' + }); + }); + + it('should keep bytes that are not valid UTF-8 as latin1 code points', () => { + // arrange + const input = Buffer.concat([ + Buffer.from('HTTP/1.1 200 OK\r\nx-raw: a'), + Buffer.from([0x80, 0xff, 0xe9]), + Buffer.from('b\r\n\r\n') + ]); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(Buffer.from(result['x-raw'] as string, 'latin1')).toEqual( + Buffer.from([0x61, 0x80, 0xff, 0xe9, 0x62]) + ); + }); + + it.each(['content-type', 'content-length', 'location'])( + 'should keep the last value of a duplicated %s as a string', + (name) => { + // arrange + const input = raw( + 'HTTP/1.1 200 OK', + `${name}: first`, + `${name}: second` + ); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ [name]: 'second' }); + } + ); + + it('should join an obsolete folded continuation line with a single space', () => { + // arrange + const input = raw('HTTP/1.1 200 OK', 'x-fold: first', '\t second'); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ 'x-fold': 'first second' }); + }); + + it('should return only the last block when there are 1xx or redirect blocks', () => { + // arrange + const input = Buffer.from( + [ + 'HTTP/1.1 100 Continue', + '', + 'HTTP/1.1 302 Found', + 'location: /next', + 'x-only-first:', + '', + 'HTTP/1.1 200 OK', + 'content-length: 0', + 'x-empty:', + '', + '' + ].join('\r\n'), + 'latin1' + ); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ 'content-length': '0', 'x-empty': '' }); + }); + + it('should accept bare LF line endings', () => { + // arrange + const input = Buffer.from('HTTP/1.1 200 OK\nx-a: 1\nx-b:\n\n'); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ 'x-a': '1', 'x-b': '' }); + }); + + it('should skip lines without a colon', () => { + // arrange + const input = raw('HTTP/1.1 200 OK', 'garbage', 'x-a: 1'); + + // act + const result = CurlHeadersParser.parse(input); + + // assert + expect(result).toEqual({ 'x-a': '1' }); + }); + + it('should return an empty object for an empty buffer', () => { + // act + const result = CurlHeadersParser.parse(Buffer.alloc(0)); + + // assert + expect(result).toEqual({}); + }); + }); +}); diff --git a/src/RequestExecutor/CurlHeadersParser.ts b/src/RequestExecutor/CurlHeadersParser.ts new file mode 100644 index 00000000..f325a954 --- /dev/null +++ b/src/RequestExecutor/CurlHeadersParser.ts @@ -0,0 +1,130 @@ +export type ParsedHeaders = Record; + +/** + * Parses the raw header dump libcurl collects for a transfer (all response + * blocks: 1xx, redirects, final) and returns the fields of the last block. + * + * Not delegated to node-libcurl's `parseHeaders`: it splits on `/:\s(.+)/`, + * which corrupts empty values (`name:`), values without a space after the + * colon, and loses repeated fields. + */ +export class CurlHeadersParser { + // Always an array, even for a single field (RFC 6265 §3: Set-Cookie must not + // be folded), and what consumers have always received. + private static readonly ARRAY_HEADERS: ReadonlySet = new Set([ + 'set-cookie' + ]); + + // Single-valued by definition; consumers (content-type charset detection, + // bridges) expect a string. A duplicate keeps the last value, as before. + // Same set Node's http module collapses. + private static readonly SINGLETON_HEADERS: ReadonlySet = new Set([ + 'age', + 'authorization', + 'content-length', + 'content-type', + 'etag', + 'expires', + 'from', + 'host', + 'if-modified-since', + 'if-unmodified-since', + 'last-modified', + 'location', + 'max-forwards', + 'proxy-authorization', + 'referer', + 'retry-after', + 'server', + 'user-agent' + ]); + + private static readonly UTF8 = new TextDecoder('utf-8', { fatal: true }); + + public static parse(raw: Buffer): ParsedHeaders { + // latin1 maps every byte 1:1, so no byte is lost before values are decoded. + const lines = raw.toString('latin1').split(/\r?\n/); + let block: [string, string][] = []; + let last = block; + + for (const line of lines) { + // "/" is not a token character, so no field name can look like a status line. + if (line.startsWith('HTTP/')) { + block = []; + last = block; + } else if (line !== '') { + CurlHeadersParser.appendField(line, block); + } + } + + return CurlHeadersParser.group(last); + } + + private static appendField(line: string, block: [string, string][]): void { + // Obsolete line folding (RFC 9112 §5.2): the continuation extends the + // previous value, joined by a single space. + if (/^[ \t]/.test(line) && block.length > 0) { + block[block.length - 1][1] += ` ${line.trim()}`; + + return; + } + + const colon = line.indexOf(':'); + if (colon <= 0) { + return; + } + + block.push([ + line.slice(0, colon).trim().toLowerCase(), + line.slice(colon + 1).replace(/^[ \t]+|[ \t]+$/g, '') + ]); + } + + private static group(fields: [string, string][]): ParsedHeaders { + const grouped = new Map(); + + for (const [name, value] of fields) { + const values = grouped.get(name); + if (values) { + values.push(value); + } else { + grouped.set(name, [value]); + } + } + + const result: ParsedHeaders = {}; + for (const [name, rawValues] of grouped) { + const values = rawValues.map((value) => + CurlHeadersParser.decodeValue(value) + ); + + if (CurlHeadersParser.SINGLETON_HEADERS.has(name)) { + result[name] = values[values.length - 1]; + } else if ( + values.length === 1 && + !CurlHeadersParser.ARRAY_HEADERS.has(name) + ) { + result[name] = values[0]; + } else { + result[name] = values; + } + } + + return result; + } + + // The request side sends header strings as UTF-8, so valid UTF-8 must be + // decoded to round-trip. Bytes that are not valid UTF-8 (obs-text) stay as + // latin1 code points instead of becoming U+FFFD. + private static decodeValue(latin1Value: string): string { + if (/^[\t\x20-\x7e]*$/.test(latin1Value)) { + return latin1Value; + } + + try { + return CurlHeadersParser.UTF8.decode(Buffer.from(latin1Value, 'latin1')); + } catch { + return latin1Value; + } + } +} diff --git a/src/RequestExecutor/HttpRequestExecutor.spec.ts b/src/RequestExecutor/HttpRequestExecutor.spec.ts index 6bbdd1f3..cdc83af8 100644 --- a/src/RequestExecutor/HttpRequestExecutor.spec.ts +++ b/src/RequestExecutor/HttpRequestExecutor.spec.ts @@ -17,7 +17,10 @@ import { when } from 'ts-mockito'; import { Curl } from '@brightsec/node-libcurl'; +import forge from 'node-forge'; +import iconv from 'iconv-lite'; import http from 'node:http'; +import http2 from 'node:http2'; import { once } from 'node:events'; import net, { AddressInfo } from 'node:net'; import { promisify } from 'node:util'; @@ -51,6 +54,29 @@ const MAX_MEAN_LATENCY_MS = 50; const serversToClose: http.Server[] = []; +// Generated per run instead of committed: a checked-in private key, even a +// throwaway one, trips secret scanners. 2048-bit RSA because OpenSSL's default +// security level rejects shorter keys. The executor disables peer +// verification, so trust is irrelevant. +const createTestTlsCredentials = (): { key: string; cert: string } => { + const { privateKey, publicKey } = forge.pki.rsa.generateKeyPair(2048); + const cert = forge.pki.createCertificate(); + const subject = [{ name: 'commonName', value: '127.0.0.1' }]; + + cert.publicKey = publicKey; + cert.serialNumber = '01'; + cert.validity.notBefore = new Date(Date.now() - 60_000); + cert.validity.notAfter = new Date(Date.now() + 24 * 60 * 60 * 1000); + cert.setSubject(subject); + cert.setIssuer(subject); + cert.sign(privateKey, forge.md.sha256.create()); + + return { + key: forge.pki.privateKeyToPem(privateKey), + cert: forge.pki.certificateToPem(cert) + }; +}; + async function startServer( handler?: (req: http.IncomingMessage, res: http.ServerResponse) => void ): Promise<{ @@ -2286,5 +2312,119 @@ describe('HttpRequestExecutor', () => { withinBudget: mean < MAX_MEAN_LATENCY_MS }).toEqual(expect.objectContaining({ withinBudget: true })); }, 60000); + + const expectWellFormed = (headers: Record) => { + for (const [name, value] of Object.entries(headers)) { + expect(name).not.toMatch(/[:\s]/); + for (const v of Array.isArray(value) ? value : [value]) { + expect(typeof v).toBe('string'); + } + } + }; + + it('should deliver empty header values from an HTTP/1.1 target as empty strings', async () => { + // arrange + const server = net.createServer((socket) => + socket.on('data', () => { + socket.write( + 'HTTP/1.1 200 OK\r\nexpires:\r\ncache-control: \r\npragma:\r\nx-nospace:value\r\nx-padded: value \r\nlink: \r\nlink: \r\nContent-Length: 0\r\nConnection: close\r\n\r\n' + ); + socket.end(); + }) + ); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const { port } = server.address() as AddressInfo; + const { request } = createRequest({ url: `http://127.0.0.1:${port}/` }); + const sut = buildSut({ timeout: 5000 }); + + try { + // act + const response = await sut.execute(request); + + // assert + expect(response.headers).toMatchObject({ + 'expires': '', + 'cache-control': '', + 'pragma': '', + 'x-nospace': 'value', + 'x-padded': 'value', + 'link': ['', ''] + }); + expectWellFormed(response.headers ?? {}); + } finally { + server.close(); + } + }); + + it('should decode the body with the charset of a duplicated content-type header', async () => { + // arrange + const body = iconv.encode('Привет', 'windows-1251'); + const server = net.createServer((socket) => + socket.on('data', () => { + socket.write( + `HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=windows-1251\r\nContent-Type: text/html; charset=windows-1251\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n` + ); + socket.end(body); + }) + ); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const { port } = server.address() as AddressInfo; + const { request } = createRequest({ url: `http://127.0.0.1:${port}/` }); + const sut = buildSut({ timeout: 5000 }); + + try { + // act + const response = await sut.execute(request); + + // assert + expect(response.headers?.['content-type']).toBe( + 'text/html; charset=windows-1251' + ); + expect(response.body).toBe('Привет'); + } finally { + server.close(); + } + }); + + it('should deliver empty header values from an HTTP/2 TLS target as empty strings', async () => { + // arrange + const server = http2.createSecureServer(createTestTlsCredentials()); + server.on('stream', (stream) => { + stream.respond({ + ':status': 200, + 'expires': '', + 'cache-control': '', + 'pragma': '', + 'set-cookie': ['a=1; Path=/', 'b=2'] + }); + stream.end(); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const { port } = server.address() as AddressInfo; + const { request } = createRequest({ + url: `https://127.0.0.1:${port}/` + }); + const sut = buildSut({ timeout: 5000 }); + + try { + // act + const response = await sut.execute(request); + + // assert + expect(response.statusCode).toBe(200); + expect(response.headers).toMatchObject({ + 'expires': '', + 'cache-control': '', + 'pragma': '', + 'set-cookie': ['a=1; Path=/', 'b=2'] + }); + expectWellFormed(response.headers ?? {}); + } finally { + server.close(); + } + }); }); }); diff --git a/src/RequestExecutor/HttpRequestExecutor.ts b/src/RequestExecutor/HttpRequestExecutor.ts index bb5dc641..127d3f42 100644 --- a/src/RequestExecutor/HttpRequestExecutor.ts +++ b/src/RequestExecutor/HttpRequestExecutor.ts @@ -10,6 +10,7 @@ import { CertificatesResolver } from './CertificatesResolver'; import { CurlSeekResult } from './CurlSeekResult'; import { CurlSeekOrigin } from './CurlSeekOrigin'; import { CurlErrorMapper } from './CurlErrorMapper'; +import { CurlHeadersParser } from './CurlHeadersParser'; import { inject, injectable } from 'tsyringe'; import iconv from 'iconv-lite'; import { safeParse } from 'fast-content-type-parse'; @@ -18,7 +19,6 @@ import { CurlAuth, CurlFeature, CurlGssApi, - HeaderInfo, Multi } from '@brightsec/node-libcurl'; import { parse as parseUrl } from 'node:url'; @@ -148,11 +148,11 @@ export class HttpRequestExecutor implements RequestExecutor { curl.on( 'end', - (statusCode: number, rawBody: Buffer, rawHeaders: HeaderInfo[]) => { + (statusCode: number, rawBody: Buffer, rawHeaders: Buffer) => { const ttfbUs = curl.getInfo('STARTTRANSFER_TIME_T') as number; const ttfb = Math.round(ttfbUs / 1000); - const headers = this.parseCurlHeaders(rawHeaders); + const headers = CurlHeadersParser.parse(rawHeaders); setImmediate(() => curl.close()); @@ -184,6 +184,7 @@ export class HttpRequestExecutor implements RequestExecutor { private configureCurl(curl: Curl, options: Request): void { curl.enable(CurlFeature.NoDataParsing); + curl.enable(CurlFeature.NoHeaderParsing); const { protocol, host, auth } = parseUrl(options.url); curl.setOpt('URL', `${protocol}//${host}`); @@ -390,21 +391,6 @@ export class HttpRequestExecutor implements RequestExecutor { return lines; } - private parseCurlHeaders( - rawHeaders: HeaderInfo[] - ): Record { - const lastHeaders = rawHeaders[rawHeaders.length - 1] ?? {}; - const result: Record = {}; - - for (const [key, val] of Object.entries(lastHeaders)) { - if (key === 'result') continue; - - result[key.toLowerCase()] = val as string; - } - - return result; - } - private resolveProxy(options: Request): string | undefined { const hostname = parseUrl(options.url).hostname;