tls: add certificateCompression option

This changes enables compression within OpenSSL *without* enabling
record compression, so this only affects compression of certificates
delivered within the TLS handshake. This certificate compression remains
disabled by default for now, but becomes available via the new
certificateCompression option in TLS context APIs.

Enabling this shrinks handshakes significantly, and also reduces
fingerprintability of Node.js client handshakes, as these are enabled in
all modern browsers by default.

Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/62217
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Tim Perry authored and Antoine du Hamel committed 2026-07-30 13:51:38 +02:00
1 parent 35222948be
commit 5e901b5cd9
10 files changed
+513 -6

No files matched your search

+9 -5
View File
@@ -19,11 +19,6 @@
{
'target_name': 'openssl',
'type': '<(library)',
'dependencies': [
'../zlib/zlib.gyp:zlib',
'../brotli/brotli.gyp:brotli',
'../zstd/zstd.gyp:zstd',
],
'includes': ['./openssl_common.gypi'],
'defines': [
# Compile out hardware engines. Most are stubs that dynamically load
@@ -54,6 +49,15 @@
'MODULESDIR="<(modules_dir)"',
]
}],
['node_shared_zlib=="false"', {
'dependencies': [ '../zlib/zlib.gyp:zlib' ],
}],
['node_shared_brotli=="false"', {
'dependencies': [ '../brotli/brotli.gyp:brotli' ],
}],
['node_shared_zstd=="false"', {
'dependencies': [ '../zstd/zstd.gyp:zstd' ],
}],
],
'direct_dependent_settings': {
'include_dirs': [ 'openssl/include', 'openssl/crypto/include']
+29
View File
@@ -1895,6 +1895,9 @@ argument.
<!-- YAML
added: v0.11.13
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/62217
description: The `certificateCompression` option has been added.
- version:
- v22.9.0
- v20.18.0
@@ -1988,6 +1991,12 @@ changes:
the same order as their private keys in `key`. If the intermediate
certificates are not provided, the peer will not be able to validate the
certificate, and the handshake will fail.
* `certificateCompression` {string\[]} An array of supported certificate
compression algorithm names, in preference order. Supported values are
`'zlib'`, `'brotli'`, and `'zstd'`. When set, enables TLS certificate
compression ([RFC 8879][]) which compresses certificates during the TLS
handshake, reducing handshake size. Only effective with TLSv1.3.
**Default:** `[]` (disabled).
* `sigalgs` {string} Colon-separated list of supported signature algorithms.
The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key
algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g
@@ -2376,6 +2385,25 @@ TLSv1.2 and below.
console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
```
## `tls.getCertificateCompressionAlgorithms()`
<!-- YAML
added: REPLACEME
-->
* Returns: {string\[]}
Returns an array with the names of the RFC 8879 certificate compression
algorithms supported by the current OpenSSL build, suitable for use in the
`certificateCompression` option of [`tls.createSecureContext()`][]. Possible
values include `'zlib'`, `'brotli'`, and `'zstd'`.
The array is empty when certificate compression is unavailable.
```js
console.log(tls.getCertificateCompressionAlgorithms()); // ['zlib', 'brotli', 'zstd']
```
## `tls.rootCertificates`
<!-- YAML
@@ -2467,6 +2495,7 @@ added: v0.11.3
[RFC 4279]: https://tools.ietf.org/html/rfc4279
[RFC 5077]: https://tools.ietf.org/html/rfc5077
[RFC 5929]: https://tools.ietf.org/html/rfc5929
[RFC 8879]: https://tools.ietf.org/html/rfc8879
[SSL_METHODS]: https://www.openssl.org/docs/man1.1.1/man7/ssl.html#Dealing-with-Protocol-Methods
[Session Resumption]: #session-resumption
[Stream]: stream.md#stream
+38
View File
@@ -133,6 +133,7 @@ function configSecureContext(context, options = kEmptyObject, name = 'options')
allowPartialTrustChain,
ca,
cert,
certificateCompression,
ciphers = getDefaultCiphers(),
clientCertEngine,
crl,
@@ -210,6 +211,43 @@ function configSecureContext(context, options = kEmptyObject, name = 'options')
}
}
if (certificateCompression != null) {
if (!ArrayIsArray(certificateCompression)) {
throw new ERR_INVALID_ARG_TYPE(
`${name}.certificateCompression`, 'Array', certificateCompression);
}
if (certificateCompression.length > 0) {
// Pack length + algorithm IDs into a single Uint32 for a cheap
// JS->C++ crossing. Layout:
// bits 0-7 : length (1..3)
// bits 8-15: alg id at position 0
// bits 16-23: alg id at position 1
// bits 24-31: alg id at position 2
// IDs match OpenSSL's TLSEXT_comp_cert_zlib (1), _brotli (2), _zstd (3)
if (certificateCompression.length > 3) {
throw new ERR_INVALID_ARG_VALUE(
`${name}.certificateCompression`, certificateCompression,
'can specify at most 3 algorithms');
}
let packed = certificateCompression.length;
for (let i = 0; i < certificateCompression.length; i++) {
const algoName = certificateCompression[i];
let id;
if (algoName === 'zlib') id = 1;
else if (algoName === 'brotli') id = 2;
else if (algoName === 'zstd') id = 3;
else {
throw new ERR_INVALID_ARG_VALUE(
`${name}.certificateCompression[${i}]`, algoName,
"must be 'zlib', 'brotli', or 'zstd'");
}
packed |= id << (8 * (i + 1));
}
context.setCertificateCompression(packed);
}
}
if (sigalgs !== undefined && sigalgs !== null) {
validateString(sigalgs, `${name}.sigalgs`);
+2
View File
@@ -1621,6 +1621,7 @@ Server.prototype.setSecureContext = function(options) {
this.privateKeyIdentifier = options.privateKeyIdentifier;
this.privateKeyEngine = options.privateKeyEngine;
this.certificateCompression = options.certificateCompression;
this._sharedCreds = tls.createSecureContext({
pfx: this.pfx,
@@ -1644,6 +1645,7 @@ Server.prototype.setSecureContext = function(options) {
sessionTimeout: this.sessionTimeout,
privateKeyIdentifier: this.privateKeyIdentifier,
privateKeyEngine: this.privateKeyEngine,
certificateCompression: this.certificateCompression,
});
};
+5
View File
@@ -47,6 +47,7 @@ const {
resetRootCertStore,
getUserRootCertificates,
getSSLCiphers,
getCertificateCompressionAlgorithms,
startLoadingCertificatesOffThread,
} = internalBinding('crypto');
@@ -113,6 +114,10 @@ exports.getCiphers = internalUtil.cachedResult(
() => internalUtil.filterDuplicateStrings(getSSLCiphers(), true),
);
exports.getCertificateCompressionAlgorithms = internalUtil.cachedResult(
() => getCertificateCompressionAlgorithms(),
);
let bundledRootCertificates;
function cacheBundledRootCertificates() {
bundledRootCertificates ||= ObjectFreeze(getBundledRootCertificates());
+112 -1
View File
@@ -12,9 +12,10 @@
#include "util.h"
#include "v8.h"
#include <openssl/x509.h>
#include <openssl/comp.h>
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif // !OPENSSL_NO_ENGINE
@@ -1308,6 +1309,8 @@ Local<FunctionTemplate> SecureContext::GetConstructorTemplate(
SetProtoMethod(isolate, tmpl, "setOptions", SetOptions);
SetProtoMethod(isolate, tmpl, "setSessionIdContext", SetSessionIdContext);
SetProtoMethod(isolate, tmpl, "setSessionTimeout", SetSessionTimeout);
SetProtoMethod(
isolate, tmpl, "setCertificateCompression", SetCertificateCompression);
SetProtoMethod(isolate, tmpl, "close", Close);
SetProtoMethod(isolate, tmpl, "loadPKCS12", LoadPKCS12);
SetProtoMethod(isolate, tmpl, "setTicketKeys", SetTicketKeys);
@@ -1372,6 +1375,10 @@ void SecureContext::Initialize(Environment* env, Local<Object> target) {
target,
"startLoadingCertificatesOffThread",
StartLoadingCertificatesOffThread);
SetMethodNoSideEffect(context,
target,
"getCertificateCompressionAlgorithms",
GetCertificateCompressionAlgorithms);
}
void SecureContext::RegisterExternalReferences(
@@ -1396,6 +1403,7 @@ void SecureContext::RegisterExternalReferences(
registry->Register(SetOptions);
registry->Register(SetSessionIdContext);
registry->Register(SetSessionTimeout);
registry->Register(SetCertificateCompression);
registry->Register(Close);
registry->Register(LoadPKCS12);
registry->Register(SetTicketKeys);
@@ -1417,6 +1425,7 @@ void SecureContext::RegisterExternalReferences(
registry->Register(ResetRootCertStore);
registry->Register(GetUserRootCertificates);
registry->Register(StartLoadingCertificatesOffThread);
registry->Register(GetCertificateCompressionAlgorithms);
}
SecureContext* SecureContext::Create(Environment* env) {
@@ -1554,6 +1563,14 @@ void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
env->external_memory_accounter()->Increase(env->isolate(), kExternalSize);
SSL_CTX_set_app_data(sc->ctx_.get(), sc);
// OpenSSL populates cert_comp_prefs with all available algorithms by
// default when compression libraries are linked. Clear them so that
// certificate compression (RFC 8879) is always opt-in for now, via
// the certificateCompression option.
#ifdef NODE_OPENSSL_HAS_CERT_COMP
SSL_CTX_set1_cert_comp_preference(sc->ctx_.get(), nullptr, 0);
#endif
// Disable SSLv2 in the case when method == TLS_method() and the
// cipher list contains SSLv2 ciphers (not the default, should be rare.)
// The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
@@ -2059,6 +2076,100 @@ void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
}
void SecureContext::SetCertificateCompression(
const FunctionCallbackInfo<Value>& args) {
SecureContext* sc;
ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
Environment* env = sc->env();
CHECK_GE(args.Length(), 1);
CHECK(args[0]->IsUint32());
// Cert compression requires TLS 1.3:
long max_proto = // NOLINT(runtime/int)
SSL_CTX_get_max_proto_version(sc->ctx_.get());
if (max_proto != 0 && max_proto < TLS1_3_VERSION) {
return THROW_ERR_INVALID_ARG_VALUE(
env,
"certificateCompression requires a TLS protocol range that includes "
"TLSv1.3");
}
#ifdef NODE_OPENSSL_HAS_CERT_COMP
// JS packs (length | alg0<<8 | alg1<<16 | alg2<<24) into a single Uint32.
// IDs match TLSEXT_comp_cert_zlib (1), _brotli (2), _zstd (3).
uint32_t packed = args[0].As<v8::Uint32>()->Value();
size_t len = packed & 0xff;
// TLSEXT_comp_cert_limit is the limit for a zero-terminated algs array,
// total number of available algs is one fewer.
constexpr size_t kMaxCompAlgs = TLSEXT_comp_cert_limit - 1;
if (len == 0 || len > kMaxCompAlgs) {
return THROW_ERR_INVALID_ARG_VALUE(
env,
"certificateCompression must specify fewer than %d algorithms",
static_cast<int>(kMaxCompAlgs));
}
int algs[kMaxCompAlgs];
for (size_t i = 0; i < len; i++) {
algs[i] = (packed >> (8 * (i + 1))) & 0xff;
}
if (!SSL_CTX_set1_cert_comp_preference(
sc->ctx_.get(), algs, static_cast<size_t>(len))) {
return THROW_ERR_CRYPTO_OPERATION_FAILED(
env, "Failed to set certificate compression preference");
}
// Pre-compress the loaded certificate(s) for all supported algorithms.
// Returns 0 when no certificate is loaded (e.g. client-only context) or
// when compression did not reduce size - both are non-fatal.
constexpr int kCompressAllAlgs = 0;
SSL_CTX_compress_certs(sc->ctx_.get(), kCompressAllAlgs);
// Store preferences for propagation during SNI context switches.
memcpy(sc->cert_comp_prefs_, algs, sizeof(int) * len);
sc->cert_comp_prefs_len_ = len;
// Cache pre-compressed cert data for SNI context switches.
// setSniContext uses SSL_use_certificate which doesn't carry comp_cert data,
// so we extract it here and re-apply via SSL_set1_compressed_cert later.
sc->compressed_certs_.clear();
for (size_t i = 0; i < len; i++) {
unsigned char* data = nullptr;
size_t orig_len = 0;
size_t comp_len =
SSL_CTX_get1_compressed_cert(sc->ctx_.get(), algs[i], &data, &orig_len);
ncrypto::DataPointer comp(data, comp_len);
if (comp_len > 0 && data != nullptr) {
sc->compressed_certs_.push_back(
{algs[i],
std::vector<unsigned char>(data, data + comp_len),
orig_len});
}
}
#else
return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(
env, "Certificate compression is not supported by this OpenSSL build");
#endif
}
void SecureContext::GetCertificateCompressionAlgorithms(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
LocalVector<Value> algs(env->isolate());
#ifdef NODE_OPENSSL_HAS_CERT_COMP
if (BIO_f_zlib() != nullptr)
algs.push_back(FIXED_ONE_BYTE_STRING(env->isolate(), "zlib"));
if (BIO_f_brotli() != nullptr)
algs.push_back(FIXED_ONE_BYTE_STRING(env->isolate(), "brotli"));
if (BIO_f_zstd() != nullptr)
algs.push_back(FIXED_ONE_BYTE_STRING(env->isolate(), "zstd"));
#endif
args.GetReturnValue().Set(
Array::New(env->isolate(), algs.data(), algs.size()));
}
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc;
ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
+35
View File
@@ -10,6 +10,10 @@
#include "memory_tracker.h"
#include "v8.h"
#ifdef NODE_OPENSSL_HAS_CERT_COMP
#include <vector>
#endif
namespace node {
namespace crypto {
// A maxVersion of 0 means "any", but OpenSSL may support TLS versions that
@@ -47,6 +51,27 @@ class SecureContext final : public BaseObject {
// the SecureContext.
ncrypto::SSLCtxPointer& ctx() { return ctx_; }
#ifdef NODE_OPENSSL_HAS_CERT_COMP
bool HasCertCompression() const {
return cert_comp_prefs_len_ > 0;
}
int* CertCompPrefs() {
return cert_comp_prefs_;
}
size_t CertCompPrefsLen() const {
return cert_comp_prefs_len_;
}
struct CompressedCertData {
int algorithm;
std::vector<unsigned char> data;
size_t orig_length;
};
const std::vector<CompressedCertData>& CompressedCerts() const {
return compressed_certs_;
}
#endif
ncrypto::SSLPointer CreateSSL();
void SetGetSessionCallback(GetSessionCb cb);
@@ -106,6 +131,10 @@ class SecureContext final : public BaseObject {
const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetSessionTimeout(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetCertificateCompression(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetCertificateCompressionAlgorithms(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetMinProto(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetMaxProto(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetMinProto(const v8::FunctionCallbackInfo<v8::Value>& args);
@@ -156,6 +185,12 @@ class SecureContext final : public BaseObject {
unsigned char ticket_key_name_[16];
unsigned char ticket_key_aes_[16];
unsigned char ticket_key_hmac_[16];
#ifdef NODE_OPENSSL_HAS_CERT_COMP
int cert_comp_prefs_[TLSEXT_comp_cert_limit] = {};
size_t cert_comp_prefs_len_ = 0;
std::vector<CompressedCertData> compressed_certs_;
#endif
};
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
+18
View File
@@ -1614,6 +1614,24 @@ void TLSWrap::CertCbDone(const FunctionCallbackInfo<Value>& args) {
unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
return ThrowCryptoError(env, err, "CertCbDone");
}
// setSniContext copies the cert via SSL_use_certificate which does not
// carry over pre-compressed certificate data (comp_cert). If the new
// context has certificate compression configured, set the compression
// preferences on this connection and apply the cached compressed cert
// data so the server can send CompressedCertificate messages.
#ifdef NODE_OPENSSL_HAS_CERT_COMP
if (sc->HasCertCompression()) {
SSL_set1_cert_comp_preference(
w->ssl_.get(), sc->CertCompPrefs(), sc->CertCompPrefsLen());
for (const auto& cc : sc->CompressedCerts()) {
SSL_set1_compressed_cert(w->ssl_.get(),
cc.algorithm,
const_cast<unsigned char*>(cc.data.data()),
cc.data.size(),
cc.orig_length);
}
}
#endif
} else if (ctx->IsObject()) {
// Failure: incorrect SNI context object
Local<Value> err = Exception::TypeError(env->sni_context_err_string());
+4
View File
@@ -22,6 +22,10 @@
#include <string>
#include <vector>
#if OPENSSL_VERSION_NUMBER >= 0x30200000L && !defined(OPENSSL_NO_COMP_ALG)
#define NODE_OPENSSL_HAS_CERT_COMP 1
#endif
namespace node::crypto {
// Currently known sizes of commonly used OpenSSL struct sizes.
// OpenSSL considers it's various structs to be opaque and the
@@ -0,0 +1,261 @@
'use strict';
const common = require('../common');
if (!common.hasCrypto) common.skip('missing crypto');
const assert = require('assert');
const tls = require('tls');
const net = require('net');
const { once } = require('events');
const fixtures = require('../common/fixtures');
const supportedAlgs = tls.getCertificateCompressionAlgorithms();
if (supportedAlgs.length === 0)
common.skip('certificate compression not supported by this OpenSSL build');
// Use small fixture certs for input validation tests.
const fixtureKey = fixtures.readKey('agent1-key.pem');
const fixtureCert = fixtures.readKey('agent1-cert.pem');
// Test: input validation
{
// Empty array is valid (means disabled, same as undefined)
tls.createSecureContext({
key: fixtureKey, cert: fixtureCert, certificateCompression: [],
});
// Non-array should throw
assert.throws(
() => tls.createSecureContext({ certificateCompression: true }),
{ code: 'ERR_INVALID_ARG_TYPE' }
);
assert.throws(
() => tls.createSecureContext({ certificateCompression: 'zlib' }),
{ code: 'ERR_INVALID_ARG_TYPE' }
);
// Invalid algorithm name should throw
assert.throws(
() => tls.createSecureContext({ certificateCompression: ['invalid'] }),
/must be 'zlib', 'brotli', or 'zstd'/
);
// Non-string entries should throw
assert.throws(
() => tls.createSecureContext({ certificateCompression: [1] }),
/must be 'zlib', 'brotli', or 'zstd'/
);
// Valid single algorithms should not throw
for (const algo of supportedAlgs) {
tls.createSecureContext({
key: fixtureKey, cert: fixtureCert, certificateCompression: [algo],
});
}
// Valid multiple algorithms should not throw
tls.createSecureContext({
key: fixtureKey, cert: fixtureCert,
certificateCompression: supportedAlgs,
});
// Default (no certificateCompression) still works
tls.createSecureContext({ key: fixtureKey, cert: fixtureCert });
// Protocol range that excludes TLSv1.3 should throw - RFC 8879 is 1.3-only.
assert.throws(
() => tls.createSecureContext({
key: fixtureKey, cert: fixtureCert,
maxVersion: 'TLSv1.2',
certificateCompression: [supportedAlgs[0]],
}),
/TLSv1\.3/,
);
}
// Test: certificate compression must not enable record-level compression.
//
// RFC 8879 certificate compression is unrelated to TLS record compression
// (the CRIME attack vector). The latter is disabled by Node at startup via
// sk_SSL_COMP_zero, and by modern OpenSSL defaults as well. To confirm, we
// Verify a ClientHello sent by Node only advertises null record compression.
(async () => {
const { promise: clientHelloReceived, resolve: onClientHello } =
Promise.withResolvers();
const tcpServer = net.createServer((socket) => {
socket.once('data', (chunk) => {
onClientHello(chunk);
socket.destroy();
});
socket.on('error', () => {});
});
tcpServer.listen(0);
await once(tcpServer, 'listening');
const probe = tls.connect({
port: tcpServer.address().port,
rejectUnauthorized: false,
certificateCompression: supportedAlgs,
});
probe.on('error', () => {});
const clientHello = await clientHelloReceived;
tcpServer.close();
probe.destroy();
// ClientHello layout (RFC 8446 4.1.2 + 5.1 record layer):
// record header (5) | handshake header (4) | legacy_version (2)
// | random (32) | session_id <1..32> | cipher_suites <2..>
// | compression_methods <1..> | extensions <2..>
assert.strictEqual(clientHello[0], 0x16); // Handshake record
assert.strictEqual(clientHello[5], 0x01); // ClientHello
let i = 5 + 4 + 2 + 32;
i += 1 + clientHello[i]; // Skip legacy_session_id
i += 2 + clientHello.readUInt16BE(i); // Skip cipher_suites
const methods = clientHello.subarray(i + 1, i + 1 + clientHello[i]);
// Must only advertise the null compression method.
assert.deepStrictEqual([...methods], [0x00]);
})().then(common.mustCall());
// Test: a CompressedCertificate whose uncompressed length exceeds OpenSSL's
// default max_cert_list (100 KB) is rejected before decompression, protecting
// against decompression bombs in malicious server's cert chains.
(async () => {
// Cert just repeats our existing fixture many times
const bigChain = Buffer.concat(
Array(200).fill(Buffer.from(fixtureCert))
);
const server = tls.createServer({
key: fixtureKey, cert: bigChain,
minVersion: 'TLSv1.3',
certificateCompression: [supportedAlgs[0]],
}, common.mustNotCall());
// The aborted handshake surfaces as a tlsClientError on the server too.
server.on('tlsClientError', () => {});
server.listen(0);
await once(server, 'listening');
// Client starts handshake, server sends enormous cert, client rejects:
const client = tls.connect({
port: server.address().port,
rejectUnauthorized: false,
minVersion: 'TLSv1.3',
certificateCompression: [supportedAlgs[0]],
});
const [err] = await once(client, 'error');
assert.strictEqual(err.code, 'ERR_SSL_EXCESSIVE_MESSAGE_SIZE');
server.close();
})().then(common.mustCall());
// Test: TLS connection with certificate compression reduces handshake size.
(async () => {
const key = fixtureKey;
// Include a massive certificate list. Doesn't matter that they're not a valid chain,
// we'll send them all and the client uses rejectUnauthorized: false.
const cert = Buffer.concat(Array(20).fill(Buffer.from(fixtureCert)));
// Helper: perform a TLS 1.3 handshake via a TCP proxy and return the total
// raw bytes transferred. The proxy counts bytes to measure the on-the-wire
// handshake size (which reflects certificate compression savings).
async function measureHandshakeBytes(serverOpts, clientOpts) {
const { promise: serverConnected, resolve: onServerConn } = Promise.withResolvers();
const server = tls.createServer(serverOpts, common.mustCall((socket) => {
onServerConn();
socket.destroy();
}));
server.listen(0);
await once(server, 'listening');
let proxyClientConn;
const proxy = net.createServer(common.mustCall((clientConn) => {
proxyClientConn = clientConn;
const serverConn = net.connect(server.address().port);
clientConn.pipe(serverConn);
serverConn.pipe(clientConn);
serverConn.on('error', () => {});
clientConn.on('error', () => {});
}));
proxy.listen(0);
await once(proxy, 'listening');
const client = tls.connect({
port: proxy.address().port,
rejectUnauthorized: false,
minVersion: 'TLSv1.3',
...clientOpts,
});
await serverConnected;
const totalBytes = proxyClientConn.bytesRead + proxyClientConn.bytesWritten;
client.destroy();
server.close();
proxy.close();
return totalBytes;
}
const baseline = await measureHandshakeBytes(
{ key, cert, minVersion: 'TLSv1.3' },
{},
);
// Test each compression algorithm produces a measurably smaller handshake.
// Certificate compression (RFC 8879) compresses the Certificate message
// during the TLS 1.3 handshake. With the large repeated cert list above, all
// supported algorithms achieve ratios well below 0.5.
for (const algo of supportedAlgs) {
const compressed = await measureHandshakeBytes(
{ key, cert, minVersion: 'TLSv1.3', certificateCompression: [algo] },
{ certificateCompression: [algo] },
);
const ratio = compressed / baseline;
assert.ok(
ratio < 0.5,
`Expected ${algo} compressed handshake (${compressed} bytes, ` +
`ratio=${ratio.toFixed(3)}) to be <50% of baseline ` +
`(${baseline} bytes)`
);
}
// Test: certificate compression works through SNI callback.
// The server uses a default context without compression, and an SNI context
// with compression enabled. The client connects with an SNI hostname that
// triggers the SNI callback, switching to the compressed context.
{
const sniCalled = common.mustCall((hostname, cb) => {
if (hostname === 'compressed.example.com') {
const ctx = tls.createSecureContext({
key, cert,
certificateCompression: [supportedAlgs[0]],
});
cb(null, ctx);
} else {
cb(null);
}
});
const sniBytes = await measureHandshakeBytes(
{
key: fixtureKey, cert: fixtureCert,
minVersion: 'TLSv1.3',
SNICallback: sniCalled,
},
{
servername: 'compressed.example.com',
certificateCompression: [supportedAlgs[0]],
},
);
const sniRatio = sniBytes / baseline;
assert.ok(
sniRatio < 0.5,
`Expected SNI compressed handshake (${sniBytes} bytes, ` +
`ratio=${sniRatio.toFixed(3)}) to be <50% of baseline ` +
`(${baseline} bytes)`
);
}
})().then(common.mustCall());