mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix: release origin connections after refused WebSocket upgrades (#7694)
This commit is contained in:
1 parent
8cff513c8d
commit
8b81638490
6 files changed
+193
-2
No files matched your search
@@ -1,9 +1,13 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.vertx.core.http.HttpClientRequest;
|
||||
import io.vertx.core.http.HttpClosedException;
|
||||
import io.vertx.core.http.HttpConnection;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.HttpVersion;
|
||||
import io.vertx.core.net.NetSocket;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* The parts of proxying a WebSocket handshake that the proxies Floci emulates share. An ALB and a
|
||||
@@ -13,6 +17,8 @@ import io.vertx.core.net.NetSocket;
|
||||
*/
|
||||
public final class WebSocketUpgrades {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebSocketUpgrades.class);
|
||||
|
||||
private WebSocketUpgrades() {
|
||||
}
|
||||
|
||||
@@ -34,6 +40,25 @@ public final class WebSocketUpgrades {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a refused connect() request once forwarding has finished or failed. Reading its
|
||||
* response does not finish the request, so the connection still holds a pool slot. Only the
|
||||
* expected closed-connection notification from this deliberate cleanup is logged at debug.
|
||||
*/
|
||||
public static void closeRefusedRequest(HttpClientRequest request) {
|
||||
HttpConnection connection = request.connection();
|
||||
request.exceptionHandler(err -> {
|
||||
if (err instanceof HttpClosedException) {
|
||||
LOG.debugv("Refused WebSocket origin connection closed: {0}", connection.remoteAddress());
|
||||
} else {
|
||||
LOG.warnv(err, "Unexpected error closing refused WebSocket origin connection to {0}",
|
||||
connection.remoteAddress());
|
||||
}
|
||||
});
|
||||
connection.close().onFailure(err ->
|
||||
LOG.warnv(err, "Could not close refused WebSocket origin connection to {0}", connection.remoteAddress()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies everything {@code source} reads to {@code destination}, pausing the source while the
|
||||
* destination's write queue is full. {@code onData} runs for each buffer, and {@code close} when
|
||||
|
||||
@@ -225,11 +225,13 @@ public class CloudFrontWebSocketProxy {
|
||||
});
|
||||
response.endHandler(ignored -> {
|
||||
clock.stop();
|
||||
WebSocketUpgrades.closeRefusedRequest(originRequest);
|
||||
viewerResponse.end();
|
||||
});
|
||||
response.exceptionHandler(err -> {
|
||||
clock.stop();
|
||||
LOG.debugv("CloudFront origin failed while refusing a WebSocket upgrade: {0}", err.getMessage());
|
||||
originRequest.reset();
|
||||
LOG.warnv(err, "CloudFront origin failed while refusing a WebSocket upgrade");
|
||||
viewerResponse.reset();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1598,7 +1598,15 @@ public class ElbV2DataPlane {
|
||||
if (resp.getHeader("Content-Length") == null) {
|
||||
req.response().setChunked(true);
|
||||
}
|
||||
resp.pipeTo(req.response());
|
||||
resp.pipeTo(req.response())
|
||||
.onComplete(result -> {
|
||||
if (result.failed()) {
|
||||
LOG.warnv(result.cause(),
|
||||
"Failed relaying refused WebSocket upgrade from {0}:{1}",
|
||||
host, port);
|
||||
}
|
||||
WebSocketUpgrades.closeRefusedRequest(clientReq);
|
||||
});
|
||||
return;
|
||||
}
|
||||
req.response().putHeader("Connection", "Upgrade");
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testutil.LogCapture;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.http.HttpClientRequest;
|
||||
import io.vertx.core.http.HttpClosedException;
|
||||
import io.vertx.core.http.HttpConnection;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WebSocketUpgradesTest {
|
||||
|
||||
@Mock
|
||||
HttpClientRequest request;
|
||||
|
||||
@Mock
|
||||
HttpConnection connection;
|
||||
|
||||
@Captor
|
||||
ArgumentCaptor<Handler<Throwable>> exceptionHandler;
|
||||
|
||||
@BeforeEach
|
||||
void configureConnection() {
|
||||
when(request.connection()).thenReturn(connection);
|
||||
when(connection.close()).thenReturn(Future.succeededFuture());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliberateCloseDoesNotWarnForExpectedClosedConnection() {
|
||||
List<LogRecord> records = LogCapture.capture(WebSocketUpgrades.class, () -> {
|
||||
WebSocketUpgrades.closeRefusedRequest(request);
|
||||
verify(request).exceptionHandler(exceptionHandler.capture());
|
||||
exceptionHandler.getValue().handle(new HttpClosedException("Connection was closed"));
|
||||
});
|
||||
|
||||
verify(connection).close();
|
||||
assertTrue(records.stream().allMatch(record -> record.getLevel().intValue() < Level.WARNING.intValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unexpectedRequestFailureKeepsItsWarningAndCause() {
|
||||
IllegalStateException failure = new IllegalStateException("unexpected transport failure");
|
||||
List<LogRecord> records = LogCapture.capture(WebSocketUpgrades.class, () -> {
|
||||
WebSocketUpgrades.closeRefusedRequest(request);
|
||||
verify(request).exceptionHandler(exceptionHandler.capture());
|
||||
exceptionHandler.getValue().handle(failure);
|
||||
});
|
||||
|
||||
assertEquals(1, records.size());
|
||||
assertEquals(Level.WARNING, records.getFirst().getLevel());
|
||||
assertSame(failure, records.getFirst().getThrown());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedConnectionCloseKeepsItsWarningAndCause() {
|
||||
IllegalStateException failure = new IllegalStateException("close failed");
|
||||
when(connection.close()).thenReturn(Future.failedFuture(failure));
|
||||
|
||||
List<LogRecord> records = LogCapture.capture(WebSocketUpgrades.class,
|
||||
() -> WebSocketUpgrades.closeRefusedRequest(request));
|
||||
|
||||
assertEquals(1, records.size());
|
||||
assertEquals(Level.WARNING, records.getFirst().getLevel());
|
||||
assertSame(failure, records.getFirst().getThrown());
|
||||
}
|
||||
}
|
||||
+32
@@ -192,6 +192,38 @@ class CloudFrontWebSocketIntegrationTest {
|
||||
assertEquals("upgrade refused", rejected.getBody().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedRefusalsDoNotExhaustOriginConnectionsAcrossDistributions() throws Exception {
|
||||
List<Distribution> distributions = List.of(
|
||||
createDistribution(policyBehavior(ALL_VIEWER)),
|
||||
createDistribution(policyBehavior(ALL_VIEWER)),
|
||||
createDistribution(policyBehavior(ALL_VIEWER)),
|
||||
createDistribution(policyBehavior(ALL_VIEWER)),
|
||||
createDistribution(policyBehavior(ALL_VIEWER)),
|
||||
createDistribution(policyBehavior(ALL_VIEWER)),
|
||||
createDistribution(policyBehavior(ALL_VIEWER)));
|
||||
|
||||
// All distribution hosts share the origin's default five-connection pool.
|
||||
for (int attempt = 0; attempt < 12; attempt++) {
|
||||
Distribution distribution = distributions.get(attempt % distributions.size());
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> connect(distribution, "/elsewhere/?transport=websocket"),
|
||||
"Refusal " + attempt + " must complete without waiting for a pool connection");
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(404, rejected.getStatus());
|
||||
assertEquals(List.of("one", "two"), rejected.getHeaders().getAll("X-Multi"));
|
||||
assertEquals("upgrade refused", rejected.getBody().toString());
|
||||
}
|
||||
|
||||
WebSocket socket = connect(distributions.getLast(), "/socket.io/?transport=websocket");
|
||||
try {
|
||||
assertEquals("transport=websocket:hello", exchange(socket, "hello"));
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
assertEquals(13, originUpgrades.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainRequestThroughDistributionCarriesNoUpgrade() {
|
||||
Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER));
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.elbv2;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.testing.RealElbV2DataPlaneProfile;
|
||||
import io.floci.aws.testutil.LogCapture;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
@@ -22,6 +23,7 @@ import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import static io.floci.aws.testing.AlbFixtures.createListener;
|
||||
import static io.floci.aws.testing.AlbFixtures.createLoadBalancer;
|
||||
@@ -70,6 +72,9 @@ class ElbV2WebSocketIntegrationTest {
|
||||
.requestHandler(request -> {
|
||||
if (!"websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
|
||||
request.response().setStatusCode(400).end("not an upgrade");
|
||||
} else if (request.path().startsWith("/broken/")) {
|
||||
request.response().setChunked(true).setStatusCode(503).write("partial")
|
||||
.onSuccess(ignored -> request.response().close());
|
||||
} else if (!request.path().startsWith("/socket.io/")) {
|
||||
request.response().headers()
|
||||
.add("Set-Cookie", "a=1; Path=/")
|
||||
@@ -161,6 +166,42 @@ class ElbV2WebSocketIntegrationTest {
|
||||
assertEquals("upgrade refused", rejected.getBody().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedRefusalsDoNotExhaustTargetConnections() throws Exception {
|
||||
// Exceed the data plane's 100-connection pool before opening a working tunnel.
|
||||
for (int attempt = 0; attempt < 110; attempt++) {
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> connect("/elsewhere/?transport=websocket"),
|
||||
"Refusal " + attempt + " must complete without waiting for a pool connection");
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(404, rejected.getStatus());
|
||||
assertEquals("upgrade refused", rejected.getBody().toString());
|
||||
}
|
||||
|
||||
WebSocket socket = connect("/socket.io/?transport=websocket");
|
||||
try {
|
||||
assertEquals("transport=websocket:hello", exchange(socket, "hello"));
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRefusalRelayLogsItsCauseAndAllowsAnotherUpgrade() throws Exception {
|
||||
LogCapture.awaitRecord(ElbV2DataPlane.class, Duration.ofSeconds(3),
|
||||
record -> record.getLevel().intValue() >= Level.WARNING.intValue()
|
||||
&& record.getThrown() != null
|
||||
&& record.getMessage().contains("Failed relaying refused WebSocket upgrade"),
|
||||
() -> assertThrows(ExecutionException.class, () -> connect("/broken/?transport=websocket")));
|
||||
|
||||
WebSocket socket = connect("/socket.io/?transport=websocket");
|
||||
try {
|
||||
assertEquals("transport=websocket:hello", exchange(socket, "hello"));
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainRequestStillReachesTargetWithoutUpgrade() {
|
||||
given()
|
||||
|
||||
Reference in new issue
Block a user