Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/js/internal/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ const abortedSymbol = Symbol("aborted");
const headerStateSymbol = Symbol("headerState");
const eofInProgress = Symbol("eofInProgress");
const fakeSocketSymbol = Symbol("fakeSocket");
const isTlsSymbol = Symbol("is_tls");
const kHandle = Symbol("handle");
const kRealListen = Symbol("kRealListen");
const noBodySymbol = Symbol("noBody");
Expand Down Expand Up @@ -503,7 +502,6 @@ export {
getMaxHTTPHeaderSize,
hasServerResponseFinished,
headerStateSymbol,
isTlsSymbol,
kAbortController,
kCloseCallback,
kHandle,
Expand Down
90 changes: 90 additions & 0 deletions src/js/internal/tls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,97 @@ function processPfxOptions(options) {
return out;
}

// Node.js only requests a client certificate when `requestCert: true`.
// The uSockets SSL context treats `ca` alone as "verify peer", so without
// these two flags an `https.Server({ ca })` would reject every client that
// doesn't present a cert. Mirror tls.Server (net.ts): default `requestCert`
// to false and, when not requesting, force `rejectUnauthorized` to false so
// the CA is loaded into the trust store without requiring a client cert.
Comment thread
robobun marked this conversation as resolved.
Resolved
function normalizeServerTls(tls) {
const requestCert = !!tls.requestCert;
tls.requestCert = requestCert;
tls.rejectUnauthorized = requestCert ? tls.rejectUnauthorized !== false : false;
return tls;
}

// The `tls` config for Bun.serve behind an https.Server. Always returns a config, so the
// listener speaks TLS without key/cert like Node's tls.Server.
Comment thread
robobun marked this conversation as resolved.
Resolved
function httpsServerTlsOptions(options) {
// Node's https.Server accepts PKCS#12 bundles (pfx [+ passphrase]); fold
// them into plain key/cert/ca so the native TLS config sees PEM material.
Comment thread
robobun marked this conversation as resolved.
Resolved
let tlsOptions = options;
if (options.pfx) {
tlsOptions = processPfxOptions(options);
}

let cert = tlsOptions.cert;
if (cert) {
throwOnInvalidTLSArray("options.cert", cert);
}

let key = tlsOptions.key;
if (key) {
throwOnInvalidTLSArray("options.key", key);
}

let ca = tlsOptions.ca;
// PKCS#12-embedded CAs extend the trust set; the server path hands raw
// {key, cert, ca} to the native config and has no addCACert hook, so fold
// them into `ca` (mirrors tls.Server.setSecureContext).
Comment thread
robobun marked this conversation as resolved.
Resolved
const pfxExtraCAs = tlsOptions._pfxExtraCACerts;
if (pfxExtraCAs?.length) {
ca = ca == null ? pfxExtraCAs : $isArray(ca) ? [...ca, ...pfxExtraCAs] : [ca, ...pfxExtraCAs];
}
if (ca) {
throwOnInvalidTLSArray("options.ca", ca);
}

let passphrase = options.passphrase;
if (passphrase && typeof passphrase !== "string") {
throw $ERR_INVALID_ARG_TYPE("options.passphrase", "string", passphrase);
}

let serverName = options.servername;
if (serverName && typeof serverName !== "string") {
throw $ERR_INVALID_ARG_TYPE("options.servername", "string", serverName);
}

let secureOptions = options.secureOptions || 0;
if (secureOptions && typeof secureOptions !== "number") {
throw $ERR_INVALID_ARG_TYPE("options.secureOptions", "number", secureOptions);
}

// Translate minVersion/maxVersion/secureProtocol into the integer
// protocol range the native layer applies (secureProtocol wins, like
// Node's SecureContext::Init); 0 keeps the native defaults.
Comment thread
robobun marked this conversation as resolved.
Resolved
validateSecureProtocol(options.secureProtocol);
let minVersion, maxVersion;
const range = secureProtocolToVersionRange(options.secureProtocol);
if (range) {
minVersion = range[0];
maxVersion = range[1];
} else {
minVersion = tlsStringToProtocolVersion(options.minVersion);
maxVersion = tlsStringToProtocolVersion(options.maxVersion);
}
return normalizeServerTls({
serverName,
key,
cert,
ca,
passphrase,
secureOptions,
minVersion,
maxVersion,
ciphers: typeof options.ciphers === "string" && options.ciphers ? options.ciphers : undefined,
requestCert: options.requestCert,
rejectUnauthorized: options.rejectUnauthorized,
});
}

export {
httpsServerTlsOptions,
normalizeServerTls,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
processPfxOptions,
secureProtocolToVersionRange,
throwOnInvalidTLSArray,
Expand Down
98 changes: 2 additions & 96 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ const {
emitCloseNT,
NodeHTTPResponseAbortEvent,
STATUS_CODES,
isTlsSymbol,
hasServerResponseFinished,
NodeHTTPBodyReadState,
eofInProgress,
Expand Down Expand Up @@ -234,19 +233,6 @@ function emitListenErrorNextTick(self, err) {
self.emit("error", err);
}

// Node.js only requests a client certificate when `requestCert: true`.
// The uSockets SSL context treats `ca` alone as "verify peer", so without
// these two flags an `https.Server({ ca })` would reject every client that
// doesn't present a cert. Mirror tls.Server (net.ts): default `requestCert`
// to false and, when not requesting, force `rejectUnauthorized` to false so
// the CA is loaded into the trust store without requiring a client cert.
function normalizeServerTls(tls) {
const requestCert = !!tls.requestCert;
tls.requestCert = requestCert;
tls.rejectUnauthorized = requestCert ? tls.rejectUnauthorized !== false : false;
return tls;
}

// Node registers connectionListener on every http.Server so `server.emit("connection", socket)`
// works for foreign Duplex sockets. The native listener handles its own sockets end to end;
// this picks up the rest. https://github.com/nodejs/node/blob/main/lib/_http_server.js
Expand All @@ -260,6 +246,7 @@ function connectionListener(this: Server, socket) {
});
}

// Like Node, http.Server ignores key/cert/ca/pfx. https.Server (https.ts) sets its own TLS config.
function Server(options, callback): void {
if (!(this instanceof Server)) return new Server(options, callback);
EventEmitter.$call(this);
Expand Down Expand Up @@ -288,87 +275,6 @@ function Server(options, callback): void {
} else {
validateObject(options, "options");
options = { ...options };
const tlsHelpers = options.pfx || options.cert || options.key || options.ca ? require("internal/tls") : undefined;

// Node's https.Server accepts PKCS#12 bundles (pfx [+ passphrase]); fold
// them into plain key/cert/ca so the native TLS config sees PEM material.
let tlsOptions = options;
if (options.pfx) {
tlsOptions = tlsHelpers.processPfxOptions(options);
this[isTlsSymbol] = true;
}

let cert = tlsOptions.cert;
if (cert) {
tlsHelpers.throwOnInvalidTLSArray("options.cert", cert);
this[isTlsSymbol] = true;
}

let key = tlsOptions.key;
if (key) {
tlsHelpers.throwOnInvalidTLSArray("options.key", key);
this[isTlsSymbol] = true;
}

let ca = tlsOptions.ca;
// PKCS#12-embedded CAs extend the trust set; the server path hands raw
// {key, cert, ca} to the native config and has no addCACert hook, so fold
// them into `ca` (mirrors tls.Server.setSecureContext).
const pfxExtraCAs = tlsOptions._pfxExtraCACerts;
if (pfxExtraCAs?.length) {
ca = ca == null ? pfxExtraCAs : $isArray(ca) ? [...ca, ...pfxExtraCAs] : [ca, ...pfxExtraCAs];
}
if (ca) {
tlsHelpers.throwOnInvalidTLSArray("options.ca", ca);
this[isTlsSymbol] = true;
}

let passphrase = options.passphrase;
if (passphrase && typeof passphrase !== "string") {
throw $ERR_INVALID_ARG_TYPE("options.passphrase", "string", passphrase);
}

let serverName = options.servername;
if (serverName && typeof serverName !== "string") {
throw $ERR_INVALID_ARG_TYPE("options.servername", "string", serverName);
}

let secureOptions = options.secureOptions || 0;
if (secureOptions && typeof secureOptions !== "number") {
throw $ERR_INVALID_ARG_TYPE("options.secureOptions", "number", secureOptions);
}

if (this[isTlsSymbol]) {
const { validateSecureProtocol, secureProtocolToVersionRange, tlsStringToProtocolVersion } = tlsHelpers;
// Translate minVersion/maxVersion/secureProtocol into the integer
// protocol range the native layer applies (secureProtocol wins, like
// Node's SecureContext::Init); 0 keeps the native defaults.
validateSecureProtocol(options.secureProtocol);
let minVersion, maxVersion;
const range = secureProtocolToVersionRange(options.secureProtocol);
if (range) {
minVersion = range[0];
maxVersion = range[1];
} else {
minVersion = tlsStringToProtocolVersion(options.minVersion);
maxVersion = tlsStringToProtocolVersion(options.maxVersion);
}
this[tlsSymbol] = normalizeServerTls({
serverName,
key,
cert,
ca,
passphrase,
secureOptions,
minVersion,
maxVersion,
ciphers: typeof options.ciphers === "string" && options.ciphers ? options.ciphers : undefined,
requestCert: options.requestCert,
rejectUnauthorized: options.rejectUnauthorized,
});
} else {
this[tlsSymbol] = null;
}
}

this[optionsSymbol] = options;
Expand Down Expand Up @@ -551,7 +457,7 @@ Server.prototype.listen = function () {

const otherTLS = arg0.tls;
if (otherTLS && $isObject(otherTLS)) {
tls = normalizeServerTls({ ...otherTLS });
tls = require("internal/tls").normalizeServerTls({ ...otherTLS });
}
} else if (typeof arg0 === "string" && !(Number(arg0) >= 0)) {
// (path[...][, cb])
Expand Down
17 changes: 14 additions & 3 deletions src/js/node/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
// The client portions (Agent, request, get) are a port of Node.js's lib/https.js
// https://github.com/nodejs/node/blob/v26.3.0/lib/https.js
const http = require("node:http");
const { httpsServerTlsOptions } = require("internal/tls");
const { isIP } = require("internal/net/isIP");
const { urlToHttpOptions } = require("internal/url");
const { kEmptyObject, once } = require("internal/shared");
const { validateObject } = require("internal/validators");
const { kProxyConfig, checkShouldUseProxy, kWaitForProxyTunnel } = require("internal/http");
const { kProxyConfig, checkShouldUseProxy, kWaitForProxyTunnel, tlsSymbol, optionsSymbol } = require("internal/http");
const { validateHeaderValue } = require("node:_http_common");

const ArrayPrototypeShift = Array.prototype.shift;
Expand Down Expand Up @@ -494,6 +495,16 @@ Agent.prototype._evictSession = function _evictSession(key) {

const { shouldUseEnvProxy } = require("node:_http_agent");

// Node's https.Server is a tls.Server: it always speaks TLS, and it reads the TLS
// options that http.Server ignores.
Comment thread
robobun marked this conversation as resolved.
Resolved
function Server(options, requestListener): void {
if (!(this instanceof Server)) return new Server(options, requestListener);
http.Server.$call(this, options, requestListener);
this[tlsSymbol] = httpsServerTlsOptions(this[optionsSymbol]);
return this;
}
$toClass(Server, "Server", http.Server);

// Like Node's https.Server constructor: default ALPNProtocols to ['http/1.1']
// when neither ALPNProtocols nor ALPNCallback was given, and store the
// normalized protocol list / callback on the server instance the way
Expand All @@ -514,7 +525,7 @@ function createServer(options, requestListener) {
// ALPN requests are always answered with http/1.1.
options.ALPNProtocols = ["http/1.1"];
}
const server = http.createServer(options, requestListener);
const server = new Server(options, requestListener);
const optionsALPNProtocols = options.ALPNProtocols;
if (optionsALPNProtocols) {
require("node:tls").convertALPNProtocols(optionsALPNProtocols, server);
Expand All @@ -531,7 +542,7 @@ var https = {
timeout: 5000,
proxyEnv: shouldUseEnvProxy() ? process.env : undefined,
}),
Server: http.Server,
Server,
createServer,
get,
request,
Expand Down
64 changes: 64 additions & 0 deletions test/js/node/http/node-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1433,6 +1433,70 @@ describe("node https server", async () => {
});
});

// Node's http.Server ignores TLS material in its options and always serves
// plaintext. Node's https.Server is a tls.Server: it speaks TLS even when no
// key/cert is given (handshakes then fail).
describe.concurrent("http.Server vs https.Server TLS mode", () => {
const handler = (req, res) => res.end(`proto=${req.socket.encrypted ? "TLS" : "plain"}`);

function plaintextGet(port: number): Promise<string> {
const { promise, resolve } = Promise.withResolvers<string>();
const chunks: Buffer[] = [];
const socket = connect({ port, host: "127.0.0.1" }, () => {
socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");
});
socket.on("data", chunk => chunks.push(chunk));
socket.on("error", () => {});
socket.on("close", () => resolve(Buffer.concat(chunks).toString()));
return promise;
}

it.each([
["key and cert", { key: tlsCert.key, cert: tlsCert.cert }],
["ca only", { ca: tlsCert.cert }],
])("http.createServer with %s serves plaintext", async (_, options) => {
const server = createServer(options, handler);
try {
const url = await listen(server);
expect(server instanceof https.Server).toBe(false);
const res = await fetch(url);
expect(await res.text()).toBe("proto=plain");
expect(await plaintextGet(Number(url.port))).toStartWith("HTTP/1.1 200");
} finally {
server.close();
}
});

it.each([
["no options", undefined],
["empty options", {}],
])("https.createServer with %s refuses plaintext", async (_, options) => {
const server = options === undefined ? createHttpsServer(handler) : createHttpsServer(options, handler);
try {
const url = await listen(server);
expect(server instanceof https.Server).toBe(true);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(server instanceof http.Server).toBe(true);
expect(await plaintextGet(Number(url.port))).not.toStartWith("HTTP/1.1");
await expect(fetch(`https://127.0.0.1:${url.port}/`, { tls: { rejectUnauthorized: false } })).rejects.toThrow();
} finally {
server.close();
}
});

it("https.createServer with key and cert serves TLS only", async () => {
const server = createHttpsServer({ key: tlsCert.key, cert: tlsCert.cert }, handler);
try {
const url = await listen(server, "https");
expect(server instanceof https.Server).toBe(true);
const res = await fetch(url, { tls: { rejectUnauthorized: false } });
expect(await res.text()).toBe("proto=TLS");
expect(await plaintextGet(Number(url.port))).not.toStartWith("HTTP/1.1");
} finally {
server.close();
}
});
});

describe("server.address should be valid IP", () => {
it("should return null before listening", done => {
const server = createServer((req, res) => {});
Expand Down