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
71 changes: 59 additions & 12 deletions src/workerd/api/global-scope.c++
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,34 @@ kj::Promise<void> ServiceWorkerGlobalScope::connect(kj::String host,

KJ_IF_SOME(handler, eh.connect) {
// Has a connect handler!
response.accept(200, "OK", headers);
auto& ioContext = IoContext::current();
jsg::Lock& js = lock;

// A peer that asked for TLS from the start must not see the connection open before it is
// secure. The handler can't run that handshake, so it accepts the connection itself once it
// has made it secure further along. WorkerEntrypoint::connect() lets such a connection through
// only when connect_handler_immediate_tls is enabled.
kj::Maybe<kj::Rc<ConnectAcceptance>> acceptance;
if (settings.useTls) {
KJ_ASSERT(FeatureFlags::get(js).getConnectHandlerImmediateTls());
acceptance = kj::rc<ConnectAcceptance>(response, ioContext.getHeaderTable());
} else {
response.accept(200, "OK", headers);
}
kj::ConstString unacceptedReason =
"The connect() handler finished without accepting a connection that requested "
"secureTransport 'on'. Call socket.accept() once the connection is secure."_kjc;
// `response` goes away once this request is over, and the handler's socket can outlive it, so
// the acceptance must give `response` up however the handler finishes: by returning or
// throwing, synchronously or asynchronously, or by being canceled. Set up before anything below
// can throw. On a normal return, it moves into the returned promise's attachments.
auto abandonAcceptance = kj::defer(
[acceptance = acceptance.map([](kj::Rc<ConnectAcceptance>& a) { return a.addRef(); }),
reason = unacceptedReason.clone()]() mutable {
KJ_IF_SOME(a, acceptance) {
a->abandon(reason);
}
});

// Using neuterable stream to manage lifetime of stream promises. We MUST neuter this when the
// promise returned to the caller resolves because `connection` is owned by the caller and will
Expand All @@ -251,13 +278,14 @@ kj::Promise<void> ServiceWorkerGlobalScope::connect(kj::String host,
});
KJ_ON_SCOPE_FAILURE(ownConnection->neuter(makeNeuterException(NeuterReason::THREW_EXCEPTION)));

auto& ioContext = IoContext::current();
jsg::Lock& js = lock;

// Support startTls if the transport that delivered this CONNECT offered a tlsStarter slot.
// A peer that asked for TLS from the start shows up as secureTransport 'on', which tells the
// handler to call accept() once it has made the connection secure. Otherwise, support startTls
// if the transport that delivered this CONNECT offered a tlsStarter slot.
auto tlsStarter = kj::heap<kj::TlsStarterCallback>();
auto secureTransport = SecureTransportKind::OFF;
KJ_IF_SOME(starter, settings.tlsStarter) {
if (settings.useTls) {
secureTransport = SecureTransportKind::ON;
} else KJ_IF_SOME(starter, settings.tlsStarter) {
if (FeatureFlags::get(lock).getConnectHandlerStartTls()) {
KJ_IF_SOME(s, starter) {
// The transport can run a real handshake on this connection -- a TCP listener holding a
Expand All @@ -276,6 +304,13 @@ kj::Promise<void> ServiceWorkerGlobalScope::connect(kj::String host,
}
}

kj::Own<kj::AsyncIoStream> socketConnection = ownConnection.addRef().toOwn();
KJ_IF_SOME(a, acceptance) {
// Nothing crosses the connection until the handler accepts it. See whenAccepted().
socketConnection = kj::newPromisedStream(a->whenAccepted().then(
[connection = kj::mv(socketConnection)]() mutable { return kj::mv(connection); }));
}

// We set isDefaultFetchPort to false here – sockets.c++ sets it for ports 443 and 8080 to
// provide a more descriptive error message for HTTP, but this is not relevant on the TCP server
// side.
Expand All @@ -285,17 +320,29 @@ kj::Promise<void> ServiceWorkerGlobalScope::connect(kj::String host,
// The handler is also the server side of any TLS upgrade, so there is no peer name to verify:
// both starters set up above ignore the hostname they are given. `host` is passed as the
// domain only because startTls() and proxyTo() refuse to upgrade a socket that has none.
jsg::Ref<Socket> jsSocket =
setupSocket(js, ownConnection.addRef().toOwn(), kj::mv(clientAddress), kj::str(host),
SocketOptions{.allowHalfOpen = true}, kj::mv(tlsStarter), secureTransport,
SocketProtocol::TCP, kj::str(host) /* domain */, false, kj::none);
jsg::Ref<Socket> jsSocket = setupSocket(js, kj::mv(socketConnection), kj::mv(clientAddress),
kj::str(host), SocketOptions{.allowHalfOpen = true}, kj::mv(tlsStarter), secureTransport,
SocketProtocol::TCP, kj::str(host) /* domain */, false /* isDefaultFetchPort */, kj::none);
// handleProxyStatus() is required to indicate that the socket was opened properly. Since the
// connection is already open at this point, exception handling is not required.
// connection is already open at this point, exception handling is not required. This holds
// even while the connection waits for accept(): the handler needs its socket to make the
// connection secure, and the peer's `opened` is what waits.
jsSocket->handleProxyStatus(js, kj::Promise<kj::Maybe<kj::Exception>>(kj::none));
KJ_IF_SOME(a, acceptance) {
jsSocket->setAcceptance(ioContext.addObject(a.addRef()));
}

kj::Maybe<SpanBuilder> span = ioContext.makeTraceSpan("connect_handler"_kjc);
auto promise = handler(js, kj::mv(jsSocket), eh.env.addRef(js), eh.getCtx());
Comment thread
fhanau marked this conversation as resolved.
Resolved
return ioContext.awaitJs(js, kj::mv(promise)).attach(kj::mv(span), kj::mv(deferredNeuter));
auto result = ioContext.awaitJs(js, kj::mv(promise));
KJ_IF_SOME(a, acceptance) {
// A handler that returns normally without accepting is an error in the handler: throwing
// fails the connection and reports it like any other exception the handler throws.
result = result.then([a = a.addRef(), reason = kj::mv(unacceptedReason)]() mutable {
JSG_REQUIRE(!a->abandon(reason), Error, reason);
});
}
return result.attach(kj::mv(span), kj::mv(abandonAcceptance), kj::mv(deferredNeuter));
}
lock.logWarningOnce("Received a connect event but we lack a handler. "
"Did you remember to export a connect() function?");
Expand Down
56 changes: 56 additions & 0 deletions src/workerd/api/sockets.c++
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,9 @@ jsg::Promise<void> Socket::close(jsg::Lock& js) {
}

isClosing = true;
KJ_IF_SOME(a, acceptance) {
a->fail("The connect() handler's socket closed before it accepted the connection."_kj);
}
writable.setPendingClosure(js);
readable.setPendingClosure(js);

Expand Down Expand Up @@ -1099,6 +1102,53 @@ jsg::Promise<void> Socket::close(jsg::Lock& js) {
});
}

void ConnectAcceptance::accept() {
KJ_IF_SOME(failed, state.tryGet<Failed>()) {
JSG_FAIL_REQUIRE(Error, failed.reason);
}
KJ_IF_SOME(pending, state.tryGet<Pending>()) {
// Settle the state before answering, so that nothing the answer sets off can answer again.
auto& response = pending.response;
state = Accepted{};
response.accept(200, "OK", headers);
accepted.signal();
}
}

void ConnectAcceptance::setFailed(kj::StringPtr reason) {
state = Failed{kj::str(reason)};
accepted.reject(JSG_KJ_EXCEPTION(DISCONNECTED, Error, reason));
}

void ConnectAcceptance::fail(kj::StringPtr reason) {
KJ_IF_SOME(pending, state.tryGet<Pending>()) {
auto& response = pending.response;
setFailed(reason);
// The peer learns only that the connection failed: Socket::handleProxyStatus() reports every
// unsuccessful status the same way.
response.reject(502, "Bad Gateway", headers, static_cast<uint64_t>(0));
}
}

bool ConnectAcceptance::abandon(kj::StringPtr reason) {
if (isPending()) {
setFailed(reason);
return true;
}
return false;
}

void Socket::setAcceptance(IoOwn<ConnectAcceptance> pendingAcceptance) {
acceptance = kj::mv(pendingAcceptance);
}

void Socket::accept() {
auto& a = JSG_REQUIRE_NONNULL(acceptance, TypeError,
"accept() can only be called on the socket passed to a connect() handler whose peer "
"requested secureTransport 'on'.");
a->accept();
}

jsg::Promise<void> Socket::proxyTo(
jsg::Lock& js, jsg::Ref<Socket> sock, jsg::Optional<PipeToOptions> options) {
jsg::Optional<PipeToOptions> optionsCopy = kj::none;
Expand Down Expand Up @@ -1615,6 +1665,12 @@ void Socket::serialize(jsg::Lock& js, jsg::Serializer& serializer) {
case OpenedState::OPENED:
break;
}
// Only the handler that received the connection can answer its peer.
KJ_IF_SOME(a, acceptance) {
JSG_REQUIRE(!a->isPending(), DOMDataCloneError,
"A Socket can only be serialized after its connection has been accepted. Call "
"`socket.accept()` before transferring the socket over RPC.");
}

// Serialize the socket metadata, referencing the stream externals
// The call to write is synchronous, so capturing this is safe.
Expand Down
69 changes: 69 additions & 0 deletions src/workerd/api/sockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <workerd/jsg/url.h>

#include <kj/refcount.h>
#include <kj/sticky-flag.h>

namespace workerd {

Expand Down Expand Up @@ -143,6 +144,59 @@ struct SocketStreamErrnos final: public kj::Refcounted {
kj::Maybe<kj::StringPtr> write;
};

// The answer to a CONNECT delivered to a connect() handler, when the peer asked for TLS from the
// start. The handler can't run that handshake, so the runtime doesn't accept such a connection on
// delivery. The handler accepts it with Socket::accept() once it has made the connection secure
// further along. Until then the peer's `opened` stays pending, and nothing crosses the connection
// in either direction: see whenAccepted().
//
// ServiceWorkerGlobalScope::connect() creates one and abandons it when the handler finishes, since
// `response` lives only that long.
class ConnectAcceptance final {
public:
ConnectAcceptance(kj::HttpService::ConnectResponse& response, const kj::HttpHeaderTable& table)
: state(Pending{response}),
headers(table) {}

// Accepts the connection. Accepting it again does nothing, and accepting a connection that has
// already failed throws the reason it failed.
void accept();

// Fails the connection with `reason`, if it hasn't been accepted or failed already.
void fail(kj::StringPtr reason);

// Gives up `response` without answering it, because it is about to go away: the handler has
// finished, and whatever finishes the request answers the peer instead. Returns whether the
// connection was still waiting to be accepted. A later accept() throws `reason`.
bool abandon(kj::StringPtr reason);

bool isPending() const {
return state.is<Pending>();
}

// Resolves once the connection is accepted, and rejects once it has failed or been abandoned.
// The handler's socket reads and writes through a stream that waits for this, so that the
// peer's early writes stay in the transport, under backpressure, until there is somewhere secure
// for them to go, and are never read at all if the connection fails.
kj::Promise<void> whenAccepted() {
return accepted.whenSignaled();
}

private:
struct Pending {
kj::HttpService::ConnectResponse& response;
};
struct Accepted {};
struct Failed {
kj::String reason;
};
kj::OneOf<Pending, Accepted, Failed> state;
kj::HttpHeaders headers;
kj::StickyFlag accepted;

void setFailed(kj::StringPtr reason);
};

class Socket: public jsg::Object {
public:
Socket(jsg::Lock& js,
Expand Down Expand Up @@ -239,6 +293,15 @@ class Socket: public jsg::Object {
KJ_UNREACHABLE;
}

// Marks this socket as the one passed to a connect() handler whose peer asked for TLS from the
// start, so that the connection waits for accept().
void setAcceptance(IoOwn<ConnectAcceptance> acceptance);

// Accepts a connection whose peer asked for TLS from the start, which the handler sees as
// `secureTransport` 'on'. The handler calls it once it has made the connection secure, after
// which the peer's `opened` resolves. Accepting again does nothing.
void accept();

// Takes ownership of the underlying connection stream, detaching the readable and writable streams.
// This is a destructive operation that renders the Socket unusable for further I/O operations.
kj::Own<kj::AsyncIoStream> takeConnectionStream(jsg::Lock& js);
Expand Down Expand Up @@ -324,6 +387,9 @@ class Socket: public jsg::Object {
if (flags.getWorkerdExperimental()) {
JSG_METHOD(proxyTo);
}
if (flags.getConnectHandlerImmediateTls()) {
JSG_METHOD(accept);
}
}

JSG_SERIALIZABLE(rpc::SerializationTag::SOCKET);
Expand Down Expand Up @@ -378,6 +444,9 @@ class Socket: public jsg::Object {
SocketProtocol protocol;
// The domain/ip this socket is connected to. Used for startTls.
kj::Maybe<kj::String> domain;
// Set on the socket passed to a connect() handler whose peer asked for TLS from the start: the
// pending answer to the peer, which the handler gives with accept().
kj::Maybe<IoOwn<ConnectAcceptance>> acceptance;
// Whether the port this socket connected to is 80/443. Used for nicer errors.
bool isDefaultFetchPort;
kj::Maybe<kj::StringPtr> connectErrno;
Expand Down
10 changes: 7 additions & 3 deletions src/workerd/api/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -276,15 +276,19 @@ wd_test(
src = "connect-handler-test.wd-test",
args = ["--experimental"],
data = [
"connect-handler-immediate-tls-test.js",
"connect-handler-server.key",
"connect-handler-server.pem",
"connect-handler-starttls-test.js",
"connect-handler-test.js",
"connect-handler-test-proxy.js",
],
listen_port_bindings = CONNECT_HANDLER_PORT_BINDINGS | {"connect-starttls": "STARTTLS_PORT"},
# The STARTTLS listener's certificate names 127.0.0.1, not the random loopback address the
# supervisor would otherwise pick.
listen_port_bindings = CONNECT_HANDLER_PORT_BINDINGS | {
"connect-starttls": "STARTTLS_PORT",
"connect-tls": "TLS_PORT",
},
# The TLS listeners' certificate names 127.0.0.1, not the random loopback address the supervisor
# would otherwise pick.
sidecar_randomize_ip = False,
)

Expand Down
Loading
Loading