Skip to content

Commit

Permalink
http: preserve raw header duplicates in writeHead after setHeader calls
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
pimterry authored Dec 14, 2023
1 parent 99f6084 commit 4b76cce
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/_http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,9 +373,18 @@ function writeHead(statusCode, reason, obj) {
throw new ERR_INVALID_ARG_VALUE('headers', obj);
}

// Headers in obj should override previous headers but still
// allow explicit duplicates. To do so, we first remove any
// existing conflicts, then use appendHeader.

for (let n = 0; n < obj.length; n += 2) {
k = obj[n + 0];
this.removeHeader(k);
}

for (let n = 0; n < obj.length; n += 2) {
k = obj[n + 0];
if (k) this.setHeader(k, obj[n + 1]);
if (k) this.appendHeader(k, obj[n + 1]);
}
} else if (obj) {
const keys = ObjectKeys(obj);
Expand Down
47 changes: 47 additions & 0 deletions test/parallel/test-http-write-head-after-set-header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'use strict';

const common = require('../common');
const Countdown = require('../common/countdown');
const assert = require('assert');
const { createServer, request } = require('http');

const server = createServer(common.mustCall((req, res) => {
if (req.url.includes('setHeader')) {
res.setHeader('set-val', 'abc');
}

res.writeHead(200, [
'array-val', '1',
'array-val', '2',
]);

res.end();
}, 2));

const countdown = new Countdown(2, () => server.close());

server.listen(0, common.mustCall(() => {
request({
port: server.address().port
}, common.mustCall((res) => {
assert.deepStrictEqual(res.rawHeaders.slice(0, 4), [
'array-val', '1',
'array-val', '2',
]);

countdown.dec();
})).end();

request({
port: server.address().port,
path: '/?setHeader'
}, common.mustCall((res) => {
assert.deepStrictEqual(res.rawHeaders.slice(0, 6), [
'set-val', 'abc',
'array-val', '1',
'array-val', '2',
]);

countdown.dec();
})).end();
}));

0 comments on commit 4b76cce

Please sign in to comment.