Skip to content

Commit fa8ffdb

Browse files
committed
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>
1 parent 75191c4 commit fa8ffdb

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
@@ -197,6 +197,7 @@ const { StreamPipe } = internalBinding('stream_pipe');
197197
const { _connectionListener: httpConnectionListener } = http;
198198

199199
const dc = require('diagnostics_channel');
200+
const onClientRequestHeadersChannel = dc.channel('http2.client.request.headers');
200201
const onClientStreamCreatedChannel = dc.channel('http2.client.stream.created');
201202
const onClientStreamStartChannel = dc.channel('http2.client.stream.start');
202203
const onClientStreamErrorChannel = dc.channel('http2.client.stream.error');
@@ -1906,30 +1907,49 @@ class ClientHttp2Session extends Http2Session {
19061907

19071908
this[kUpdateTimer]();
19081909

1910+
let headers = headersParam;
1911+
if (onClientRequestHeadersChannel.hasSubscribers &&
1912+
(headers === undefined ||
1913+
ArrayIsArray(headers) ||
1914+
(!!headers && typeof headers === 'object'))) {
1915+
if (headers === undefined) {
1916+
headers = { __proto__: null };
1917+
} else {
1918+
headers = ArrayIsArray(headers) ?
1919+
ArrayFrom(headers) :
1920+
ObjectAssign({ __proto__: null }, headers);
1921+
if (headersParam[kSensitiveHeaders] !== undefined) {
1922+
headers[kSensitiveHeaders] =
1923+
ArrayFrom(headersParam[kSensitiveHeaders]);
1924+
}
1925+
}
1926+
onClientRequestHeadersChannel.publish({ headers, session: this });
1927+
}
1928+
19091929
let headersList;
19101930
let headersObject;
19111931
let rawHeaders;
19121932
let scheme;
19131933
let authority;
19141934
let method;
19151935

1916-
if (ArrayIsArray(headersParam)) {
1936+
if (ArrayIsArray(headers)) {
19171937
({
19181938
rawHeaders,
19191939
headersList,
19201940
scheme,
19211941
authority,
19221942
method,
1923-
} = prepareRequestHeadersArray(headersParam, this));
1924-
} else if (!!headersParam && typeof headersParam === 'object') {
1943+
} = prepareRequestHeadersArray(headers, this));
1944+
} else if (!!headers && typeof headers === 'object') {
19251945
({
19261946
headersObject,
19271947
headersList,
19281948
scheme,
19291949
authority,
19301950
method,
1931-
} = prepareRequestHeadersObject(headersParam, this));
1932-
} else if (headersParam === undefined) {
1951+
} = prepareRequestHeadersObject(headers, this));
1952+
} else if (headers === undefined) {
19331953
({
19341954
headersObject,
19351955
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)