Skip to content

Commit 656d78d

Browse files
bengladuh95
authored andcommitted
http2: allow client request header injection via diagnostics_channel
The http2.client.stream.created and http2.client.stream.start channels publish the stream's sentHeaders object, but by that point the request headers have already been serialized in ClientHttp2Session#request(). Mutating the published object has no effect on the wire, so tracing instrumentation has no way to add context headers such as traceparent to outgoing HTTP/2 client requests. Add a new http2.client.request.headers channel, published when ClientHttp2Session#request() is called, before the headers are validated and serialized. Subscribers receive a shallow copy of the headers object passed by the caller and can mutate it in place to add or modify request headers. When request() is called without headers, a fresh object is published so subscribers can still inject headers. The caller's own headers object and its sensitiveHeaders list are never modified, so header objects can be safely reused or forwarded across requests. Injected headers go through the same validation as headers passed directly to request(). The existing created and start channels are unchanged. Assisted-by: pi Signed-off-by: Bryan English <bryan@bryanenglish.com> PR-URL: #67069 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 081f642 commit 656d78d

3 files changed

Lines changed: 278 additions & 5 deletions

File tree

‎doc/api/diagnostics_channel.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1699,6 +1699,25 @@ Emitted when server sends a response.
16991699

17001700
> Stability: 1 - Experimental
17011701

1702+
##### Event: `'http2.client.request.headers'`
1703+
1704+
* `headers` {HTTP/2 Headers Object | string\[]}
1705+
* `session` {http2.ClientHttp2Session}
1706+
1707+
Emitted when `ClientHttp2Session#request()` is called, before the request
1708+
headers are validated and serialized. The `headers` object is a copy of the
1709+
one passed to `request()` by the caller (or a newly created object when no
1710+
headers were passed), and it can be mutated in place to add or modify request
1711+
headers before they are sent. Mutating it does not affect the headers
1712+
object passed by the caller. This allows subscribers such as tracing
1713+
instrumentation to inject context headers (e.g. `traceparent`) into outgoing
1714+
HTTP/2 requests.
1715+
Headers injected this way are subject to the same validation as headers
1716+
passed directly to `request()`. To take effect, headers must be mutated in
1717+
place. Unlike `'http2.client.stream.created'`, which is published after
1718+
the request headers have been serialized, mutations made by subscribers to
1719+
this channel affect the headers that are sent.
1720+
17021721
##### Event: `'http2.client.stream.created'`
17031722

17041723
* `stream` {ClientHttp2Stream}

‎lib/internal/http2/core.js‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ const { StreamPipe } = internalBinding('stream_pipe');
199199
const { _connectionListener: httpConnectionListener } = http;
200200

201201
const dc = require('diagnostics_channel');
202+
const onClientRequestHeadersChannel = dc.channel('http2.client.request.headers');
202203
const onClientStreamCreatedChannel = dc.channel('http2.client.stream.created');
203204
const onClientStreamStartChannel = dc.channel('http2.client.stream.start');
204205
const onClientStreamErrorChannel = dc.channel('http2.client.stream.error');
@@ -1925,30 +1926,49 @@ class ClientHttp2Session extends Http2Session {
19251926

19261927
this[kUpdateTimer]();
19271928

1929+
let headers = headersParam;
1930+
if (onClientRequestHeadersChannel.hasSubscribers &&
1931+
(headers === undefined ||
1932+
ArrayIsArray(headers) ||
1933+
(!!headers && typeof headers === 'object'))) {
1934+
if (headers === undefined) {
1935+
headers = { __proto__: null };
1936+
} else {
1937+
headers = ArrayIsArray(headers) ?
1938+
ArrayFrom(headers) :
1939+
ObjectAssign({ __proto__: null }, headers);
1940+
if (headersParam[kSensitiveHeaders] !== undefined) {
1941+
headers[kSensitiveHeaders] =
1942+
ArrayFrom(headersParam[kSensitiveHeaders]);
1943+
}
1944+
}
1945+
onClientRequestHeadersChannel.publish({ headers, session: this });
1946+
}
1947+
19281948
let headersList;
19291949
let headersObject;
19301950
let rawHeaders;
19311951
let scheme;
19321952
let authority;
19331953
let method;
19341954

1935-
if (ArrayIsArray(headersParam)) {
1955+
if (ArrayIsArray(headers)) {
19361956
({
19371957
rawHeaders,
19381958
headersList,
19391959
scheme,
19401960
authority,
19411961
method,
1942-
} = prepareRequestHeadersArray(headersParam, this));
1943-
} else if (!!headersParam && typeof headersParam === 'object') {
1962+
} = prepareRequestHeadersArray(headers, this));
1963+
} else if (!!headers && typeof headers === 'object') {
19441964
({
19451965
headersObject,
19461966
headersList,
19471967
scheme,
19481968
authority,
19491969
method,
1950-
} = prepareRequestHeadersObject(headersParam, this));
1951-
} else if (headersParam === undefined) {
1970+
} = prepareRequestHeadersObject(headers, this));
1971+
} else if (headers === undefined) {
19521972
({
19531973
headersObject,
19541974
headersList,
Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
if (!common.hasCrypto)
5+
common.skip('missing crypto');
6+
7+
const assert = require('assert');
8+
const { once } = require('events');
9+
const dc = require('diagnostics_channel');
10+
const http2 = require('http2');
11+
12+
const kPublishCount = 8;
13+
14+
let currentSession;
15+
let injection;
16+
17+
dc.subscribe('http2.client.request.headers', common.mustCall(({ headers, session }) => {
18+
assert.strictEqual(session, currentSession);
19+
assert.strictEqual(session.constructor.name, 'ClientHttp2Session');
20+
assert.ok(!!headers && typeof headers === 'object');
21+
if (injection !== undefined)
22+
injection(headers);
23+
}, kPublishCount));
24+
25+
function doRequest(client, headers) {
26+
return new Promise((resolve, reject) => {
27+
const stream = client.request(headers);
28+
stream.setEncoding('utf8');
29+
let body = '';
30+
stream.on('data', (chunk) => { body += chunk; });
31+
stream.on('end', () => resolve(JSON.parse(body)));
32+
stream.on('error', reject);
33+
});
34+
}
35+
36+
async function main() {
37+
const server = http2.createServer();
38+
server.on('stream', (stream, headers) => {
39+
// Echo the received request headers back in the response body.
40+
stream.respond({ 'content-type': 'application/json' });
41+
stream.end(JSON.stringify(headers));
42+
});
43+
server.listen(0);
44+
await once(server, 'listening');
45+
const port = server.address().port;
46+
47+
// Scenario 1: request() called while the session is still connecting,
48+
// with an object headers argument.
49+
{
50+
const client = http2.connect(`http://localhost:${port}`);
51+
currentSession = client;
52+
injection = (headers) => {
53+
headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01';
54+
};
55+
// Also make sure the snapshot published to 'http2.client.stream.created'
56+
// reflects the injected header, since serialization happens after the
57+
// 'http2.client.request.headers' publish.
58+
const onCreated = common.mustCall(({ headers }) => {
59+
assert.strictEqual(
60+
headers.traceparent,
61+
'00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
62+
}, 1);
63+
dc.subscribe('http2.client.stream.created', onCreated);
64+
const origHeaders = { ':path': '/connecting' };
65+
const received = await doRequest(client, origHeaders);
66+
dc.unsubscribe('http2.client.stream.created', onCreated);
67+
assert.strictEqual(
68+
received.traceparent,
69+
'00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
70+
assert.strictEqual(received[':path'], '/connecting');
71+
// The subscriber mutates a copy, so the caller's object is unchanged.
72+
assert.deepStrictEqual(origHeaders, { ':path': '/connecting' });
73+
client.close();
74+
await once(client, 'close');
75+
}
76+
77+
// Scenario 2: request() called on an already-connected session.
78+
{
79+
const client = http2.connect(`http://localhost:${port}`);
80+
await once(client, 'connect');
81+
currentSession = client;
82+
injection = (headers) => {
83+
headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-b7ad6b7169203331-01';
84+
};
85+
const received = await doRequest(client, { ':path': '/connected' });
86+
assert.strictEqual(
87+
received.traceparent,
88+
'00-0af7651916cd43dd8f8ba5c1d1f77f0f-b7ad6b7169203331-01');
89+
assert.strictEqual(received[':path'], '/connected');
90+
client.close();
91+
await once(client, 'close');
92+
}
93+
94+
// Scenario 3: no headers argument at all. The subscriber must still be
95+
// able to inject headers into the fresh object that is published.
96+
{
97+
const client = http2.connect(`http://localhost:${port}`);
98+
currentSession = client;
99+
let sawFreshObject;
100+
injection = (headers) => {
101+
sawFreshObject = headers[':path'] === undefined;
102+
headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01';
103+
};
104+
const received = await doRequest(client);
105+
assert.ok(sawFreshObject);
106+
assert.strictEqual(
107+
received.traceparent,
108+
'00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
109+
assert.strictEqual(received[':path'], '/');
110+
client.close();
111+
await once(client, 'close');
112+
}
113+
114+
// Scenario 4: a subscriber that does not mutate the headers must have no
115+
// effect on the request.
116+
{
117+
const client = http2.connect(`http://localhost:${port}`);
118+
await once(client, 'connect');
119+
currentSession = client;
120+
injection = undefined;
121+
const received = await doRequest(client, {
122+
':path': '/no-mutation',
123+
'x-test': 'value',
124+
});
125+
assert.strictEqual(received.traceparent, undefined);
126+
assert.deepStrictEqual(received, {
127+
':method': 'GET',
128+
':scheme': 'http',
129+
':authority': `localhost:${port}`,
130+
':path': '/no-mutation',
131+
'x-test': 'value',
132+
});
133+
client.close();
134+
await once(client, 'close');
135+
}
136+
137+
// Scenario 5: an array of raw headers can be mutated in place.
138+
{
139+
const client = http2.connect(`http://localhost:${port}`);
140+
currentSession = client;
141+
const origHeaders = [':path', '/array'];
142+
let sawArray;
143+
injection = (headers) => {
144+
sawArray = Array.isArray(headers);
145+
headers.push('traceparent', '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
146+
};
147+
const received = await doRequest(client, origHeaders);
148+
assert.ok(sawArray);
149+
assert.strictEqual(
150+
received.traceparent,
151+
'00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
152+
assert.strictEqual(received[':path'], '/array');
153+
// The subscriber mutates a copy, so the caller's array is unchanged.
154+
assert.deepStrictEqual(origHeaders, [':path', '/array']);
155+
client.close();
156+
await once(client, 'close');
157+
}
158+
159+
// Scenario 6: injected headers go through the same validation as headers
160+
// passed directly to request(). Injecting an unknown pseudo-header throws
161+
// the same error that passing it directly would.
162+
{
163+
const client = http2.connect(`http://localhost:${port}`);
164+
currentSession = client;
165+
injection = (headers) => {
166+
headers[':foo'] = 'invalid';
167+
};
168+
assert.throws(() => client.request({ ':path': '/invalid' }),
169+
{ code: 'ERR_HTTP2_INVALID_PSEUDOHEADER' });
170+
injection = undefined;
171+
client.destroy();
172+
}
173+
174+
// Scenario 7: sensitiveHeaders is preserved on the published copy, in
175+
// object form, and mutating it does not touch the caller's list.
176+
{
177+
const client = http2.connect(`http://localhost:${port}`);
178+
currentSession = client;
179+
const origHeaders = {
180+
':path': '/sensitive',
181+
'authorization': 'secret',
182+
[http2.sensitiveHeaders]: ['authorization'],
183+
};
184+
let sawSensitive;
185+
injection = (headers) => {
186+
sawSensitive = headers[http2.sensitiveHeaders]?.slice();
187+
headers[http2.sensitiveHeaders].push('traceparent');
188+
headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01';
189+
};
190+
const received = await doRequest(client, origHeaders);
191+
assert.strictEqual(
192+
received.traceparent,
193+
'00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
194+
assert.deepStrictEqual(sawSensitive, ['authorization']);
195+
assert.deepStrictEqual(origHeaders, {
196+
':path': '/sensitive',
197+
'authorization': 'secret',
198+
[http2.sensitiveHeaders]: ['authorization'],
199+
});
200+
client.close();
201+
await once(client, 'close');
202+
}
203+
204+
// Scenario 8: same as scenario 7, in raw array form.
205+
{
206+
const client = http2.connect(`http://localhost:${port}`);
207+
currentSession = client;
208+
const origHeaders = [':path', '/sensitive-array', 'authorization', 'secret'];
209+
origHeaders[http2.sensitiveHeaders] = ['authorization'];
210+
let sawArray;
211+
let sawSensitive;
212+
injection = (headers) => {
213+
sawArray = Array.isArray(headers);
214+
sawSensitive = headers[http2.sensitiveHeaders]?.slice();
215+
headers[http2.sensitiveHeaders].push('traceparent');
216+
headers.push('traceparent', '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
217+
};
218+
const received = await doRequest(client, origHeaders);
219+
assert.strictEqual(
220+
received.traceparent,
221+
'00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01');
222+
assert.ok(sawArray);
223+
assert.deepStrictEqual(sawSensitive, ['authorization']);
224+
assert.strictEqual(origHeaders.length, 4);
225+
assert.deepStrictEqual(origHeaders[http2.sensitiveHeaders], ['authorization']);
226+
client.close();
227+
await once(client, 'close');
228+
}
229+
230+
server.close();
231+
await once(server, 'close');
232+
}
233+
234+
main().then(common.mustCall());

0 commit comments

Comments
 (0)