GeezerVison is showing github.com — http: add isValidHeaderName() and isValidHeaderValue() · nodejs/node@2df322a
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: doc/api/http.md +86Lines changed: 86 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -4350,6 +4350,89 @@ request. Specifically, the `'error'` event will be emitted with an error with | 4350 | 4350 | the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` | 4351 | 4351 | and the `cause`, if one was provided. | 4352 | 4352 |
| | 4353 | +## `http.isValidHeaderName(name)` | | 4354 | +
| | 4355 | +<!-- YAML | | 4356 | +added: REPLACEME | | 4357 | +--> | | 4358 | +
| | 4359 | +* `name` {any} | | 4360 | +* Returns: {boolean} | | 4361 | +
| | 4362 | +Returns `true` if `name` is a valid HTTP header name (a non-empty string that | | 4363 | +is an HTTP [token][]), and `false` otherwise. This is the same check that | | 4364 | +[`http.validateHeaderName()`][] performs, but the result is returned instead of | | 4365 | +an error being thrown, so it is suitable for use in hot paths where invalid | | 4366 | +input is expected. | | 4367 | +
| | 4368 | +HTTP methods are also tokens, so this function can validate them as well. | | 4369 | +
| | 4370 | +```mjs | | 4371 | +import { isValidHeaderName } from 'node:http'; | | 4372 | +
| | 4373 | +console.log(isValidHeaderName('content-type')); // true | | 4374 | +console.log(isValidHeaderName('X-Request-Id')); // true | | 4375 | +console.log(isValidHeaderName('')); // false | | 4376 | +console.log(isValidHeaderName('bad header')); // false | | 4377 | +console.log(isValidHeaderName(42)); // false | | 4378 | +``` | | 4379 | +
| | 4380 | +```cjs | | 4381 | +const { isValidHeaderName } = require('node:http'); | | 4382 | +
| | 4383 | +console.log(isValidHeaderName('content-type')); // true | | 4384 | +console.log(isValidHeaderName('X-Request-Id')); // true | | 4385 | +console.log(isValidHeaderName('')); // false | | 4386 | +console.log(isValidHeaderName('bad header')); // false | | 4387 | +console.log(isValidHeaderName(42)); // false | | 4388 | +``` | | 4389 | +
| | 4390 | +## `http.isValidHeaderValue(value[, options])` | | 4391 | +
| | 4392 | +<!-- YAML | | 4393 | +added: REPLACEME | | 4394 | +--> | | 4395 | +
| | 4396 | +* `value` {any} | | 4397 | +* `options` {Object} | | 4398 | + * `httpValidation` {string} Validation strictness, one of `'strict'` or | | 4399 | + `'relaxed'`. These have the same meaning as the `httpValidation` option of | | 4400 | + [`http.createServer()`][] and [`http.request()`][]. **Default:** `'strict'`. | | 4401 | +* Returns: {boolean} | | 4402 | +
| | 4403 | +Returns `true` if `value` is a valid HTTP header value, and `false` otherwise. | | 4404 | +With the default options this is the same check that | | 4405 | +[`http.validateHeaderValue()`][] performs, but the result is returned instead | | 4406 | +of an error being thrown. | | 4407 | +
| | 4408 | +`undefined` and symbols are never valid header values. Other non-string | | 4409 | +values are converted to strings before being checked, as they are when passed | | 4410 | +to [`outgoingMessage.setHeader(name, value)`][]. | | 4411 | +
| | 4412 | +Passing an invalid `options` argument throws. | | 4413 | +
| | 4414 | +```mjs | | 4415 | +import { isValidHeaderValue } from 'node:http'; | | 4416 | +
| | 4417 | +console.log(isValidHeaderValue('text/html')); // true | | 4418 | +console.log(isValidHeaderValue(123)); // true | | 4419 | +console.log(isValidHeaderValue(undefined)); // false | | 4420 | +console.log(isValidHeaderValue('a\r\nb')); // false | | 4421 | +console.log(isValidHeaderValue('a\x01b')); // false | | 4422 | +console.log(isValidHeaderValue('a\x01b', { httpValidation: 'relaxed' })); // true | | 4423 | +``` | | 4424 | +
| | 4425 | +```cjs | | 4426 | +const { isValidHeaderValue } = require('node:http'); | | 4427 | +
| | 4428 | +console.log(isValidHeaderValue('text/html')); // true | | 4429 | +console.log(isValidHeaderValue(123)); // true | | 4430 | +console.log(isValidHeaderValue(undefined)); // false | | 4431 | +console.log(isValidHeaderValue('a\r\nb')); // false | | 4432 | +console.log(isValidHeaderValue('a\x01b')); // false | | 4433 | +console.log(isValidHeaderValue('a\x01b', { httpValidation: 'relaxed' })); // true | | 4434 | +``` | | 4435 | +
| 4353 | 4436 | ## `http.validateHeaderName(name[, label])` | 4354 | 4437 |
| 4355 | 4438 | <!-- YAML | @@ -4739,6 +4822,8 @@ const agent2 = new http.Agent({ proxyEnv: process.env }); | 4739 | 4822 | [`http.globalAgent`]: #httpglobalagent | 4740 | 4823 | [`http.request()`]: #httprequestoptions-callback | 4741 | 4824 | [`http.setGlobalProxyFromEnv()`]: #httpsetglobalproxyfromenvproxyenv | | 4825 | +[`http.validateHeaderName()`]: #httpvalidateheadernamename-label | | 4826 | +[`http.validateHeaderValue()`]: #httpvalidateheadervaluename-value | 4742 | 4827 | [`message.headers`]: #messageheaders | 4743 | 4828 | [`message.rawHeaders`]: #messagerawheaders | 4744 | 4829 | [`message.socket`]: #messagesocket | @@ -4801,3 +4886,4 @@ const agent2 = new http.Agent({ proxyEnv: process.env }); | 4801 | 4886 | [information event]: #event-information | 4802 | 4887 | [initial delay]: net.md#socketsetkeepaliveenable-initialdelay-interval-count | 4803 | 4888 | [request target]: https://datatracker.ietf.org/doc/html/rfc9112#section-3.2 | | 4889 | +[token]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2 |
Collapse file Copy file name to clipboardExpand all lines: lib/_http_outgoing.js +42-2Lines changed: 42 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -71,7 +71,11 @@ const { | 71 | 71 | }, | 72 | 72 | hideStackFrames, | 73 | 73 | } = require('internal/errors'); | 74 | | -const { validateString } = require('internal/validators'); | | 74 | +const { | | 75 | + validateObject, | | 76 | + validateOneOf, | | 77 | + validateString, | | 78 | +} = require('internal/validators'); | 75 | 79 | const { assignFunctionName } = require('internal/util'); | 76 | 80 | const { isUint8Array } = require('internal/util/types'); | 77 | 81 |
| @@ -716,11 +720,45 @@ function matchHeader(self, state, field, value) { | 716 | 720 | } | 717 | 721 |
| 718 | 722 | const validateHeaderName = assignFunctionName('validateHeaderName', hideStackFrames((name, label) => { | 719 | | - if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) { | | 723 | + if (!isValidHeaderName(name)) { | 720 | 724 | throw new ERR_INVALID_HTTP_TOKEN.HideStackFramesError(label || 'Header name', name); | 721 | 725 | } | 722 | 726 | })); | 723 | 727 |
| | 728 | +/** | | 729 | + * Non-throwing counterpart of `validateHeaderName()`. | | 730 | + * @param {any} name | | 731 | + * @returns {boolean} | | 732 | + */ | | 733 | +function isValidHeaderName(name) { | | 734 | + return typeof name === 'string' && checkIsHttpToken(name); | | 735 | +} | | 736 | + | | 737 | +const kHttpValidationValues = ['strict', 'relaxed']; | | 738 | + | | 739 | +/** | | 740 | + * Non-throwing counterpart of `validateHeaderValue()`. | | 741 | + * @param {any} value | | 742 | + * @param {{ httpValidation?: 'strict' | 'relaxed' }} [options] | | 743 | + * @returns {boolean} | | 744 | + */ | | 745 | +function isValidHeaderValue(value, options) { | | 746 | + let lenient = false; | | 747 | + if (options !== undefined) { | | 748 | + validateObject(options, 'options'); | | 749 | + const { httpValidation } = options; | | 750 | + if (httpValidation === 'relaxed') { | | 751 | + lenient = true; | | 752 | + } else if (httpValidation !== undefined && httpValidation !== 'strict') { | | 753 | + validateOneOf(httpValidation, 'options.httpValidation', kHttpValidationValues); | | 754 | + } | | 755 | + } | | 756 | + if (value === undefined || typeof value === 'symbol') { | | 757 | + return false; | | 758 | + } | | 759 | + return !checkInvalidHeaderChar(value, lenient); | | 760 | +} | | 761 | + | 724 | 762 | const validateHeaderValue = assignFunctionName('validateHeaderValue', hideStackFrames((name, value, lenient) => { | 725 | 763 | if (value === undefined) { | 726 | 764 | throw new ERR_HTTP_INVALID_HEADER_VALUE.HideStackFramesError(value, name); | @@ -1413,6 +1451,8 @@ module.exports = { | 1413 | 1451 | kHighWaterMark, | 1414 | 1452 | kUniqueHeaders, | 1415 | 1453 | parseUniqueHeadersOption, | | 1454 | + isValidHeaderName, | | 1455 | + isValidHeaderValue, | 1416 | 1456 | validateHeaderName, | 1417 | 1457 | validateHeaderValue, | 1418 | 1458 | OutgoingMessage, | |
Collapse file Copy file name to clipboardExpand all lines: lib/http.js +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -32,6 +32,8 @@ const { methods, parsers } = require('_http_common'); | 32 | 32 | const { IncomingMessage } = require('_http_incoming'); | 33 | 33 | const { ERR_PROXY_INVALID_CONFIG } = require('internal/errors').codes; | 34 | 34 | const { | | 35 | + isValidHeaderName, | | 36 | + isValidHeaderValue, | 35 | 37 | validateHeaderName, | 36 | 38 | validateHeaderValue, | 37 | 39 | OutgoingMessage, | @@ -193,6 +195,8 @@ module.exports = { | 193 | 195 | Server, | 194 | 196 | ServerResponse, | 195 | 197 | createServer, | | 198 | + isValidHeaderName, | | 199 | + isValidHeaderValue, | 196 | 200 | validateHeaderName, | 197 | 201 | validateHeaderValue, | 198 | 202 | get, | |
Collapse file Copy file name to clipboard +168Lines changed: 168 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | +require('../common'); | | 3 | +const assert = require('assert'); | | 4 | +const { | | 5 | + isValidHeaderName, | | 6 | + isValidHeaderValue, | | 7 | + validateHeaderName, | | 8 | + validateHeaderValue, | | 9 | +} = require('http'); | | 10 | + | | 11 | +function succeeds(fn) { | | 12 | + try { | | 13 | + fn(); | | 14 | + return true; | | 15 | + } catch { | | 16 | + return false; | | 17 | + } | | 18 | +} | | 19 | + | | 20 | +// isValidHeaderName | | 21 | +{ | | 22 | + const valid = [ | | 23 | + 'a', | | 24 | + 'user-agent', | | 25 | + 'USER-AGENT', | | 26 | + 'User-Agent', | | 27 | + 'x-forwarded-for', | | 28 | + 'x-request-id-with-a-long-name', | | 29 | + "!#$%&'*+-.^_`|~", | | 30 | + '0123456789', | | 31 | + ]; | | 32 | + const invalid = [ | | 33 | + '', | | 34 | + ' ', | | 35 | + 'bad header', | | 36 | + 'bad:header', | | 37 | + 'x-forwarded-fםr', | | 38 | + 'איקס-פורוורד-פור', | | 39 | + 'x\r\ny', | | 40 | + 'x\0', | | 41 | + '(comment)', | | 42 | + '"quoted"', | | 43 | + 'a,b', | | 44 | + 'long-invalid-header-name\u00e9', | | 45 | + ]; | | 46 | + const nonStrings = [ | | 47 | + undefined, null, 0, 1, true, false, {}, [], ['a'], | | 48 | + Symbol('a'), () => {}, 1n, Buffer.from('a'), | | 49 | + ]; | | 50 | + | | 51 | + for (const name of valid) { | | 52 | + assert.strictEqual(isValidHeaderName(name), true, name); | | 53 | + } | | 54 | + for (const name of [...invalid, ...nonStrings]) { | | 55 | + assert.strictEqual(isValidHeaderName(name), false, String(name?.toString?.())); | | 56 | + } | | 57 | + | | 58 | + // Must agree with validateHeaderName() for every input. | | 59 | + for (const name of [...valid, ...invalid, ...nonStrings]) { | | 60 | + assert.strictEqual( | | 61 | + isValidHeaderName(name), | | 62 | + succeeds(() => validateHeaderName(name)), | | 63 | + ); | | 64 | + } | | 65 | + | | 66 | + // Every single-character name agrees with validateHeaderName(), for both | | 67 | + // the short (lookup table) and long (regexp) code paths. | | 68 | + for (let c = 0; c <= 0x10ff; c++) { | | 69 | + const ch = String.fromCharCode(c); | | 70 | + for (const name of [ch, `${ch}xxxxxxxxxxxx`]) { | | 71 | + assert.strictEqual( | | 72 | + isValidHeaderName(name), | | 73 | + succeeds(() => validateHeaderName(name)), | | 74 | + `char code ${c}`, | | 75 | + ); | | 76 | + } | | 77 | + } | | 78 | +} | | 79 | + | | 80 | +// isValidHeaderValue | | 81 | +{ | | 82 | + const valid = [ | | 83 | + '', | | 84 | + 'text/html', | | 85 | + 'a b\tc', | | 86 | + '\u00e9\u00ff', | | 87 | + '\x80', | | 88 | + 1, | | 89 | + 0, | | 90 | + null, | | 91 | + true, | | 92 | + ['a', 'b'], | | 93 | + ]; | | 94 | + const invalid = [ | | 95 | + undefined, | | 96 | + 'a\r\nb', | | 97 | + 'a\nb', | | 98 | + 'a\rb', | | 99 | + 'a\0b', | | 100 | + 'a\x01b', | | 101 | + 'a\x7fb', | | 102 | + 'לא תקין', | | 103 | + '\u0100', | | 104 | + ['a', 'b\n'], | | 105 | + Symbol('a'), | | 106 | + ]; | | 107 | + | | 108 | + for (const value of valid) { | | 109 | + assert.strictEqual(isValidHeaderValue(value), true, String(value)); | | 110 | + } | | 111 | + for (const value of invalid) { | | 112 | + assert.strictEqual(isValidHeaderValue(value), false, String(value)); | | 113 | + } | | 114 | + | | 115 | + // Must agree with validateHeaderValue() for every input. | | 116 | + for (const value of [...valid, ...invalid]) { | | 117 | + assert.strictEqual( | | 118 | + isValidHeaderValue(value), | | 119 | + succeeds(() => validateHeaderValue('x-test', value)), | | 120 | + ); | | 121 | + } | | 122 | + | | 123 | + for (let c = 0; c <= 0x10ff; c++) { | | 124 | + const value = `a${String.fromCharCode(c)}b`; | | 125 | + assert.strictEqual( | | 126 | + isValidHeaderValue(value), | | 127 | + succeeds(() => validateHeaderValue('x-test', value)), | | 128 | + `char code ${c}`, | | 129 | + ); | | 130 | + // Explicit 'strict' is the same as the default. | | 131 | + assert.strictEqual( | | 132 | + isValidHeaderValue(value, { httpValidation: 'strict' }), | | 133 | + isValidHeaderValue(value), | | 134 | + `char code ${c}`, | | 135 | + ); | | 136 | + } | | 137 | + | | 138 | + // 'relaxed' follows the Fetch spec: only NUL, CR, LF and code points above | | 139 | + // U+00FF are rejected. | | 140 | + const relaxed = { httpValidation: 'relaxed' }; | | 141 | + for (let c = 0; c <= 0x10ff; c++) { | | 142 | + const expected = !(c === 0x00 || c === 0x0a || c === 0x0d || c > 0xff); | | 143 | + assert.strictEqual( | | 144 | + isValidHeaderValue(`a${String.fromCharCode(c)}b`, relaxed), | | 145 | + expected, | | 146 | + `char code ${c}`, | | 147 | + ); | | 148 | + } | | 149 | + assert.strictEqual(isValidHeaderValue(undefined, relaxed), false); | | 150 | + assert.strictEqual(isValidHeaderValue('a\x01b', relaxed), true); | | 151 | + assert.strictEqual(isValidHeaderValue('a\x7fb', relaxed), true); | | 152 | + | | 153 | + // An empty options object uses the default. | | 154 | + assert.strictEqual(isValidHeaderValue('a\x01b', {}), false); | | 155 | + assert.strictEqual(isValidHeaderValue('a\x01b', { httpValidation: undefined }), false); | | 156 | + | | 157 | + // Invalid options throw. | | 158 | + for (const options of [null, 1, 'relaxed', true]) { | | 159 | + assert.throws(() => isValidHeaderValue('a', options), { | | 160 | + code: 'ERR_INVALID_ARG_TYPE', | | 161 | + }); | | 162 | + } | | 163 | + for (const httpValidation of ['insecure', 'RELAXED', '', 1, null]) { | | 164 | + assert.throws(() => isValidHeaderValue('a', { httpValidation }), { | | 165 | + code: 'ERR_INVALID_ARG_VALUE', | | 166 | + }); | | 167 | + } | | 168 | +} |
|