diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 28f12dc97..48d139359 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -1133,6 +1133,7 @@ public class WhisperServerService extends Application dynamicConfigurationManager.getConfiguration().getOmnibus(), config.getGrpc().idleTimeout()); environment.lifecycle().manage(omnibusLocalEventLoopGroup); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfiguration.java index 2a9b90bfe..545121d42 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfiguration.java @@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.Valid; +import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -80,6 +81,10 @@ public class DynamicConfiguration { @Valid private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration(); + @JsonProperty + @Valid + private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO); + @JsonProperty @Valid private DynamicTurnConfiguration turn = new DynamicTurnConfiguration(); @@ -150,6 +155,10 @@ public class DynamicConfiguration { return grpcAllowList; } + public DynamicOmnibusConfiguration getOmnibus() { + return omnibus; + } + public DynamicTurnConfiguration getTurnConfiguration() { return turn; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicOmnibusConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicOmnibusConfiguration.java new file mode 100644 index 000000000..65b9e76fa --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicOmnibusConfiguration.java @@ -0,0 +1,13 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.configuration.dynamic; + +import jakarta.validation.constraints.DecimalMax; +import jakarta.validation.constraints.DecimalMin; +import java.math.BigDecimal; + +/// @param rejectConnectionRatio The proportion of connection attempts that should be immediately closed with a GOAWAY +public record DynamicOmnibusConfiguration(@DecimalMin("0.0") @DecimalMax("1.0") BigDecimal rejectConnectionRatio) { +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2Server.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2Server.java index 0d5ed686f..3fa3f7816 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2Server.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2Server.java @@ -8,10 +8,9 @@ import com.google.common.annotations.VisibleForTesting; import io.dropwizard.lifecycle.Managed; import io.micrometer.core.instrument.Metrics; import io.netty.bootstrap.ServerBootstrap; -import io.netty.buffer.ByteBufAllocator; -import io.netty.buffer.ByteBufAllocatorMetricProvider; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; @@ -34,15 +33,19 @@ import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.Mapping; import java.io.IOException; +import java.math.BigDecimal; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketException; import java.time.Duration; import java.util.List; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicOmnibusConfiguration; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; /// An HTTP/2 server that proxies H2 streams to configurable backends via path-based routing @@ -55,10 +58,12 @@ public class OmnibusH2Server implements Managed { new OmnibusExceptionHandler("omnibus-handshake", List.of(SocketException.class, DecoderException.class, IOException.class)); private static final OmnibusExceptionHandler SESSION_EXCEPTION_HANDLER = new OmnibusExceptionHandler("omnibus-session", List.of(Http2Exception.class)); + private static final OmnibusLoadShedHandler LOAD_SHED_HANDLER = new OmnibusLoadShedHandler(); private static final String IDLE_DISCONNECT_COUNTER_NAME = MetricsUtil.name(OmnibusH2Server.class, "idleDisconnect"); private final @Nullable Mapping sslContextBySni; private final OmnibusRouter router; + private final Supplier configurationSupplier; private final Duration idleTimeout; private final DefaultEventLoopGroup localEventLoopGroup; private final NioEventLoopGroup nioEventLoopGroup; @@ -68,20 +73,24 @@ public class OmnibusH2Server implements Managed { /// Create an omnibus server /// - /// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for - /// that SNI. If null, the server will not include TLS (h2c with prior-knowledge) - /// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines - /// @param localEventLoopGroup Event loop to use for all local channel pipelines - /// @param bindAddress The address the server should listen on - /// @param router How the server should select backends based on request paths + /// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for + /// that SNI. If null, the server will not include TLS (h2c with prior-knowledge) + /// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines + /// @param localEventLoopGroup Event loop to use for all local channel pipelines + /// @param bindAddress The address the server should listen on + /// @param router How the server should select backends based on request paths + /// @param configurationSupplier Dynamic configuration supplier + /// @param idleTimeout How long to wait before terminating idle TCP connections public OmnibusH2Server( final @Nullable Mapping sslContextBySni, final NioEventLoopGroup nioEventLoopGroup, final DefaultEventLoopGroup localEventLoopGroup, final SocketAddress bindAddress, final OmnibusRouter router, + final Supplier configurationSupplier, final Duration idleTimeout) { this.sslContextBySni = sslContextBySni; + this.configurationSupplier = configurationSupplier; this.nioEventLoopGroup = nioEventLoopGroup; this.localEventLoopGroup = localEventLoopGroup; this.bindAddress = bindAddress; @@ -114,7 +123,15 @@ public class OmnibusH2Server implements Managed { ch.pipeline().addLast(new ProxyProtocolHandler()); ch.pipeline().addLast(new ProxyMessageAttributeSetterHandler()); if (sslContextBySni == null) { - configureH2Pipeline(ch.pipeline()); + // Defer setting up the H2 pipeline until the channel is active, so we know we can immediately write + // to it if we need to. + ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(final ChannelHandlerContext ctx) { + configureH2Pipeline(ctx.pipeline()); + ctx.pipeline().remove(this); + } + }); } else { ch.pipeline().addLast(new SniHandler(sslContextBySni)); ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { @@ -156,6 +173,11 @@ public class OmnibusH2Server implements Managed { // Advertise support for RFC-8441 extended connect final Http2Settings settings = Http2Settings.defaultSettings().connectProtocolEnabled(true); pipeline.addLast(Http2FrameCodecBuilder.forServer().initialSettings(settings).build()); + if (shouldRejectConnection()) { + pipeline.addLast(LOAD_SHED_HANDLER); + return; + } + pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer() { @Override protected void initChannel(final Http2StreamChannel ch) { @@ -164,4 +186,11 @@ public class OmnibusH2Server implements Managed { })); pipeline.addLast(SESSION_EXCEPTION_HANDLER); } + + private boolean shouldRejectConnection() { + final DynamicOmnibusConfiguration configuration = configurationSupplier.get(); + final BigDecimal rejectionRatio = configuration.rejectConnectionRatio(); + return rejectionRatio.compareTo(BigDecimal.ZERO) > 0 && + ThreadLocalRandom.current().nextDouble() < rejectionRatio.doubleValue(); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusLoadShedHandler.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusLoadShedHandler.java new file mode 100644 index 000000000..aa3769e8e --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusLoadShedHandler.java @@ -0,0 +1,41 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.grpc.net; + +import com.google.common.annotations.VisibleForTesting; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Metrics; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame; +import io.netty.util.ReferenceCountUtil; +import org.whispersystems.textsecuregcm.metrics.MetricsUtil; + +@ChannelHandler.Sharable +public class OmnibusLoadShedHandler extends ChannelInboundHandlerAdapter { + // Error code to put in GOAWAY frames that indicate load-shedding. 0x40 + // is an arbitrary non-reserved code per https://datatracker.ietf.org/doc/html/rfc7540#section-7 + @VisibleForTesting + static final int LOAD_SHED_ERROR_CODE = 0x40; + + private static final Counter LOAD_SHED_COUNTER = + Metrics.counter(MetricsUtil.name(OmnibusLoadShedHandler.class, "loadShed")); + + @Override + public void handlerAdded(final ChannelHandlerContext ctx) { + LOAD_SHED_COUNTER.increment(); + final DefaultHttp2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(LOAD_SHED_ERROR_CODE); + ctx.writeAndFlush(goAwayFrame).addListener(ChannelFutureListener.CLOSE); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + // Drop any attempts to open streams + ReferenceCountUtil.release(msg); + } + +} diff --git a/service/src/main/proto/org/signal/chat/README.md b/service/src/main/proto/org/signal/chat/README.md index c2340c88e..441c31e51 100644 --- a/service/src/main/proto/org/signal/chat/README.md +++ b/service/src/main/proto/org/signal/chat/README.md @@ -49,3 +49,8 @@ The chat server may return the following errors from any RPC When logging error responses, clients may always log the status code, domain, and reason. For errors with domain `grpc.chat.signal.org` and reason `CONSTRAINT_VIOLATED`, clients should check the `details` field for a `BadRequest` proto. If present, they should log the `field` of each violation in `field_violations`. + +### GOAWAY +In a partial or total server outage, the server may start rejecting new connection requests or terminating existing connections with an HTTP/2 GOAWAY frame with code 0x40. + +If clients receive a 0x40 GOAWAY they should retry connections with an aggressive exponential backoff. diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java index 885d65592..f5960cd45 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java @@ -36,6 +36,7 @@ import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; import io.netty.handler.codec.http2.Http2DataFrame; import io.netty.handler.codec.http2.Http2Error; import io.netty.handler.codec.http2.Http2FrameCodecBuilder; +import io.netty.handler.codec.http2.Http2GoAwayFrame; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2HeadersFrame; import io.netty.handler.codec.http2.Http2MultiplexHandler; @@ -51,6 +52,7 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.util.ReferenceCountUtil; import io.netty.util.test.LeakPresenceExtension; import java.io.InputStream; +import java.math.BigDecimal; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -69,10 +71,12 @@ import javax.annotation.Nullable; import javax.net.ssl.SSLException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.junitpioneer.jupiter.cartesian.CartesianTest; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicOmnibusConfiguration; @ExtendWith(LeakPresenceExtension.class) class OmnibusH2ServerTest { @@ -88,11 +92,13 @@ class OmnibusH2ServerTest { private List backendChannelsToShutDown; private List omnibusH2ServersToShutDown; + private AtomicReference dynamicConfiguration; @BeforeEach void setUp() { backendChannelsToShutDown = new ArrayList<>(); omnibusH2ServersToShutDown = new ArrayList<>(); + dynamicConfiguration = new AtomicReference<>(new DynamicOmnibusConfiguration(BigDecimal.ZERO)); } @AfterEach @@ -389,6 +395,41 @@ class OmnibusH2ServerTest { timeoutServer.stop(); } + @Test + void loadShed() throws Exception { + dynamicConfiguration.set(new DynamicOmnibusConfiguration(BigDecimal.ONE)); + final OmnibusH2Server server = startOmnibusServer( + Map.of(PREFIX, startBackendServer(true, PREFIX_BACKEND_IDENTITY)), + startBackendServer(true, DEFAULT_BACKEND_IDENTITY)); + + final CompletableFuture goAwayFuture = new CompletableFuture<>(); + final Bootstrap clientBootstrap = new Bootstrap() + .group(nioEventLoopGroup) + .channel(NioSocketChannel.class) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(final SocketChannel ch) { + final SslContext clientSsl = sslContext(); + ch.pipeline().addLast(clientSsl.newHandler(ch.alloc(), server.getLocalAddress().getHostName(), + server.getLocalAddress().getPort())); + ch.pipeline() + .addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build()); + ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + if (msg instanceof Http2GoAwayFrame g) { + goAwayFuture.complete(g); + } + ctx.fireChannelRead(msg); + } + }); + } + }); + clientBootstrap.connect(server.getLocalAddress()).syncUninterruptibly().channel(); + final Http2GoAwayFrame frame = goAwayFuture.get(1, TimeUnit.SECONDS); + assertEquals(OmnibusLoadShedHandler.LOAD_SHED_ERROR_CODE, frame.errorCode()); + } + /// Start an OmnibusH2Server. The returned server and provided backends will be torn down in [#tearDown()] /// /// @param routes A map of prefixes and the corresponding backend server channels the omnibus will target @@ -409,6 +450,7 @@ class OmnibusH2ServerTest { new OmnibusRouter( routes.entrySet().stream().map(entry -> new OmnibusRouter.OmnibusRoute(entry.getKey(), entry.getValue().localAddress())).toList(), defaultBackend.localAddress()), + dynamicConfiguration::get, timeout); server.start(); omnibusH2ServersToShutDown.add(server); @@ -459,19 +501,7 @@ class OmnibusH2ServerTest { /// Makes an H2 connection to the omnibus at [this#server] on which new H2 streams can be opened private Channel connectToOmnibus(final OmnibusH2Server server, @Nullable final HAProxyMessage proxyHeader) { - final SslContext clientSsl; - try { - clientSsl = SslContextBuilder.forClient() - .trustManager(InsecureTrustManagerFactory.INSTANCE) - .applicationProtocolConfig(new ApplicationProtocolConfig( - ApplicationProtocolConfig.Protocol.ALPN, - ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, - ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, - ApplicationProtocolNames.HTTP_2)) - .build(); - } catch (SSLException e) { - throw new RuntimeException(e); - } + final SslContext clientSsl = sslContext(); final Bootstrap clientBootstrap = new Bootstrap() .group(nioEventLoopGroup) @@ -504,6 +534,21 @@ class OmnibusH2ServerTest { return connectToOmnibus(server, null); } + private static SslContext sslContext() { + try { + return SslContextBuilder.forClient() + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig( + ApplicationProtocolConfig.Protocol.ALPN, + ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, + ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, + ApplicationProtocolNames.HTTP_2)) + .build(); + } catch (SSLException e) { + throw new RuntimeException(e); + } + } + private String sendRequestThroughOmnibus(final Channel h2Connection, final String path) { final CompletableFuture responseFuture = new CompletableFuture<>(); final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);