Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
18 changes: 14 additions & 4 deletions src/workerd/api/sockets.c++
Original file line number Diff line number Diff line change
Expand Up @@ -1227,8 +1227,7 @@ jsg::Ref<Socket> Socket::startTls(jsg::Lock& js, jsg::Optional<TlsOptions> tlsOp
(self, openedResolver), (jsg::Lock & js) mutable {
auto& context = IoContext::current();

self->writable.detach(js);
self->readable.detach(js, IgnoreDisturbed::YES);
self->detachStreams(js);

// We should set this before closedResolver.resolve() in order to give the user
// the option to check if the closed promise is resolved due to upgrade or not.
Expand Down Expand Up @@ -1932,15 +1931,26 @@ kj::Array<SocketsModule::InboundListener> SocketsModule::getInboundListeners(jsg
};
}

void Socket::detachStreams(jsg::Lock& js) {
writable.detach(js);

// Detaching leaves this socket's readable neutralized, which is all we want: nothing reads the
// detached copy. Cancel it rather than just dropping it. Under the TypeScript streams
// implementation the copy is a JavaScript object, and until it is garbage-collected its native
// source would hold a reference to the connection, so the connection would stay open after its
// new owner closes it. Canceling the source only abandons this socket's own reads; it does not
// touch the connection.
readable.detach(js, IgnoreDisturbed::YES).forceCancel(js, kj::none).markAsHandled(js);
}

kj::Own<kj::AsyncIoStream> Socket::takeConnectionStream(jsg::Lock& js) {
// Set this so that if `close` is called after this, that no closure steps are taken and instead
// the `close` is a no-op.
isClosing = true;

// We do not care if the socket was disturbed, we require the user to ensure the socket is not
// being used.
writable.detach(js);
readable.detach(js, IgnoreDisturbed::YES);
detachStreams(js);

// Move the stream out of the socket, to ensure the stream is properly destroyed when the
// caller is done with it.
Expand Down
4 changes: 4 additions & 0 deletions src/workerd/api/sockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,10 @@ class Socket: public jsg::Object {
// Helper method for handleProxyStatus implementations.
void handleProxyError(jsg::Lock& js, kj::Exception e);

// Neutralizes the socket's streams when its connection is handed to another owner (startTls(),
// takeConnectionStream()), releasing their hold on the connection.
void detachStreams(jsg::Lock& js);

void resolveFulfiller(jsg::Lock& js, kj::Maybe<kj::Exception> maybeErr) {
KJ_IF_SOME(err, maybeErr) {
closedResolver.reject(js, err.clone());
Expand Down
6 changes: 6 additions & 0 deletions src/workerd/api/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,12 @@ wd_test(
data = ["connect-handler-starttls-lifetime-test.js"],
)

wd_test(
src = "connect-handler-starttls-close-test.wd-test",
args = ["--experimental"],
data = ["connect-handler-starttls-close-test.js"],
)

# Regression test for AUTOVULN-CLOUDFLARE-WORKERD-334: connect() handler must neuter the
# NeuterableIoStream when the handler promise resolves, preventing use-after-free.
wd_test(
Expand Down
53 changes: 53 additions & 0 deletions src/workerd/api/tests/connect-handler-starttls-close-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0
//
// close() on a socket upgraded with startTls() must close the connection under it, so that the
// other end's reads end. startTls() hands the connection to the socket it returns, and the
// plain-text socket it leaves behind must not keep the connection open.
//
// The connection is a tunnel to a Durable Object's connect() handler, which tells the test through
// RPC how its read ended.

import { DurableObject } from 'cloudflare:workers';
import { strictEqual } from 'node:assert';

export class Peer extends DurableObject {
#readEnded = Promise.withResolvers();

async connect(socket) {
const secure = socket.startTls();
await secure.opened;

// The test sends nothing, so this read ends only when the connection does.
const reader = secure.readable.getReader();
try {
const { done } = await reader.read();
this.#readEnded.resolve(done ? 'EOF' : 'data');
} catch (e) {
this.#readEnded.resolve(e.message);
}
}

readEnded() {
return this.#readEnded.promise;
}
}

export const closingUpgradedSocketClosesConnection = {
async test(ctrl, env) {
const stub = env.PEER.get(env.PEER.idFromName('peer'));
const socket = stub.connect('smtp.example.com:25', {
secureTransport: 'starttls',
});
await socket.opened;
const secure = socket.startTls();
await secure.opened;

await secure.close();
strictEqual(
await stub.readEnded(),
"Can't read from request stream because client disconnected."
);
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Workerd = import "/workerd/workerd.capnp";

# The same worker runs twice: once on the TypeScript streams implementation and once on the C++
# one, since startTls() detaches a socket's streams differently in each.
const unitTests :Workerd.Config = (
services = [
( name = "connect-handler-starttls-close-test",
worker = (
modules = .modules,
# connect_handler_starttls and typescript_implemented_streams are experimental.
compatibilityFlags = [
"nodejs_compat_v2", "connect_handler_starttls", "experimental",
"typescript_implemented_streams",
],
durableObjectNamespaces = [
(className = "Peer", uniqueKey = "7d2b4f1e9a6c4b3d8e5f0a1b2c3d4e5f"),
],
durableObjectStorage = (inMemory = void),
bindings = [(name = "PEER", durableObjectNamespace = "Peer")],
)
),
( name = "connect-handler-starttls-close-test-cpp-streams",
worker = (
modules = .modules,
compatibilityFlags = ["nodejs_compat_v2", "connect_handler_starttls", "experimental"],
durableObjectNamespaces = [
(className = "Peer", uniqueKey = "1a9e3c5b7d2f4e6a8b0c2d4e6f8a0b1c"),
],
durableObjectStorage = (inMemory = void),
bindings = [(name = "PEER", durableObjectNamespace = "Peer")],
)
),
],
);

const modules :List(Workerd.Worker.Module) = [
(name = "worker", esModule = embed "connect-handler-starttls-close-test.js"),
];
Loading