Skip to content

Commit

Permalink
Duplicate header handling (#874)
Browse files Browse the repository at this point in the history
* Update parseHeaders to match node http behavior

Node ignores duplicate entries for certain HTTP headers.

It also always converts the `set-cookie` header into an array.

* add tests for new duplicate header handling

* clarify comment
  • Loading branch information
tybro0103 authored and rubennorte committed Aug 12, 2017
1 parent 2b85626 commit fb08e95
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
18 changes: 17 additions & 1 deletion lib/helpers/parseHeaders.js
Expand Up @@ -2,6 +2,15 @@

var utils = require('./../utils');

// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'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', 'user-agent'
];

/**
* Parse headers into an object
*
Expand Down Expand Up @@ -29,7 +38,14 @@ module.exports = function parseHeaders(headers) {
val = utils.trim(line.substr(i + 1));

if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});

Expand Down
28 changes: 27 additions & 1 deletion test/specs/helpers/parseHeaders.spec.js
Expand Up @@ -15,5 +15,31 @@ describe('helpers::parseHeaders', function () {
expect(parsed['connection']).toEqual('keep-alive');
expect(parsed['transfer-encoding']).toEqual('chunked');
});
});

it('should use array for set-cookie', function() {
var parsedZero = parseHeaders('');
var parsedSingle = parseHeaders(
'Set-Cookie: key=val;'
);
var parsedMulti = parseHeaders(
'Set-Cookie: key=val;\n' +
'Set-Cookie: key2=val2;\n'
);

expect(parsedZero['set-cookie']).toBeUndefined();
expect(parsedSingle['set-cookie']).toEqual(['key=val;']);
expect(parsedMulti['set-cookie']).toEqual(['key=val;', 'key2=val2;']);
});

it('should handle duplicates', function() {
var parsed = parseHeaders(
'Age: age-a\n' + // age is in ignore duplicates blacklist
'Age: age-b\n' +
'Foo: foo-a\n' +
'Foo: foo-b\n'
);

expect(parsed['age']).toEqual('age-a');
expect(parsed['foo']).toEqual('foo-a, foo-b');
});
});

0 comments on commit fb08e95

Please sign in to comment.