Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions lib/_http_common.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,17 +256,31 @@ function checkIsHttpToken(val) {
return true;
}

const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
// Strict header value regex per RFC 7230:
// field-value = *( field-content / obs-fold )
// field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
// field-vchar = VCHAR / obs-text
// This rejects control characters (0x00-0x1f except HTAB) and DEL (0x7f).
const strictHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;

// Lenient header value regex per Fetch spec (https://fetch.spec.whatwg.org/#header-value):
// - Must contain no 0x00 (NUL) or HTTP newline bytes (0x0a LF, 0x0d CR)
// - Must be byte sequences (0x00-0xff), not arbitrary unicode
// This allows most control characters except NUL, CR, and LF.
// eslint-disable-next-line no-control-regex
const lenientHeaderCharRegex = /[\x00\x0a\x0d]|[^\x00-\xff]/;

/**
* True if val contains an invalid field-vchar
* field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* True if val contains an invalid header value character.
* By default uses strict validation per RFC 7230.
* When lenient=true, uses relaxed validation per Fetch spec.
* @param {string} val
* @param {boolean} [lenient=false] - Use lenient validation (Fetch spec rules)
* @returns {boolean}
*/
function checkInvalidHeaderChar(val) {
return headerCharRegex.test(val);
function checkInvalidHeaderChar(val, lenient = false) {
const regex = lenient ? lenientHeaderCharRegex : strictHeaderCharRegex;
return regex.test(val);
}

function cleanParser(parser) {
Expand Down
39 changes: 35 additions & 4 deletions lib/_http_outgoing.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const {
_checkIsHttpToken: checkIsHttpToken,
_checkInvalidHeaderChar: checkInvalidHeaderChar,
chunkExpression: RE_TE_CHUNKED,
isLenient,
} = require('_http_common');
const {
defaultTriggerAsyncIdScope,
Expand Down Expand Up @@ -158,6 +159,23 @@ function OutgoingMessage(options) {
ObjectSetPrototypeOf(OutgoingMessage.prototype, Stream.prototype);
ObjectSetPrototypeOf(OutgoingMessage, Stream);

// Check if lenient header validation should be used.
// For ClientRequest: checks this.insecureHTTPParser
// For ServerResponse: checks the server's insecureHTTPParser
// Falls back to global --insecure-http-parser flag.
OutgoingMessage.prototype._isLenientHeaderValidation = function() {
// ClientRequest has insecureHTTPParser directly
if (this.insecureHTTPParser !== undefined) {
return this.insecureHTTPParser;
}
// ServerResponse can access via req.socket.server
if (this.req?.socket?.server?.insecureHTTPParser !== undefined) {
return this.req.socket.server.insecureHTTPParser;
}
// Fall back to global option
return isLenient();
};

ObjectDefineProperty(OutgoingMessage.prototype, 'errored', {
__proto__: null,
get() {
Expand Down Expand Up @@ -642,7 +660,13 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
throw new ERR_HTTP_HEADERS_SENT('set');
}
validateHeaderName(name);
validateHeaderValue(name, value);
if (value === undefined) {
throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name);
}
if (checkInvalidHeaderChar(value, this._isLenientHeaderValidation())) {
debug('Header "%s" contains invalid characters', name);
throw new ERR_INVALID_CHAR('header content', name);
}

let headers = this[kOutHeaders];
if (headers === null)
Expand Down Expand Up @@ -700,7 +724,13 @@ OutgoingMessage.prototype.appendHeader = function appendHeader(name, value) {
throw new ERR_HTTP_HEADERS_SENT('append');
}
validateHeaderName(name);
validateHeaderValue(name, value);
if (value === undefined) {
throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name);
}
if (checkInvalidHeaderChar(value, this._isLenientHeaderValidation())) {
debug('Header "%s" contains invalid characters', name);
throw new ERR_INVALID_CHAR('header content', name);
}

const field = name.toLowerCase();
const headers = this[kOutHeaders];
Expand Down Expand Up @@ -996,12 +1026,13 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {

// Check if the field must be sent several times
const isArrayValue = ArrayIsArray(value);
const lenient = this._isLenientHeaderValidation();
if (
isArrayValue && value.length > 1 &&
(!this[kUniqueHeaders] || !this[kUniqueHeaders].has(field.toLowerCase()))
) {
for (let j = 0, l = value.length; j < l; j++) {
if (checkInvalidHeaderChar(value[j])) {
if (checkInvalidHeaderChar(value[j], lenient)) {
debug('Trailer "%s"[%d] contains invalid characters', field, j);
throw new ERR_INVALID_CHAR('trailer content', field);
}
Expand All @@ -1012,7 +1043,7 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
value = value.join('; ');
}

if (checkInvalidHeaderChar(value)) {
if (checkInvalidHeaderChar(value, lenient)) {
debug('Trailer "%s" contains invalid characters', field);
throw new ERR_INVALID_CHAR('trailer content', field);
}
Expand Down
73 changes: 60 additions & 13 deletions test/parallel/test-http-invalidheaderfield2.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,30 +59,77 @@ const { _checkIsHttpToken, _checkInvalidHeaderChar } = require('_http_common');
});


// Good header field values
// ============================================================================
// Strict header value validation (default) - per RFC 7230
// Rejects control characters (0x00-0x1f except HTAB) and DEL (0x7f)
// ============================================================================

// Good header field values in strict mode
[
'foo bar',
'foo\tbar',
'foo\tbar', // HTAB is allowed
'0123456789ABCdef',
'!@#$%^&*()-_=+\\;\':"[]{}<>,./?|~`',
'\x80\x81\xff', // obs-text (0x80-0xff) is allowed
].forEach(function(str) {
assert.strictEqual(
_checkInvalidHeaderChar(str), false,
`_checkInvalidHeaderChar(${inspect(str)}) unexpectedly failed`);
`_checkInvalidHeaderChar(${inspect(str)}) unexpectedly failed in strict mode`);
});

// Bad header field values
// Bad header field values in strict mode
// Control characters (except HTAB) and DEL are rejected
[
'foo\rbar',
'foo\nbar',
'foo\r\nbar',
'中文呢', // unicode
'\x7FMe!',
'Testing 123\x00',
'foo\vbar',
'Ding!\x07',
'foo\x00bar', // NUL
'foo\x01bar', // SOH
'foo\rbar', // CR
'foo\nbar', // LF
'foo\r\nbar', // CRLF
'foo\x7Fbar', // DEL
'中文呢', // unicode > 0xff
].forEach(function(str) {
assert.strictEqual(
_checkInvalidHeaderChar(str), true,
`_checkInvalidHeaderChar(${inspect(str)}) unexpectedly succeeded`);
`_checkInvalidHeaderChar(${inspect(str)}) unexpectedly succeeded in strict mode`);
});


// ============================================================================
// Lenient header value validation (with insecureHTTPParser) - per Fetch spec
// Only NUL (0x00), CR (0x0d), LF (0x0a), and chars > 0xff are rejected
// ============================================================================

// Good header field values in lenient mode
// CTL characters (except NUL, LF, CR) are valid per Fetch spec
[
'foo bar',
'foo\tbar',
'0123456789ABCdef',
'!@#$%^&*()-_=+\\;\':"[]{}<>,./?|~`',
'\x01\x02\x03\x04\x05\x06\x07\x08', // 0x01-0x08
'foo\x0bbar', // VT (0x0b)
'foo\x0cbar', // FF (0x0c)
'\x0e\x0f\x10\x11\x12\x13\x14\x15', // 0x0e-0x15
'\x16\x17\x18\x19\x1a\x1b\x1c\x1d', // 0x16-0x1d
'\x1e\x1f', // 0x1e-0x1f
'\x7FMe!', // DEL (0x7f)
'\x80\x81\xff', // obs-text (0x80-0xff)
].forEach(function(str) {
assert.strictEqual(
_checkInvalidHeaderChar(str, true), false,
`_checkInvalidHeaderChar(${inspect(str)}, true) unexpectedly failed in lenient mode`);
});

// Bad header field values in lenient mode
// Only NUL (0x00), LF (0x0a), CR (0x0d), and characters > 0xff are invalid
[
'foo\rbar', // CR (0x0d)
'foo\nbar', // LF (0x0a)
'foo\r\nbar', // CRLF
'中文呢', // unicode > 0xff
'Testing 123\x00', // NUL (0x00)
].forEach(function(str) {
assert.strictEqual(
_checkInvalidHeaderChar(str, true), true,
`_checkInvalidHeaderChar(${inspect(str)}, true) unexpectedly succeeded in lenient mode`);
});