Skip to content

Commit 4b76cce

Browse files
authored
http: preserve raw header duplicates in writeHead after setHeader calls
writeHead accepts a raw header array, which is intended to allow directly specifying raw header details, such as ordering, duplicates and header key casing. When used by itself this works correctly. However, if setHeader was called first, it effectively changed the behaviour of subsequent writeHead calls, so that even if a raw header array was provided, duplicates were collapsed, losing raw header data. This change preserves the raw headers passed to writeHead, while still maintaining the 'writeHead overwrites setHeader' behaviour. PR-URL: #50394 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 99f6084 commit 4b76cce

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

lib/_http_server.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -373,9 +373,18 @@ function writeHead(statusCode, reason, obj) {
373373
throw new ERR_INVALID_ARG_VALUE('headers', obj);
374374
}
375375

376+
// Headers in obj should override previous headers but still
377+
// allow explicit duplicates. To do so, we first remove any
378+
// existing conflicts, then use appendHeader.
379+
380+
for (let n = 0; n < obj.length; n += 2) {
381+
k = obj[n + 0];
382+
this.removeHeader(k);
383+
}
384+
376385
for (let n = 0; n < obj.length; n += 2) {
377386
k = obj[n + 0];
378-
if (k) this.setHeader(k, obj[n + 1]);
387+
if (k) this.appendHeader(k, obj[n + 1]);
379388
}
380389
} else if (obj) {
381390
const keys = ObjectKeys(obj);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const Countdown = require('../common/countdown');
5+
const assert = require('assert');
6+
const { createServer, request } = require('http');
7+
8+
const server = createServer(common.mustCall((req, res) => {
9+
if (req.url.includes('setHeader')) {
10+
res.setHeader('set-val', 'abc');
11+
}
12+
13+
res.writeHead(200, [
14+
'array-val', '1',
15+
'array-val', '2',
16+
]);
17+
18+
res.end();
19+
}, 2));
20+
21+
const countdown = new Countdown(2, () => server.close());
22+
23+
server.listen(0, common.mustCall(() => {
24+
request({
25+
port: server.address().port
26+
}, common.mustCall((res) => {
27+
assert.deepStrictEqual(res.rawHeaders.slice(0, 4), [
28+
'array-val', '1',
29+
'array-val', '2',
30+
]);
31+
32+
countdown.dec();
33+
})).end();
34+
35+
request({
36+
port: server.address().port,
37+
path: '/?setHeader'
38+
}, common.mustCall((res) => {
39+
assert.deepStrictEqual(res.rawHeaders.slice(0, 6), [
40+
'set-val', 'abc',
41+
'array-val', '1',
42+
'array-val', '2',
43+
]);
44+
45+
countdown.dec();
46+
})).end();
47+
}));

0 commit comments

Comments
 (0)