Skip to content

Commit

Permalink
feature: support pre-shared sessions (#3325)
Browse files Browse the repository at this point in the history
Co-authored-by: Ezekiel Keator <ekeator@paypal.com>
  • Loading branch information
tastypackets and Ezekiel Keator authored Jun 14, 2024
1 parent 7f54a24 commit 39869b2
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/core/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env
}
}

function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {
if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
}
Expand All @@ -91,7 +91,7 @@ function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...o
servername = servername || options.servername || util.getServerName(host) || null

const sessionKey = servername || hostname
const session = sessionCache.get(sessionKey) || null
const session = customSession || sessionCache.get(sessionKey) || null

assert(sessionKey)

Expand Down
50 changes: 50 additions & 0 deletions test/connect-pre-shared-session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict'

const { tspl } = require('@matteo.collina/tspl')
const { test, after, mock } = require('node:test')
const { Client } = require('..')
const { createServer } = require('node:https')
const pem = require('https-pem')
const tls = require('node:tls')

test('custom session passed to client will be used in tls connect call', async (t) => {
t = tspl(t, { plan: 4 })

const mockConnect = mock.method(tls, 'connect')

const server = createServer(pem, (req, res) => {
t.strictEqual('/', req.url)
t.strictEqual('GET', req.method)
res.setHeader('content-type', 'text/plain')
res.end('hello')
})
after(() => server.close())

server.listen(0, async () => {
const session = Buffer.from('test-session')

const client = new Client(`https://localhost:${server.address().port}`, {
connect: {
rejectUnauthorized: false,
session
}
})
after(() => client.close())

const { statusCode, headers, body } = await client.request({
path: '/',
method: 'GET'
})

t.strictEqual(statusCode, 200)
t.strictEqual(headers['content-type'], 'text/plain')

const responseText = await body.text()
t.strictEqual('hello', responseText)

const connectSession = mockConnect.mock.calls[0].arguments[0].session
t.strictEqual(connectSession, session)
})

await t.completed
})

0 comments on commit 39869b2

Please sign in to comment.