Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(node): support HTTP/2 in secure request helpers (#90344)

Robbie0a782dc9c31b
diff --git a/nodejs/src/common/utils/request-http2.test.ts b/nodejs/src/common/utils/request-http2.test.ts
new file mode 100644
index 000000000000..a701ed0e9b25
--- /dev/null
+++ b/nodejs/src/common/utils/request-http2.test.ts
@@ -0,0 +1,195 @@
+import http from 'node:http'
+import http2 from 'node:http2'
+import https from 'node:https'
+import net, { AddressInfo } from 'node:net'
+import tls from 'node:tls'
+
+import { TestTlsIdentity, createTestTlsIdentity } from '~/tests/helpers/tls'
+
+type RequestModule = typeof import('./request')
+
+const proxyEnvironmentNames = ['HTTPS_PROXY', 'HTTP_PROXY', 'https_proxy', 'http_proxy'] as const
+
+function serverPort(server: http.Server | http2.Http2SecureServer | https.Server): number {
+ return (server.address() as AddressInfo).port
+}
+
+function listen(server: http.Server | http2.Http2SecureServer | https.Server): Promise<void> {
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
+}
+
+function close(server: http.Server | http2.Http2SecureServer | https.Server): Promise<void> {
+ if (!server.listening) {
+ return Promise.resolve()
+ }
+ return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))
+}
+
+describe('secure HTTP/2 requests', () => {
+ let requestModule: RequestModule
+ let http2Origin: http2.Http2SecureServer
+ let http1Origin: https.Server
+ let connectProxy: http.Server
+ let tlsConnectSpy: jest.SpyInstance
+ let tlsIdentity: TestTlsIdentity | undefined
+ const originalExternalRequestConnections = process.env.EXTERNAL_REQUEST_CONNECTIONS
+ const originalProxyEnvironment = Object.fromEntries(
+ proxyEnvironmentNames.map((name) => [name, process.env[name]])
+ ) as Record<(typeof proxyEnvironmentNames)[number], string | undefined>
+ let http2SessionCount = 0
+ const http2OriginProtocols: string[] = []
+ const http1OriginProtocols: string[] = []
+ const proxyAuthorities: string[] = []
+ const openSockets = new Set<net.Socket>()
+ const openHttp2Sessions = new Set<http2.ServerHttp2Session>()
+ const pendingConcurrentResponses: Array<() => void> = []
+
+ beforeAll(async () => {
+ const generatedTlsIdentity = await createTestTlsIdentity('origin.test')
+ tlsIdentity = generatedTlsIdentity
+
+ http2Origin = http2.createSecureServer({
+ allowHTTP1: true,
+ cert: generatedTlsIdentity.certificate,
+ key: generatedTlsIdentity.privateKey,
+ })
+ http2Origin.on('request', (request, response) => {
+ http2OriginProtocols.push(request.httpVersion)
+ const finishResponse = (): void => {
+ response.writeHead(200, { 'content-type': 'text/plain' })
+ response.end(request.url)
+ }
+ if (request.url?.startsWith('/concurrent-')) {
+ pendingConcurrentResponses.push(finishResponse)
+ if (pendingConcurrentResponses.length === 2) {
+ pendingConcurrentResponses.splice(0).forEach((finish) => finish())
+ }
+ return
+ }
+ finishResponse()
+ })
+ http2Origin.on('session', (session) => {
+ http2SessionCount += 1
+ openHttp2Sessions.add(session)
+ session.once('close', () => openHttp2Sessions.delete(session))
+ })
+ await listen(http2Origin)
+
+ http1Origin = https.createServer(
+ { cert: generatedTlsIdentity.certificate, key: generatedTlsIdentity.privateKey },
+ (request, response) => {
+ http1OriginProtocols.push(request.httpVersion)
+ response.writeHead(200, { 'content-type': 'text/plain' })
+ response.end(request.url)
+ }
+ )
+ await listen(http1Origin)
+
+ connectProxy = http.createServer()
+ connectProxy.on('connection', (socket) => {
+ openSockets.add(socket)
+ socket.once('close', () => openSockets.delete(socket))
+ })
+ connectProxy.on('connect', (request, clientSocket, head) => {
+ proxyAuthorities.push(request.url ?? '')
+ const requestedPort = Number(request.url?.split(':').at(-1))
+ const originSocket = net.connect(requestedPort, '127.0.0.1', () => {
+ clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
+ if (head.length > 0) {
+ originSocket.write(head)
+ }
+ clientSocket.pipe(originSocket)
+ originSocket.pipe(clientSocket)
+ })
+ openSockets.add(originSocket)
+ originSocket.once('close', () => openSockets.delete(originSocket))
+ originSocket.once('error', () => clientSocket.destroy())
+ clientSocket.once('error', () => originSocket.destroy())
+ })
+ await listen(connectProxy)
+
+ const connectWithSystemTrust = tls.connect
+ tlsConnectSpy = jest
+ .spyOn(tls, 'connect')
+ .mockImplementation(((options: tls.ConnectionOptions, callback?: () => void) =>
+ connectWithSystemTrust(
+ { ...options, ca: generatedTlsIdentity.certificate },
+ callback
+ )) as typeof tls.connect)
+ process.env.HTTPS_PROXY = `http://127.0.0.1:${serverPort(connectProxy)}`
+ process.env.EXTERNAL_REQUEST_CONNECTIONS = '2'
+ delete process.env.HTTP_PROXY
+ delete process.env.https_proxy
+ delete process.env.http_proxy
+
+ jest.resetModules()
+ requestModule = require('./request') as RequestModule
+ })
+
+ afterAll(async () => {
+ for (const name of proxyEnvironmentNames) {
+ const value = originalProxyEnvironment[name]
+ if (value === undefined) {
+ delete process.env[name]
+ } else {
+ process.env[name] = value
+ }
+ }
+ if (originalExternalRequestConnections === undefined) {
+ delete process.env.EXTERNAL_REQUEST_CONNECTIONS
+ } else {
+ process.env.EXTERNAL_REQUEST_CONNECTIONS = originalExternalRequestConnections
+ }
+ tlsConnectSpy.mockRestore()
+
+ for (const session of openHttp2Sessions) {
+ session.destroy()
+ }
+ for (const socket of openSockets) {
+ socket.destroy()
+ }
+ http1Origin.closeAllConnections()
+ connectProxy.closeAllConnections()
+ await Promise.all([close(http2Origin), close(http1Origin), close(connectProxy)])
+ await tlsIdentity?.cleanup()
+ })
+
+ it('negotiates, reuses, runs concurrently, defaults, and falls back through a CONNECT proxy', async () => {
+ const http2Authority = `origin.test:${serverPort(http2Origin)}`
+ const http2Url = `https://${http2Authority}`
+ const bufferedResponse = await requestModule.fetch(`${http2Url}/buffered`, { allowH2: true, timeoutMs: 2000 })
+ expect(await bufferedResponse.text()).toBe('/buffered')
+
+ const streamedResponse = await requestModule.fetchStreamed(`${http2Url}/streamed`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ expect((await streamedResponse.read(100)).bytes.toString()).toBe('/streamed')
+
+ const concurrentBodies = await Promise.all(
+ ['/concurrent-a', '/concurrent-b'].map(async (path) => {
+ const response = await requestModule.fetchStreamed(`${http2Url}${path}`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ return (await response.read(100)).bytes.toString()
+ })
+ )
+ expect(concurrentBodies).toEqual(['/concurrent-a', '/concurrent-b'])
+
+ const defaultResponse = await requestModule.fetchStreamed(`${http2Url}/default`, { timeoutMs: 2000 })
+ expect((await defaultResponse.read(100)).bytes.toString()).toBe('/default')
+
+ const http1Authority = `origin.test:${serverPort(http1Origin)}`
+ const fallbackResponse = await requestModule.fetchStreamed(`https://${http1Authority}/fallback`, {
+ allowH2: true,
+ timeoutMs: 2000,
+ })
+ expect((await fallbackResponse.read(100)).bytes.toString()).toBe('/fallback')
+
+ expect(http2OriginProtocols).toEqual(['2.0', '2.0', '2.0', '2.0', '1.1'])
+ expect(http1OriginProtocols).toEqual(['1.1'])
+ expect(http2SessionCount).toBe(2)
+ expect(proxyAuthorities).toEqual([http2Authority, http2Authority, http2Authority, http1Authority])
+ }, 10000)
+})
diff --git a/nodejs/src/common/utils/request.test.ts b/nodejs/src/common/utils/request.test.ts
index 82be21b4da76..7758ad63c928 100644
--- a/nodejs/src/common/utils/request.test.ts
+++ b/nodejs/src/common/utils/request.test.ts
@@ -208,6 +208,14 @@ describe('fetch', () => {
await expect(fetch(`http://example.com`)).rejects.toThrow(new SecureRequestError(`Hostname is not allowed`))
})
+ it('uses secure DNS lookup when HTTP/2 is enabled', async () => {
+ jest.mocked(dns.lookup).mockResolvedValue([{ address: '10.0.0.1', family: 4 }] as any)
+
+ await expect(fetch('https://example.com', { allowH2: true })).rejects.toThrow(
+ new SecureRequestError('Hostname is not allowed')
+ )
+ })
+
it.each([
['::ffff:169.254.169.254', 'IPv6-mapped IMDS'],
['::ffff:127.0.0.1', 'IPv6-mapped loopback'],
diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.ts
index 56e46418742a..58e592750e93 100644
--- a/nodejs/src/common/utils/request.ts
+++ b/nodejs/src/common/utils/request.ts
@@ -253,19 +253,6 @@ export async function raiseIfUserProvidedUrlUnsafe(url: string): Promise<void> {
await staticLookupAsync(parsedUrl.hostname)
}
-class SecureAgent extends Agent {
- constructor() {
- super({
- keepAliveTimeout: Number(requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS),
- connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
- connect: {
- lookup: httpStaticLookup,
- timeout: requestConfig.EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS,
- },
- })
- }
-}
-
// Safe way to use the same helpers for talking to internal endpoints such as other services
class InsecureAgent extends Agent {
constructor() {
@@ -282,7 +269,7 @@ class InsecureAgent extends Agent {
// When a proxy URL is available, external requests go through a CONNECT tunnel.
// The proxy handles SSRF blocking (private IP rejection) at the network level,
// so we skip the DNS lookup (httpStaticLookup) which would be redundant.
-function makeSecureDispatcher(): Dispatcher {
+function makeSecureDispatcher({ allowH2 }: { allowH2: boolean }): Dispatcher {
const proxyUrl =
process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy || process.env.http_proxy
@@ -291,26 +278,23 @@ function makeSecureDispatcher(): Dispatcher {
uri: proxyUrl,
keepAliveTimeout: requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS,
connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
- requestTls: {},
+ allowH2,
+ requestTls: { allowH2 },
})
}
- return new SecureAgent()
+ return new Agent({
+ keepAliveTimeout: Number(requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS),
+ connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
+ allowH2,
+ connect: {
+ lookup: httpStaticLookup,
+ timeout: requestConfig.EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS,
+ },
+ })
}
-const sharedSecureAgent = makeSecureDispatcher()
-// Unlike `makeSecureDispatcher`, this agent deliberately skips the ProxyAgent branch: CDP workers don't
-// set the proxy env vars, and SSRF stays covered via `httpStaticLookup`. If CDP egress ever moves behind
-// the proxy (see #49170), swap this for a `ProxyAgent` — undici's `ProxyAgent` supports `allowH2` — so
-// H2 traffic (e.g. APNs) doesn't silently keep going direct.
-const sharedSecureH2Agent = new Agent({
- keepAliveTimeout: Number(requestConfig.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS),
- connections: requestConfig.EXTERNAL_REQUEST_CONNECTIONS,
- allowH2: true,
- connect: {
- lookup: httpStaticLookup,
- timeout: requestConfig.EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS,
- },
-})
+const sharedSecureAgent = makeSecureDispatcher({ allowH2: false })
+const sharedSecureH2Agent = makeSecureDispatcher({ allowH2: true })
const sharedInsecureAgent = new InsecureAgent()
function destroyBody(body: Dispatcher.ResponseData['body']): void {
@@ -434,6 +418,7 @@ export async function fetch(url: string, options: FetchOptions = {}): Promise<Fe
export type StreamedFetchOptions = {
headers?: HeadersInit
timeoutMs: number
+ allowH2?: boolean
}
export type StreamedResponse = {
@@ -537,7 +522,7 @@ export async function fetchStreamed(url: string, options: StreamedFetchOptions):
result = await request(parsed.toString(), {
method: 'GET',
headers: options.headers,
- dispatcher: sharedSecureAgent,
+ dispatcher: options.allowH2 ? sharedSecureH2Agent : sharedSecureAgent,
signal: AbortSignal.timeout(options.timeoutMs),
responseHeaders: 'raw',
})
diff --git a/nodejs/tests/helpers/tls.ts b/nodejs/tests/helpers/tls.ts
new file mode 100644
index 000000000000..2ed6113540c0
--- /dev/null
+++ b/nodejs/tests/helpers/tls.ts
@@ -0,0 +1,51 @@
+import { execFile } from 'node:child_process'
+import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+
+const execFileAsync = promisify(execFile)
+
+export type TestTlsIdentity = {
+ privateKey: Buffer
+ certificate: Buffer
+ cleanup: () => Promise<void>
+}
+
+export async function createTestTlsIdentity(hostname: string): Promise<TestTlsIdentity> {
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'posthog-test-tls-'))
+ const privateKeyPath = path.join(directory, 'server.key')
+ const certificatePath = path.join(directory, 'server.crt')
+
+ try {
+ await execFileAsync('openssl', [
+ 'req',
+ '-x509',
+ '-newkey',
+ 'ec',
+ '-pkeyopt',
+ 'ec_paramgen_curve:P-256',
+ '-nodes',
+ '-keyout',
+ privateKeyPath,
+ '-out',
+ certificatePath,
+ '-days',
+ '1',
+ '-subj',
+ `/CN=${hostname}`,
+ '-addext',
+ `subjectAltName=DNS:${hostname}`,
+ ])
+ const [privateKey, certificate] = await Promise.all([readFile(privateKeyPath), readFile(certificatePath)])
+
+ return {
+ privateKey,
+ certificate,
+ cleanup: async () => await rm(directory, { recursive: true, force: true }),
+ }
+ } catch (error) {
+ await rm(directory, { recursive: true, force: true })
+ throw error
+ }
+}