From 9b532861ad66ecea6d6c134e34aea7ed79f44807 Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Fri, 27 Nov 2026 12:21:58 -0500 Subject: [PATCH] Add explicit EPP/TLS/quota FSMs and P0 hotfixes Implicit connection flags, split certificate caches, and misclassified HTTP status codes across EPP transport, proxy quota enforcement, and scheduled background tasks create security bypasses, rotation outages, and silent operational failures. Replacing those ad-hoc booleans and split caches with explicit state machines and atomic credentials keeps connection lifecycles unambiguous, ensures TLS rotations never pair mismatched keys and certificates, enforces RFC 5734 session closure and PROXY v1 framing caps, and prevents Cloud Tasks from silently dropping domain purges or RDE escrow uploads and staging failures. Changes: - Atomic TLS credentials and SslContext caching (CertificateSupplierModule, SslServerInitializer, core/proxy EppProtocolModule): bundle private key and ordered certificate chain in one TlsCredentials record cached under a single memoizeWithExpiration TTL, fail fast on unsupported Mode.P12_FILE, cache/rebuild SslContext atomically only on credential rotation instead of per TCP connection, and re-read credentials inside the build lock so stale reads cannot overwrite rotated contexts. - Disable server-side TLS session resumption on cached mTLS SslContexts (SslServerInitializer, jetty/kubernetes/*, proxy/kubernetes/*, jetty/start.sh, proxy/Dockerfile, networking/build.gradle): BoringSSL omits intermediate certificates on resumed server sessions, which would break post-handshake client certificate chain validation on 3+ tier chains, and both JDK and Netty OpenSSL emit stateless TLS 1.2/1.3 session tickets unless jdk.tls.server.enableSessionTicketExtension=false is set. Because EPP uses persistent TCP connections and previously built a fresh SslContext per connection, TLS session resumption was never used in production. Explicitly disable the OpenSSL session cache (setSessionCacheEnabled(false) / SSL_SESS_CACHE_OFF), unconditionally invalidate server-side sessions on handshake completion (sslSession.invalidate()), log a startup warning if the ticket flag is absent on an mTLS server, and set -Djdk.tls.server.enableSessionTicketExtension=false across all Jetty and proxy Kubernetes containers, Dockerfiles/start.sh, and networking tests so every mTLS connection performs a full handshake and preserves full client certificate chains on both TLS 1.2 and TLS 1.3. - Explicit integrated EPP connection FSM (core EppServiceHandler): replace ad-hoc boolean flags with a flat ConnectionState enum (AWAITING_TLS, READY_UNAUTHENTICATED, AUTHENTICATED, CLOSING) and a single idempotent releaseConnectionLimits() helper, execute already-completed cert promises inline in channelActive (and re-check after addListener() to close the cross-executor TOCTOU window), reject pre-TLS frames and non-200 servlet responses fail-closed, guard buildServletRequest() inside try/catch so OIDC token errors fail closed and release limits, defer CLOSING until close-on-flush succeeds so write failures still release limits and close, remove the sticky regex latch on failed logins, preserve client certificate chain validation and hostname header forwarding, and drop pipelined frames in CLOSING. - Proxy quota lease FSM and PROXY v1 header cap (QuotaHandler, ProxyProtocolHandler): add LeaseState (UNCHECKED, LEASED, REJECTED, RELEASED) so pipelined frames after quota rejection are dropped and released instead of bypassing checks, and enforce the 107-byte HAProxy PROXY protocol v1 header cap to prevent unbounded buffer growth. - RFC 5734 section 2 close on 2501 (EppRequestHandler): set Epp-Session: close on AUTHENTICATION_ERROR_CLOSING_CONNECTION (2501) as well as SUCCESS_AND_CLOSE (1500). - Rolled-in P0 operational hotfixes (b/591075298, b/591075515): - ResaveEntityAction: pass tm().getTxTime() (filtering remaining times) instead of original requestedTime so Day-35 final purges (30d RGP + 5d pending delete > 30d MAX_ASYNC_ETA) are not silently dropped, and enqueue the follow-up Cloud Task outside the SERIALIZABLE transaction. - RdeUploadAction: throw ServiceUnavailableException (503) instead of NoContentException (204) on SFTP cooldown so Cloud Tasks retries. - RdeStagingAction: preserve HTTP 500 when any Dataflow launch throws IOException instead of overwriting the status with 200. Operational justification and blast radius: Eliminates TLS rotation key/cert mismatch outages, per-connection native OpenSSL context churn, resumed-session client chain truncation, pre-TLS and post-rejection quota bypasses, unbounded PROXY header memory allocation, and silent RDE/domain-purge drops across the frontend EPP/proxy tier and backend Cloud Tasks actions, keeping JDK_JAVA_OPTIONS in parity across all 15 Jetty and proxy containers with zero database schema, Flyway, or Valkey Protostuff changes. BUG= http://b/591076386 --- .../registry/batch/ResaveEntityAction.java | 39 +- .../registry/eppserver/EppProtocolModule.java | 10 +- .../eppserver/handler/EppServiceHandler.java | 275 ++++--- .../registry/flows/EppRequestHandler.java | 20 +- .../google/registry/rde/RdeStagingAction.java | 127 ++-- .../google/registry/rde/RdeUploadAction.java | 3 +- .../batch/ResaveEntityActionTest.java | 116 ++- .../handler/EppServiceHandlerTest.java | 708 +++++++++++++++++- .../registry/flows/EppRequestHandlerTest.java | 134 ++++ .../registry/rde/RdeStagingActionTest.java | 36 + .../registry/rde/RdeUploadActionTest.java | 8 +- jetty/kubernetes/nomulus-backend.yaml | 10 +- jetty/kubernetes/nomulus-console.yaml | 10 +- jetty/kubernetes/nomulus-epp-server.yaml | 10 +- jetty/kubernetes/nomulus-frontend.yaml | 20 +- jetty/kubernetes/nomulus-pubapi.yaml | 10 +- jetty/start.sh | 3 + networking/build.gradle | 3 + .../handler/SslServerInitializer.java | 105 ++- .../module/CertificateSupplierModule.java | 130 ++-- .../handler/SslInitializerTestUtils.java | 4 +- .../handler/SslServerInitializerTest.java | 483 +++++++++++- .../module/CertificateSupplierModuleTest.java | 151 +++- proxy/Dockerfile | 5 +- proxy/kubernetes/proxy-deployment-alpha.yaml | 10 +- .../proxy-deployment-crash-canary.yaml | 10 +- proxy/kubernetes/proxy-deployment-crash.yaml | 10 +- .../proxy-deployment-production-canary.yaml | 10 +- .../proxy-deployment-production.yaml | 10 +- .../proxy-deployment-qa-canary.yaml | 10 +- proxy/kubernetes/proxy-deployment-qa.yaml | 10 +- .../proxy-deployment-sandbox-canary.yaml | 10 +- .../kubernetes/proxy-deployment-sandbox.yaml | 10 +- .../registry/proxy/EppProtocolModule.java | 10 +- .../proxy/handler/ProxyProtocolHandler.java | 73 +- .../registry/proxy/handler/QuotaHandler.java | 58 +- .../proxy/handler/EppQuotaHandlerTest.java | 55 ++ .../handler/ProxyProtocolHandlerTest.java | 69 ++ 38 files changed, 2297 insertions(+), 478 deletions(-) create mode 100644 core/src/test/java/google/registry/flows/EppRequestHandlerTest.java diff --git a/core/src/main/java/google/registry/batch/ResaveEntityAction.java b/core/src/main/java/google/registry/batch/ResaveEntityAction.java index 0e4ea56ca4d..ea51a8dcf58 100644 --- a/core/src/main/java/google/registry/batch/ResaveEntityAction.java +++ b/core/src/main/java/google/registry/batch/ResaveEntityAction.java @@ -73,22 +73,29 @@ public class ResaveEntityAction implements Runnable { public void run() { logger.atInfo().log( "Re-saving entity %s which was enqueued at %s.", resourceKey, requestedTime); - tm().transact( - () -> { - Optional entity = - tm().loadByKeyIfPresent(VKey.createEppVKeyFromString(resourceKey)); - if (entity.isEmpty()) { - logger.atSevere().log( - "Could not re-save entity %s because it does not exist; failing permanently.", - resourceKey); - return; - } - tm().put(entity.get().cloneProjectedAtTime(tm().getTxTime())); - if (!resaveTimes.isEmpty()) { - asyncTaskEnqueuer.enqueueAsyncResave( - VKey.createEppVKeyFromString(resourceKey), requestedTime, resaveTimes); - } - }); + VKey entityKey = VKey.createEppVKeyFromString(resourceKey); + Optional resavedAt = + tm().transact( + () -> { + Optional entity = tm().loadByKeyIfPresent(entityKey); + if (entity.isEmpty()) { + logger.atSevere().log( + "Could not re-save entity %s because it does not exist; failing" + + " permanently.", + resourceKey); + return Optional.empty(); + } + Instant now = tm().getTxTime(); + tm().put(entity.get().cloneProjectedAtTime(now)); + return Optional.of(now); + }); + resavedAt.ifPresent( + now -> { + ImmutableSortedSet remainingResaveTimes = resaveTimes.tailSet(now, false); + if (!remainingResaveTimes.isEmpty()) { + asyncTaskEnqueuer.enqueueAsyncResave(entityKey, now, remainingResaveTimes); + } + }); response.setPayload("Entity re-saved."); } } diff --git a/core/src/main/java/google/registry/eppserver/EppProtocolModule.java b/core/src/main/java/google/registry/eppserver/EppProtocolModule.java index becf052877d..03eecd8dac9 100644 --- a/core/src/main/java/google/registry/eppserver/EppProtocolModule.java +++ b/core/src/main/java/google/registry/eppserver/EppProtocolModule.java @@ -26,6 +26,7 @@ import google.registry.eppserver.handler.EppServiceHandler; import google.registry.eppserver.quota.EppServerQuotaManager; import google.registry.networking.handler.SslServerInitializer; +import google.registry.networking.module.CertificateSupplierModule.TlsCredentials; import google.registry.quota.NoopQuotaManager; import google.registry.quota.QuotaManager; import google.registry.quota.ValkeyQuotaManager; @@ -40,8 +41,6 @@ import jakarta.inject.Qualifier; import jakarta.inject.Singleton; import java.io.IOException; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; import java.util.Optional; import java.util.function.Supplier; import redis.clients.jedis.UnifiedJedis; @@ -130,11 +129,8 @@ static byte[] provideHelloBytes() { @Provides @EppProtocol static SslServerInitializer provideSslServerInitializer( - SslProvider sslProvider, - Supplier privateKeySupplier, - Supplier> certificatesSupplier) { - return new SslServerInitializer<>( - true, false, sslProvider, privateKeySupplier, certificatesSupplier); + SslProvider sslProvider, Supplier tlsCredentialsSupplier) { + return new SslServerInitializer<>(true, false, sslProvider, tlsCredentialsSupplier); } @Provides diff --git a/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java b/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java index 61440773f23..b3ddd28e918 100644 --- a/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java +++ b/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java @@ -15,6 +15,7 @@ package google.registry.eppserver.handler; import static com.google.common.base.MoreObjects.firstNonNull; +import static com.google.common.base.Preconditions.checkNotNull; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_HOSTNAMES_KEY; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_PROMISE_KEY; @@ -43,11 +44,12 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.AttributeKey; -import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.ScheduledFuture; import jakarta.inject.Inject; import jakarta.inject.Named; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.cert.X509Certificate; @@ -55,29 +57,38 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import javax.annotation.Nullable; /** * Unified processor for EPP protocol traffic. * - *

Consolidates throttling, session management, and in-process execution. Extracts registrar ID - * (clID) directly from EPP login XML for accurate throttling. + *

Consolidates connection lifecycle state, throttling, session management, and in-process + * execution. Connection state transitions strictly through {@link ConnectionState} on the handler's + * single-threaded {@link ChannelHandlerContext#executor()}. */ public class EppServiceHandler extends SimpleChannelInboundHandler { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); - // Fast regex to extract clID from EPP login command without full XML parsing. - private static final Pattern CLID_PATTERN = - Pattern.compile("([^<]+)", Pattern.CASE_INSENSITIVE); - public static final AttributeKey CLIENT_CERTIFICATE_HASH_KEY = AttributeKey.valueOf("CLIENT_CERTIFICATE_HASH_KEY"); public static final AttributeKey REMOTE_ADDRESS_KEY = AttributeKey.valueOf("REMOTE_ADDRESS_KEY"); + /** Explicit connection lifecycle state for an integrated EPP TCP connection. */ + @VisibleForTesting + enum ConnectionState { + /** TLS handshake has not completed yet; no EPP frames may be processed. */ + AWAITING_TLS, + /** TLS handshake succeeded and IP connection quota is held; waiting for EPP login. */ + READY_UNAUTHENTICATED, + /** Registrar login succeeded and both IP and registrar connection quotas are held. */ + AUTHENTICATED, + /** Closure has been initiated or the channel became inactive; frames are dropped. */ + CLOSING + } + private final byte[] helloBytes; private final FrontendMetrics metrics; private final LocalConnectionLimiter localConnectionLimiter; @@ -86,17 +97,16 @@ public class EppServiceHandler extends SimpleChannelInboundHandler { private final String projectId; private final int preLoginReadTimeoutSeconds; - private String sslClientCertificateHash; + private ConnectionState state = ConnectionState.AWAITING_TLS; + // Non-null iff IP connection quota is currently held. + @Nullable private String clientAddress; + @Nullable private String sslClientCertificateHash; private boolean sslClientCertificateChainValidated; private Optional sslClientCertificateHostnamesHeader = Optional.empty(); - private String clientAddress; - private String registrarId; // The clID extracted from login - private String authenticatedRegistrarId; // The verified registrar ID after successful login - private String sessionCookie; - - private boolean ipAcquired = false; - private boolean registrarAcquired = false; - private ScheduledFuture preLoginTimeoutTask; + // Non-null iff registrar connection quota is currently held. + @Nullable private String authenticatedRegistrarId; + @Nullable private String sessionCookie; + @Nullable private ScheduledFuture preLoginTimeoutTask; @VisibleForTesting RequestHandler requestHandler = RegistryServlet.component.requestHandler(); @@ -118,53 +128,79 @@ public EppServiceHandler( this.preLoginReadTimeoutSeconds = preLoginReadTimeoutSeconds; } + @VisibleForTesting + ConnectionState getState() { + return state; + } + @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Promise certPromise = ctx.channel().attr(CLIENT_CERTIFICATE_PROMISE_KEY).get(); - if (certPromise != null) { + if (certPromise == null) { + logger.atSevere().log("Missing client certificate promise, closing connection"); + transitionToClosing(ctx); + return; + } + if (certPromise.isDone()) { + // Run synchronously inside channelActive so a completed TLS handshake cannot be re-queued + // on businessGroup behind an already-pipelined channelRead0 event. + handleCertPromiseCompletion(ctx, certPromise); + } else { certPromise.addListener( (Promise promise) -> { - if (promise.isSuccess()) { - ctx.executor().execute(() -> onSslHandshakeComplete(ctx, promise.getNow())); + if (ctx.executor().inEventLoop()) { + handleCertPromiseCompletion(ctx, promise); } else { - logger.atWarning().withCause(promise.cause()).log("SSL handshake failed"); - closeConnection(ctx); + ctx.executor().execute(() -> handleCertPromiseCompletion(ctx, promise)); } }); + // Re-check after listener registration to close the cross-executor TOCTOU window: if + // certPromise completed on the I/O eventLoop between isDone() and addListener(), run + // synchronously now before any queued channelRead0 (the bounced listener becomes a no-op + // once state leaves AWAITING_TLS). + if (certPromise.isDone()) { + handleCertPromiseCompletion(ctx, certPromise); + } } super.channelActive(ctx); } - private void onSslHandshakeComplete(ChannelHandlerContext ctx, X509Certificate cert) { - if (!ctx.channel().isActive()) { + private void handleCertPromiseCompletion( + ChannelHandlerContext ctx, Promise promise) { + if (state != ConnectionState.AWAITING_TLS) { return; } - clientAddress = ctx.channel().attr(REMOTE_ADDRESS_KEY).get(); - if (clientAddress == null) { - SocketAddress remoteAddress = ctx.channel().remoteAddress(); - if (remoteAddress instanceof InetSocketAddress inetSocketAddress) { - clientAddress = inetSocketAddress.getAddress().getHostAddress(); - } + if (!promise.isSuccess()) { + logger.atWarning().withCause(promise.cause()).log("SSL handshake failed"); + transitionToClosing(ctx); + return; + } + + if (!ctx.channel().isActive()) { + state = ConnectionState.CLOSING; + return; } - if (clientAddress == null || clientAddress.isEmpty()) { + String resolvedAddress = resolveClientAddress(ctx); + if (resolvedAddress == null || resolvedAddress.isEmpty()) { logger.atSevere().log("Failed to resolve client IP address, closing connection"); - closeConnection(ctx); + transitionToClosing(ctx); return; } - sslClientCertificateHash = getCertificateHash(cert); - ctx.channel().attr(CLIENT_CERTIFICATE_HASH_KEY).set(sslClientCertificateHash); + String certHash = getCertificateHash(promise.getNow()); + ctx.channel().attr(CLIENT_CERTIFICATE_HASH_KEY).set(certHash); // 1. Connection throttling (IP only pre-login) - if (!localConnectionLimiter.acquireIp(clientAddress)) { - metrics.registerQuotaRejection("epp_connection_ip", clientAddress); - closeConnection(ctx); + if (!localConnectionLimiter.acquireIp(resolvedAddress)) { + metrics.registerQuotaRejection("epp_connection_ip", resolvedAddress); + transitionToClosing(ctx); return; } - ipAcquired = true; + clientAddress = resolvedAddress; + sslClientCertificateHash = certHash; sslClientCertificateChainValidated = firstNonNull(ctx.channel().attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get(), false); sslClientCertificateHostnamesHeader = @@ -173,22 +209,10 @@ private void onSslHandshakeComplete(ChannelHandlerContext ctx, X509Certificate c ctx.channel().attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get(), sslClientCertificateHash) : Optional.empty(); - - // Schedule login timeout preLoginTimeoutTask = ctx.executor() - .schedule( - () -> { - if (!registrarAcquired) { - logger.atWarning().log( - "EPP login timeout expired for channel %s, closing connection", - ctx.channel()); - metrics.registerQuotaRejection("epp_login_timeout", clientAddress); - closeConnection(ctx); - } - }, - preLoginReadTimeoutSeconds, - TimeUnit.SECONDS); + .schedule(() -> onPreLoginTimeout(ctx), preLoginReadTimeoutSeconds, TimeUnit.SECONDS); + state = ConnectionState.READY_UNAUTHENTICATED; metrics.registerActiveConnection("epp", sslClientCertificateHash, ctx.channel()); @@ -196,21 +220,55 @@ private void onSslHandshakeComplete(ChannelHandlerContext ctx, X509Certificate c handleEppFrame(ctx, Unpooled.wrappedBuffer(helloBytes)); } + @Nullable + private static String resolveClientAddress(ChannelHandlerContext ctx) { + String clientAddress = ctx.channel().attr(REMOTE_ADDRESS_KEY).get(); + if (clientAddress == null) { + SocketAddress remoteAddress = ctx.channel().remoteAddress(); + if (remoteAddress instanceof InetSocketAddress inetSocketAddress) { + clientAddress = inetSocketAddress.getAddress().getHostAddress(); + } + } + return clientAddress; + } + + private void onPreLoginTimeout(ChannelHandlerContext ctx) { + if (state != ConnectionState.READY_UNAUTHENTICATED) { + return; + } + logger.atWarning().log( + "EPP login timeout expired for channel %s, closing connection", ctx.channel()); + metrics.registerQuotaRejection("epp_login_timeout", checkNotNull(clientAddress)); + transitionToClosing(ctx); + } + @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf frame) { - handleEppFrame(ctx, frame); + switch (state) { + case AWAITING_TLS -> { + logger.atWarning().log( + "Received EPP frame before TLS handshake completed on channel %s, closing connection", + ctx.channel()); + transitionToClosing(ctx); + } + case READY_UNAUTHENTICATED -> handleEppFrame(ctx, frame); + case AUTHENTICATED -> handleEppFrame(ctx, frame); + case CLOSING -> + logger.atFine().log("Ignoring EPP frame on closing channel %s", ctx.channel()); + } } private void handleEppFrame(ChannelHandlerContext ctx, ByteBuf frame) { String xml = frame.toString(UTF_8); - extractRegistrarId(xml); - - if (!acquireCommandQuota(ctx)) { + String throttleId = + (state == ConnectionState.AUTHENTICATED) + ? checkNotNull(authenticatedRegistrarId) + : checkNotNull(sslClientCertificateHash); + if (!acquireCommandQuota(ctx, throttleId)) { return; } - FakeHttpServletRequest req = buildServletRequest(xml); FakeHttpServletResponse rsp = new FakeHttpServletResponse(); String traceId = String.format( @@ -218,36 +276,23 @@ private void handleEppFrame(ChannelHandlerContext ctx, ByteBuf frame) { setCurrentTraceId(traceId); setCurrentRequest("POST", "/_dr/epp", "Netty-EPP", "EPP/1.0"); try { + FakeHttpServletRequest req = buildServletRequest(xml); requestHandler.handleRequest(req, rsp); processServletResponse(ctx, rsp); - } catch (Exception e) { + } catch (IOException | RuntimeException e) { logger.atSevere().withCause(e).log("Internal EPP processing error"); - closeConnection(ctx); + transitionToClosing(ctx); } finally { setCurrentTraceId(null); unsetCurrentRequest(); } } - private void extractRegistrarId(String xml) { - if (registrarId == null) { - Matcher matcher = CLID_PATTERN.matcher(xml); - if (matcher.find()) { - registrarId = matcher.group(1).trim(); - logger.atInfo().log("Identified registrar: %s", registrarId); - } - } - } - - private boolean acquireCommandQuota(ChannelHandlerContext ctx) { - String throttleId = - (authenticatedRegistrarId != null) ? authenticatedRegistrarId : sslClientCertificateHash; - if (throttleId != null) { - if (!commandQuotaManager.acquireQuota(throttleId)) { - metrics.registerQuotaRejection("epp_command", throttleId); - closeConnection(ctx); - return false; - } + private boolean acquireCommandQuota(ChannelHandlerContext ctx, String throttleId) { + if (!commandQuotaManager.acquireQuota(throttleId)) { + metrics.registerQuotaRejection("epp_command", throttleId); + transitionToClosing(ctx); + return false; } return true; } @@ -256,15 +301,15 @@ private FakeHttpServletRequest buildServletRequest(String xml) { FakeHttpServletRequest req = new FakeHttpServletRequest(); req.setRequestUri("/_dr/epp"); req.setBody(xml.getBytes(UTF_8)); - req.setHeader(ProxyHttpHeaders.CERTIFICATE_HASH, sslClientCertificateHash); + req.setHeader(ProxyHttpHeaders.CERTIFICATE_HASH, checkNotNull(sslClientCertificateHash)); req.setHeader( ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, Boolean.toString(sslClientCertificateChainValidated)); sslClientCertificateHostnamesHeader.ifPresent( header -> req.setHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, header)); - req.setHeader(ProxyHttpHeaders.IP_ADDRESS, clientAddress); - if (registrarId != null) { - req.setHeader(ProxyHttpHeaders.REGISTRAR_ID, registrarId); + req.setHeader(ProxyHttpHeaders.IP_ADDRESS, checkNotNull(clientAddress)); + if (state == ConnectionState.AUTHENTICATED) { + req.setHeader(ProxyHttpHeaders.REGISTRAR_ID, checkNotNull(authenticatedRegistrarId)); } if (sessionCookie != null) { req.setHeader("Cookie", sessionCookie); @@ -273,61 +318,81 @@ private FakeHttpServletRequest buildServletRequest(String xml) { return req; } + @SuppressWarnings("FutureReturnValueIgnored") private void processServletResponse(ChannelHandlerContext ctx, FakeHttpServletResponse rsp) { + if (rsp.getStatus() != HttpServletResponse.SC_OK) { + logger.atWarning().log( + "Servlet returned non-200 HTTP status %d on channel %s, closing connection", + rsp.getStatus(), ctx.channel()); + transitionToClosing(ctx); + return; + } + String setCookie = rsp.getHeader("Set-Cookie"); if (setCookie != null) { sessionCookie = setCookie; } + boolean shouldClose = "close".equals(rsp.getHeader(ProxyHttpHeaders.EPP_SESSION)); String authRegistrarId = rsp.getHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR); - if (authRegistrarId != null && !registrarAcquired) { + if (!shouldClose && state == ConnectionState.READY_UNAUTHENTICATED && authRegistrarId != null) { logger.atInfo().log("Registrar %s successfully authenticated", authRegistrarId); if (!localConnectionLimiter.acquireRegistrar(authRegistrarId)) { logger.atWarning().log( "Registrar %s exceeded concurrent connection limit, closing connection", authRegistrarId); metrics.registerQuotaRejection("epp_connection_registrar", authRegistrarId); - closeConnection(ctx); + transitionToClosing(ctx); return; } - registrarAcquired = true; authenticatedRegistrarId = authRegistrarId; - registrarId = authRegistrarId; - - // Cancel pre-login timeout task - if (preLoginTimeoutTask != null) { - preLoginTimeoutTask.cancel(false); - preLoginTimeoutTask = null; - } + cancelPreLoginTimeout(); + state = ConnectionState.AUTHENTICATED; } ByteBuf out = Unpooled.wrappedBuffer(rsp.getPayload()); - if ("close".equals(rsp.getHeader(ProxyHttpHeaders.EPP_SESSION))) { - @SuppressWarnings("unused") - Future unusedFuture = ctx.writeAndFlush(out).addListener(ChannelFutureListener.CLOSE); + if (shouldClose) { + ctx.writeAndFlush(out).addListener(ChannelFutureListener.CLOSE); + state = ConnectionState.CLOSING; + cancelPreLoginTimeout(); } else { - @SuppressWarnings("unused") - Future unusedFuture = ctx.writeAndFlush(out); + ctx.writeAndFlush(out); } } - private void closeConnection(ChannelHandlerContext ctx) { - @SuppressWarnings("unused") - Future unusedFuture = ctx.close(); + @SuppressWarnings("FutureReturnValueIgnored") + private void transitionToClosing(ChannelHandlerContext ctx) { + if (state == ConnectionState.CLOSING) { + return; + } + state = ConnectionState.CLOSING; + releaseConnectionLimits(); + ctx.close(); } - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { + private void cancelPreLoginTimeout() { if (preLoginTimeoutTask != null) { preLoginTimeoutTask.cancel(false); preLoginTimeoutTask = null; } - if (registrarAcquired) { + } + + private void releaseConnectionLimits() { + cancelPreLoginTimeout(); + if (authenticatedRegistrarId != null) { localConnectionLimiter.releaseRegistrar(authenticatedRegistrarId); + authenticatedRegistrarId = null; } - if (ipAcquired) { + if (clientAddress != null) { localConnectionLimiter.releaseIp(clientAddress); + clientAddress = null; } + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + state = ConnectionState.CLOSING; + releaseConnectionLimits(); super.channelInactive(ctx); } } diff --git a/core/src/main/java/google/registry/flows/EppRequestHandler.java b/core/src/main/java/google/registry/flows/EppRequestHandler.java index 8e4b166c256..de5246fc627 100644 --- a/core/src/main/java/google/registry/flows/EppRequestHandler.java +++ b/core/src/main/java/google/registry/flows/EppRequestHandler.java @@ -15,6 +15,7 @@ package google.registry.flows; import static google.registry.flows.FlowUtils.marshalWithLenientRetry; +import static google.registry.model.eppoutput.Result.Code.AUTHENTICATION_ERROR_CLOSING_CONNECTION; import static google.registry.model.eppoutput.Result.Code.SUCCESS_AND_CLOSE; import static google.registry.xml.XmlTransformer.prettyPrint; import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; @@ -24,6 +25,7 @@ import com.google.common.flogger.FluentLogger; import com.google.common.net.MediaType; import google.registry.model.eppoutput.EppOutput; +import google.registry.model.eppoutput.Result; import google.registry.request.Response; import google.registry.util.ProxyHttpHeaders; import google.registry.util.StopwatchLogger; @@ -69,11 +71,10 @@ public void executeEpp( // a non-OK status (400) is if we fail to muster even an EPP error response message. In that // case it's better to close the connection than to return garbage. response.setStatus(SC_OK); - // Per RFC 5734, a server receiving a logout command must end the EPP session and close the - // TCP connection. Since the app itself only gets HttpServletRequest and is not aware of TCP - // sessions, it simply sets the HTTP response header to indicate the connection should be - // closed by the proxy. Whether the EPP proxy actually terminates the connection with the - // client is up to its implementation. + // Per RFC 5734 ยง2, a server ending an EPP session (1500 logout or 2501 authentication error + // closing connection) must close the TCP connection. Since the app itself only gets + // HttpServletRequest and is not aware of TCP sessions, it sets the HTTP response header to + // indicate the connection should be closed by the proxy or integrated EPP server. // See: https://tools.ietf.org/html/rfc5734#section-2 String authRegistrarId = null; try { @@ -84,9 +85,12 @@ public void executeEpp( if (authRegistrarId != null) { response.setHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, authRegistrarId); } - if (eppOutput.isResponse() - && eppOutput.getResponse().getResult().getCode() == SUCCESS_AND_CLOSE) { - response.setHeader(ProxyHttpHeaders.EPP_SESSION, "close"); + if (eppOutput.isResponse()) { + Result.Code resultCode = eppOutput.getResponse().getResult().getCode(); + if (resultCode == SUCCESS_AND_CLOSE + || resultCode == AUTHENTICATION_ERROR_CLOSING_CONNECTION) { + response.setHeader(ProxyHttpHeaders.EPP_SESSION, "close"); + } } } catch (Exception e) { logger.atWarning().withCause(e).log("handleEppCommand general exception."); diff --git a/core/src/main/java/google/registry/rde/RdeStagingAction.java b/core/src/main/java/google/registry/rde/RdeStagingAction.java index bb1e5c28562..feae8c6810b 100644 --- a/core/src/main/java/google/registry/rde/RdeStagingAction.java +++ b/core/src/main/java/google/registry/rde/RdeStagingAction.java @@ -63,6 +63,8 @@ import java.io.IOException; import java.time.Duration; import java.time.Instant; +import java.util.Collection; +import java.util.Map; import java.util.Optional; /** @@ -266,64 +268,75 @@ public void run() { } ValidationMode validationMode = lenient ? LENIENT : STRICT; ImmutableList.Builder jobNameBuilder = new ImmutableList.Builder<>(); - pendings.values().stream() - .collect(toImmutableSetMultimap(PendingDeposit::watermark, identity())) - .asMap() - .forEach( - (watermark, pendingDeposits) -> { - try { - LaunchFlexTemplateParameter parameter = - new LaunchFlexTemplateParameter() - .setJobName( - createJobName( - String.format( - "rde-%s", LOWERCASE_TIMESTAMP_FORMATTER.format(watermark)), - clock)) - .setContainerSpecGcsPath( - String.format("%s/%s_metadata.json", stagingBucketUrl, PIPELINE_NAME)) - .setParameters( - new ImmutableMap.Builder() - .put( - "pendings", - RdePipeline.encodePendingDeposits( - ImmutableSet.copyOf(pendingDeposits))) - .put("validationMode", validationMode.name()) - .put("rdeStagingBucket", rdeBucket) - .put( - "stagingKey", - BaseEncoding.base64Url().omitPadding().encode(stagingKeyBytes)) - .put("registryEnvironment", RegistryEnvironment.get().name()) - .put("workerMachineType", machineType) - .put("numWorkers", String.valueOf(numWorkers)) - // TODO (jianglai): Investigate turning off public IPs (for which - // there is a quota) in order to increase the total number of - // workers allowed (also under quota). - // See: - // https://cloud.google.com/dataflow/docs/guides/routes-firewall - .put("usePublicIps", "true") - .build()); - LaunchFlexTemplateResponse launchResponse = - dataflow - .projects() - .locations() - .flexTemplates() - .launch( - projectId, - jobRegion, - new LaunchFlexTemplateRequest().setLaunchParameter(parameter)) - .execute(); - logger.atInfo().log( - "Launched RDE staging Dataflow job: %s", launchResponse.getJob().getId()); - jobNameBuilder.add(launchResponse.getJob().getId()); - } catch (IOException e) { - logger.atWarning().withCause(e).log("Pipeline Launch failed"); - response.setStatus(SC_INTERNAL_SERVER_ERROR); - response.setPayload(String.format("Pipeline launch failed: %s", e.getMessage())); - } - }); + ImmutableList.Builder errorMessageBuilder = new ImmutableList.Builder<>(); + for (Map.Entry> entry : + pendings.values().stream() + .collect(toImmutableSetMultimap(PendingDeposit::watermark, identity())) + .asMap() + .entrySet()) { + Instant watermark = entry.getKey(); + Collection pendingDeposits = entry.getValue(); + try { + LaunchFlexTemplateParameter parameter = + new LaunchFlexTemplateParameter() + .setJobName( + createJobName( + String.format("rde-%s", LOWERCASE_TIMESTAMP_FORMATTER.format(watermark)), + clock)) + .setContainerSpecGcsPath( + String.format("%s/%s_metadata.json", stagingBucketUrl, PIPELINE_NAME)) + .setParameters( + new ImmutableMap.Builder() + .put( + "pendings", + RdePipeline.encodePendingDeposits(ImmutableSet.copyOf(pendingDeposits))) + .put("validationMode", validationMode.name()) + .put("rdeStagingBucket", rdeBucket) + .put( + "stagingKey", + BaseEncoding.base64Url().omitPadding().encode(stagingKeyBytes)) + .put("registryEnvironment", RegistryEnvironment.get().name()) + .put("workerMachineType", machineType) + .put("numWorkers", String.valueOf(numWorkers)) + // TODO (jianglai): Investigate turning off public IPs (for which + // there is a quota) in order to increase the total number of + // workers allowed (also under quota). + // See: + // https://cloud.google.com/dataflow/docs/guides/routes-firewall + .put("usePublicIps", "true") + .build()); + LaunchFlexTemplateResponse launchResponse = + dataflow + .projects() + .locations() + .flexTemplates() + .launch( + projectId, + jobRegion, + new LaunchFlexTemplateRequest().setLaunchParameter(parameter)) + .execute(); + logger.atInfo().log( + "Launched RDE staging Dataflow job: %s", launchResponse.getJob().getId()); + jobNameBuilder.add(launchResponse.getJob().getId()); + } catch (IOException e) { + logger.atWarning().withCause(e).log("Pipeline Launch failed"); + errorMessageBuilder.add(String.format("Pipeline launch failed: %s", e.getMessage())); + } + } + ImmutableList errorMessages = errorMessageBuilder.build(); + ImmutableList jobNames = jobNameBuilder.build(); + if (!errorMessages.isEmpty()) { + response.setStatus(SC_INTERNAL_SERVER_ERROR); + String errorPayload = Joiner.on("; ").join(errorMessages); + if (!jobNames.isEmpty()) { + errorPayload = + String.format("%s (launched: %s)", errorPayload, Joiner.on(", ").join(jobNames)); + } + response.setPayload(errorPayload); + return; + } response.setStatus(SC_OK); - response.setPayload( - String.format("Launched RDE pipeline: %s", Joiner.on(", ").join(jobNameBuilder.build()))); + response.setPayload(String.format("Launched RDE pipeline: %s", Joiner.on(", ").join(jobNames))); } private ImmutableSetMultimap getStandardPendingDeposits() { diff --git a/core/src/main/java/google/registry/rde/RdeUploadAction.java b/core/src/main/java/google/registry/rde/RdeUploadAction.java index c5af597e0ca..a7ec719399f 100644 --- a/core/src/main/java/google/registry/rde/RdeUploadAction.java +++ b/core/src/main/java/google/registry/rde/RdeUploadAction.java @@ -51,6 +51,7 @@ import google.registry.rde.JSchSshSession.JSchSshSessionFactory; import google.registry.request.Action; import google.registry.request.HttpException.NoContentException; +import google.registry.request.HttpException.ServiceUnavailableException; import google.registry.request.Parameter; import google.registry.request.RequestParameters; import google.registry.request.Response; @@ -162,7 +163,7 @@ public void runWithLock(Instant watermark) throws Exception { .orElse(START_INSTANT); Duration timeSinceLastSftp = Duration.between(sftpCursorTime, clock.now()); if (timeSinceLastSftp.compareTo(sftpCooldown) < 0) { - throw new NoContentException( + throw new ServiceUnavailableException( String.format( "Waiting on %d minute SFTP cooldown for TLD %s to send %s upload; " + "last upload attempt was at %s (%d minutes ago)", diff --git a/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java b/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java index 62843d019d5..fd63ba0ba98 100644 --- a/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java +++ b/core/src/test/java/google/registry/batch/ResaveEntityActionTest.java @@ -18,6 +18,7 @@ import static google.registry.batch.AsyncTaskEnqueuer.PARAM_REQUESTED_TIME; import static google.registry.batch.AsyncTaskEnqueuer.PARAM_RESOURCE_KEY; import static google.registry.batch.AsyncTaskEnqueuer.QUEUE_ASYNC_ACTIONS; +import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.loadByEntity; import static google.registry.testing.DatabaseHelper.newDomain; @@ -25,9 +26,14 @@ import static google.registry.testing.DatabaseHelper.persistDomainWithPendingTransfer; import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.util.DateTimeUtils.plusDays; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import com.google.cloud.tasks.v2.HttpMethod; +import com.google.cloud.tasks.v2.Task; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import google.registry.model.domain.Domain; @@ -42,6 +48,7 @@ import google.registry.testing.FakeClock; import java.time.Duration; import java.time.Instant; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -55,12 +62,13 @@ @ExtendWith(MockitoExtension.class) public class ResaveEntityActionTest { + private final FakeClock clock = new FakeClock(Instant.parse("2016-02-11T10:00:00Z")); + @RegisterExtension final JpaIntegrationTestExtension jpa = - new JpaTestExtensions.Builder().buildIntegrationTestExtension(); + new JpaTestExtensions.Builder().withClock(clock).buildIntegrationTestExtension(); @Mock private Response response; - private final FakeClock clock = new FakeClock(Instant.parse("2016-02-11T10:00:00Z")); private AsyncTaskEnqueuer asyncTaskEnqueuer; private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); @@ -106,29 +114,31 @@ void test_domainPendingTransfer_isResavedAndTransferCompleted() { @Test void test_domainPendingDeletion_isResavedAndReenqueued() { + Instant deletionRequestedTime = Instant.parse("2016-02-11T10:00:00Z"); + Instant day30 = plusDays(deletionRequestedTime, 30); + Instant day35 = plusDays(deletionRequestedTime, 35); Domain newDomain = newDomain("domain.tld"); Domain domain = persistResource( newDomain .asBuilder() - .setDeletionTime(plusDays(clock.now(), 35)) + .setDeletionTime(day35) .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE)) .setGracePeriods( ImmutableSet.of( GracePeriod.createWithoutBillingEvent( GracePeriodStatus.REDEMPTION, newDomain.getRepoId(), - plusDays(clock.now(), 30), + day30, "TheRegistrar"))) .build()); clock.advanceBy(Duration.ofDays(30)); - Instant requestedTime = clock.now(); assertThat(domain.getGracePeriods()).isNotEmpty(); - runAction( - domain.createVKey().stringify(), - requestedTime, - ImmutableSortedSet.of(plusDays(requestedTime, 5))); + // Pass the original Day-0 requestedTime (as DomainDeleteFlow does); ResaveEntityAction must + // compute the next hop relative to the current transaction time (Day 30), not Day 0, so the + // Day-35 final purge (5d away, <= 30d MAX_ASYNC_ETA) is enqueued rather than silently dropped. + runAction(domain.createVKey().stringify(), deletionRequestedTime, ImmutableSortedSet.of(day35)); Domain resavedDomain = loadByEntity(domain); assertThat(resavedDomain.getGracePeriods()).isEmpty(); @@ -140,8 +150,36 @@ void test_domainPendingDeletion_isResavedAndReenqueued() { .service("backend") .header("content-type", "application/x-www-form-urlencoded") .param(PARAM_RESOURCE_KEY, resavedDomain.createVKey().stringify()) - .param(PARAM_REQUESTED_TIME, requestedTime.toString()) - .scheduleTime(plusDays(clock.now(), 5))); + .param(PARAM_REQUESTED_TIME, day30.toString()) + .scheduleTime(day35)); + } + + @Test + void test_domainPendingDeletion_executedPastLastResaveTime_doesNotFailOrReenqueue() { + Instant deletionRequestedTime = Instant.parse("2016-02-11T10:00:00Z"); + Instant day30 = plusDays(deletionRequestedTime, 30); + Instant day35 = plusDays(deletionRequestedTime, 35); + Domain newDomain = newDomain("late.tld"); + Domain domain = + persistResource( + newDomain + .asBuilder() + .setDeletionTime(day35) + .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE)) + .setGracePeriods( + ImmutableSet.of( + GracePeriod.createWithoutBillingEvent( + GracePeriodStatus.REDEMPTION, + newDomain.getRepoId(), + day30, + "TheRegistrar"))) + .build()); + clock.advanceBy(Duration.ofDays(36)); + + runAction(domain.createVKey().stringify(), deletionRequestedTime, ImmutableSortedSet.of(day35)); + Domain resavedDomain = loadByEntity(domain); + assertThat(resavedDomain.getGracePeriods()).isEmpty(); + cloudTasksHelper.assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS); } @Test @@ -155,4 +193,60 @@ void test_queuedTaskForNonExistentDomain_failsPermanently() { // ... and it shouldn't enqueue the subsequent re-save 5 days later. cloudTasksHelper.assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS); } + + @Test + void test_domainPendingDeletion_enqueuesResaveOutsideTransaction() { + Instant deletionRequestedTime = Instant.parse("2016-02-11T10:00:00Z"); + Instant day30 = plusDays(deletionRequestedTime, 30); + Instant day35 = plusDays(deletionRequestedTime, 35); + Domain newDomain = newDomain("outside-tx.tld"); + Domain domain = + persistResource( + newDomain + .asBuilder() + .setDeletionTime(day35) + .setStatusValues(ImmutableSet.of(StatusValue.PENDING_DELETE)) + .setGracePeriods( + ImmutableSet.of( + GracePeriod.createWithoutBillingEvent( + GracePeriodStatus.REDEMPTION, + newDomain.getRepoId(), + day30, + "TheRegistrar"))) + .build()); + clock.advanceBy(Duration.ofDays(30)); + + AtomicBoolean enqueuedOutsideTx = new AtomicBoolean(false); + CloudTasksUtils spiedCloudTasksUtils = spy(cloudTasksHelper.getTestCloudTasksUtils()); + doAnswer( + invocation -> { + assertThat(tm().inTransaction()).isFalse(); + assertThat(loadByEntity(domain).getGracePeriods()).isEmpty(); + enqueuedOutsideTx.set(true); + return invocation.callRealMethod(); + }) + .when(spiedCloudTasksUtils) + .enqueue(anyString(), any(Task.class)); + + ResaveEntityAction action = + new ResaveEntityAction( + domain.createVKey().stringify(), + deletionRequestedTime, + ImmutableSortedSet.of(day35), + AsyncTaskEnqueuerTest.createForTesting(spiedCloudTasksUtils), + response); + action.run(); + + assertThat(enqueuedOutsideTx.get()).isTrue(); + cloudTasksHelper.assertTasksEnqueued( + QUEUE_ASYNC_ACTIONS, + new TaskMatcher() + .path(ResaveEntityAction.PATH) + .method(HttpMethod.POST) + .service("backend") + .header("content-type", "application/x-www-form-urlencoded") + .param(PARAM_RESOURCE_KEY, domain.createVKey().stringify()) + .param(PARAM_REQUESTED_TIME, day30.toString()) + .scheduleTime(day35)); + } } diff --git a/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java b/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java index e2c812c5901..dc49fab495f 100644 --- a/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java +++ b/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java @@ -28,39 +28,72 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; +import google.registry.eppserver.handler.EppServiceHandler.ConnectionState; import google.registry.eppserver.metric.FrontendMetrics; import google.registry.eppserver.quota.EppServerQuotaManager; import google.registry.eppserver.quota.LocalConnectionLimiter; +import google.registry.networking.handler.SslServerInitializer; +import google.registry.networking.module.CertificateSupplierModule.TlsCredentials; import google.registry.request.RequestHandler; +import google.registry.testing.FakeClock; import google.registry.util.FakeHttpServletRequest; import google.registry.util.FakeHttpServletResponse; import google.registry.util.ProxyHttpHeaders; +import google.registry.util.SelfSignedCaCertificate; import google.registry.util.X509Utils; +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.DefaultEventLoopGroup; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.channel.local.LocalAddress; +import io.netty.channel.local.LocalChannel; +import io.netty.channel.local.LocalServerChannel; +import io.netty.handler.codec.LengthFieldBasedFrameDecoder; +import io.netty.handler.codec.LengthFieldPrepender; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.SslProvider; import io.netty.util.Attribute; import io.netty.util.DefaultAttributeMap; +import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.EventExecutor; +import io.netty.util.concurrent.EventExecutorGroup; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.ImmediateEventExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.ScheduledFuture; +import jakarta.servlet.http.HttpServletResponse; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.IntStream; import javax.annotation.Nullable; @@ -108,14 +141,15 @@ void setUp() { handler.requestHandler = requestHandler; - when(ctx.channel()).thenReturn(channel); - when(ctx.executor()).thenReturn(executor); + lenient().when(ctx.channel()).thenReturn(channel); + lenient().when(ctx.executor()).thenReturn(executor); lenient().when(channel.isActive()).thenReturn(true); lenient() .when(channel.attr(any())) .thenAnswer(invocation -> attributeMap.attr(invocation.getArgument(0))); - doAnswer( + lenient() + .doAnswer( invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); @@ -193,8 +227,11 @@ void testChannelActive_ipQuotaRejected() throws Exception { certPromise.setSuccess(certificate); + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); verify(metrics).registerQuotaRejection(eq("epp_connection_ip"), eq("192.168.1.1")); verify(ctx).close(); + handler.channelInactive(ctx); + verify(localConnectionLimiter, never()).releaseIp(any()); } @Test @@ -221,8 +258,13 @@ void testChannelRead0_registrarQuotaRejected() throws Exception { handler.channelRead0(ctx, inFrame); + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); verify(metrics).registerQuotaRejection(eq("epp_connection_registrar"), eq("RegistrarA")); verify(ctx).close(); + // Cleanup is idempotent across transitionToClosing() and channelInactive(). + handler.channelInactive(ctx); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + verify(localConnectionLimiter, never()).releaseRegistrar(any()); } @Test @@ -612,4 +654,664 @@ void testTruncatesOversizedCertificateHostnamesHeader() throws Exception { .isEqualTo(expectedHeader); } } + + @Test + void testChannelActive_missingCertPromise_closesImmediately() throws Exception { + when(channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY)).thenReturn(certPromiseAttr); + when(certPromiseAttr.get()).thenReturn(null); + + handler.channelActive(ctx); + + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(ctx).close(); + verify(requestHandler, never()).handleRequest(any(), any()); + } + + @Test + void testChannelActive_failedCertPromise_closesConnection() throws Exception { + certPromise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); + when(channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY)).thenReturn(certPromiseAttr); + when(certPromiseAttr.get()).thenReturn(certPromise); + + handler.channelActive(ctx); + certPromise.setFailure(new RuntimeException("TLS handshake failed")); + + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(ctx).close(); + verify(localConnectionLimiter, never()).acquireIp(any()); + verify(requestHandler, never()).handleRequest(any(), any()); + } + + @Test + void testChannelRead0_beforeTlsHandshakeCompletes_rejectsAndCloses() throws Exception { + certPromise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); + when(channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY)).thenReturn(certPromiseAttr); + when(certPromiseAttr.get()).thenReturn(certPromise); + + handler.channelActive(ctx); + assertThat(handler.getState()).isEqualTo(ConnectionState.AWAITING_TLS); + + // Frame arrives before TLS handshake completes: must not bypass quota or invoke requestHandler. + ByteBuf prematureFrame = Unpooled.wrappedBuffer("".getBytes(UTF_8)); + handler.channelRead0(ctx, prematureFrame); + + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(ctx).close(); + // Late TLS completion after transitioning to CLOSING must be ignored. + certPromise.setSuccess(certificate); + verify(localConnectionLimiter, never()).acquireIp(any()); + verify(requestHandler, never()).handleRequest(any(), any()); + verify(commandQuotaManager, never()).acquireQuota(any()); + } + + @Test + void testChannelRead0_failedLoginDoesNotLatchClid() throws Exception { + setUpSuccessfulHandshake(); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + when(localConnectionLimiter.acquireRegistrar("RealRegistrar")).thenReturn(true); + + AtomicInteger callCount = new AtomicInteger(); + doAnswer( + invocation -> { + FakeHttpServletRequest req = invocation.getArgument(0); + FakeHttpServletResponse rsp = invocation.getArgument(1); + int call = callCount.incrementAndGet(); + if (call == 1) { + // Failed login with spoofed clID must not receive REGISTRAR_ID header. + assertThat(req.getHeader(ProxyHttpHeaders.REGISTRAR_ID)).isNull(); + rsp.getWriter().write(""); + } else if (call == 2) { + // Second login attempt must still not carry the failed spoofed clID. + assertThat(req.getHeader(ProxyHttpHeaders.REGISTRAR_ID)).isNull(); + rsp.setHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, "RealRegistrar"); + rsp.setHeader("Set-Cookie", "SESSION_INFO=cmVhbA=="); + rsp.getWriter().write(""); + } else { + // Authenticated command carries verified registrar ID. + assertThat(req.getHeader(ProxyHttpHeaders.REGISTRAR_ID)).isEqualTo("RealRegistrar"); + rsp.getWriter().write(""); + } + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + + handler.channelRead0( + ctx, + Unpooled.wrappedBuffer( + "SpoofedRegistrar" + .getBytes(UTF_8))); + assertThat(handler.getState()).isEqualTo(ConnectionState.READY_UNAUTHENTICATED); + + handler.channelRead0( + ctx, + Unpooled.wrappedBuffer( + "RealRegistrar" + .getBytes(UTF_8))); + assertThat(handler.getState()).isEqualTo(ConnectionState.AUTHENTICATED); + + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + + verify(commandQuotaManager).acquireQuota("RealRegistrar"); + verify(commandQuotaManager, never()).acquireQuota("SpoofedRegistrar"); + } + + @Test + void testChannelRead0_pipelinedFrameAfterLogout_droppedAndCleanupIdempotent() throws Exception { + setUpSuccessfulHandshake(); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + when(localConnectionLimiter.acquireRegistrar("RegistrarA")).thenReturn(true); + + ChannelFuture mockFuture = mock(ChannelFuture.class); + when(ctx.writeAndFlush(any(ByteBuf.class))).thenReturn(mockFuture); + + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.setHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, "RegistrarA"); + rsp.getWriter().write("login ok"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + assertThat(handler.getState()).isEqualTo(ConnectionState.AUTHENTICATED); + + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.setHeader(ProxyHttpHeaders.EPP_SESSION, "close"); + rsp.getWriter().write("logout ok"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(mockFuture).addListener(ChannelFutureListener.CLOSE); + + // Pipelined frame after logout must be dropped without invoking requestHandler again. + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + // 1 greeting + 1 login + 1 logout = 3 invocations total (not 4). + verify(requestHandler, times(3)).handleRequest(any(), any()); + + // Duplicate channelInactive calls must release IP and registrar exactly once. + handler.channelInactive(ctx); + handler.channelInactive(ctx); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + verify(localConnectionLimiter, times(1)).releaseRegistrar("RegistrarA"); + } + + @Test + void testChannelRead0_non200HttpStatus400_failsClosedWithoutWriting() throws Exception { + setUpSuccessfulHandshake(); + clearInvocations(ctx); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + rsp.getWriter().write("Bad Request"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + + handler.channelRead0(ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(ctx, never()).writeAndFlush(any()); + verify(ctx).close(); + verify(scheduledFuture).cancel(false); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + handler.channelInactive(ctx); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + } + + @Test + void testChannelRead0_non200HttpStatus500_failsClosedAndReleasesLimits() throws Exception { + setUpSuccessfulHandshake(); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + when(localConnectionLimiter.acquireRegistrar("RegistrarA")).thenReturn(true); + + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.setHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, "RegistrarA"); + rsp.getWriter().write("login ok"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + assertThat(handler.getState()).isEqualTo(ConnectionState.AUTHENTICATED); + + clearInvocations(ctx); + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Error"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(ctx, never()).writeAndFlush(any()); + verify(ctx).close(); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + verify(localConnectionLimiter, times(1)).releaseRegistrar("RegistrarA"); + } + + @Test + void testChannelRead0_writeAndFlushThrowsOnClosingResponse_releasesLimitsAndCloses() + throws Exception { + setUpSuccessfulHandshake(); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + when(localConnectionLimiter.acquireRegistrar("RegistrarA")).thenReturn(true); + + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.setHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, "RegistrarA"); + rsp.getWriter().write("login ok"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + assertThat(handler.getState()).isEqualTo(ConnectionState.AUTHENTICATED); + + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.setHeader(ProxyHttpHeaders.EPP_SESSION, "close"); + rsp.getWriter().write("logout ok"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + when(ctx.writeAndFlush(any(ByteBuf.class))).thenThrow(new RuntimeException("write failed")); + + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(ctx).close(); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + verify(localConnectionLimiter, times(1)).releaseRegistrar("RegistrarA"); + handler.channelInactive(ctx); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + verify(localConnectionLimiter, times(1)).releaseRegistrar("RegistrarA"); + } + + @Test + void testChannelRead0_idTokenSupplierThrows_failsClosedAndReleasesLimits() throws Exception { + setUpSuccessfulHandshake(); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + when(localConnectionLimiter.acquireRegistrar("RegistrarA")).thenReturn(true); + + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.setHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, "RegistrarA"); + rsp.getWriter().write("login ok"); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + assertThat(handler.getState()).isEqualTo(ConnectionState.AUTHENTICATED); + + clearInvocations(ctx, requestHandler); + when(idTokenSupplier.get()).thenThrow(new RuntimeException("OIDC token fetch failed")); + + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8))); + + assertThat(handler.getState()).isEqualTo(ConnectionState.CLOSING); + verify(requestHandler, never()).handleRequest(any(), any()); + verify(ctx, never()).writeAndFlush(any()); + verify(ctx).close(); + verify(localConnectionLimiter, times(1)).releaseIp("192.168.1.1"); + verify(localConnectionLimiter, times(1)).releaseRegistrar("RegistrarA"); + } + + @Test + void testChannelActive_crossExecutorPromiseCompletesBeforeAddListener_processesQueuedRead() + throws Exception { + EventExecutorGroup ioGroup = new DefaultEventExecutorGroup(1); + EventExecutorGroup businessGroup = new DefaultEventExecutorGroup(1); + EventExecutor ioExecutor = ioGroup.next(); + EventExecutor businessExecutor = businessGroup.next(); + try { + when(ctx.executor()).thenReturn(businessExecutor); + when(channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY)).thenReturn(certPromiseAttr); + when(channel.attr(REMOTE_ADDRESS_KEY)).thenReturn(remoteAddressAttr); + when(remoteAddressAttr.get()).thenReturn("192.168.1.1"); + when(channel.attr(EppServiceHandler.CLIENT_CERTIFICATE_HASH_KEY)).thenReturn(certHashAttr); + when(certificate.getEncoded()).thenReturn(new byte[] {1, 2, 3}); + when(localConnectionLimiter.acquireIp("192.168.1.1")).thenReturn(true); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + + String expectedCertHash = X509Utils.getCertificateHash(certificate); + BlockingQueue observedBodies = new LinkedBlockingQueue<>(); + doAnswer( + invocation -> { + FakeHttpServletRequest req = invocation.getArgument(0); + FakeHttpServletResponse rsp = invocation.getArgument(1); + String body = new String(req.getInputStream().readAllBytes(), UTF_8); + observedBodies.add(body); + rsp.getWriter().write("" + body + ""); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + + // Simulate the TOCTOU window: certPromise is NOT done during channelActive's initial + // isDone() check, then completes on ioExecutor and queues channelRead0 on businessExecutor + // before addListener() registers the listener. + AtomicBoolean raceTriggered = new AtomicBoolean(false); + DefaultPromise racingPromise = + new DefaultPromise<>(ioExecutor) { + @Override + public Promise addListener( + GenericFutureListener> listener) { + if (raceTriggered.compareAndSet(false, true)) { + assertThat( + ioExecutor + .submit(() -> trySuccess(certificate)) + .syncUninterruptibly() + .getNow()) + .isTrue(); + businessExecutor.execute( + () -> + handler.channelRead0( + ctx, Unpooled.wrappedBuffer("".getBytes(UTF_8)))); + } + return super.addListener(listener); + } + }; + when(certPromiseAttr.get()).thenReturn(racingPromise); + + businessExecutor + .submit( + () -> { + handler.channelActive(ctx); + return null; + }) + .sync(); + + // Drain ioExecutor (which bounces the listener callback to businessExecutor) and then drain + // businessExecutor so both channelRead0 and the bounced no-op callback complete. + ioExecutor.submit(() -> null).sync(); + businessExecutor.submit(() -> null).sync(); + + assertThat(observedBodies).containsExactly("hello", "").inOrder(); + assertThat(businessExecutor.submit(handler::getState).get(5, TimeUnit.SECONDS)) + .isEqualTo(ConnectionState.READY_UNAUTHENTICATED); + verify(ctx, never()).close(); + verify(localConnectionLimiter, times(1)).acquireIp("192.168.1.1"); + verify(commandQuotaManager, times(2)).acquireQuota(expectedCertHash); + } finally { + ioGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS).syncUninterruptibly(); + businessGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS).syncUninterruptibly(); + } + } + + @Test + void testEmbeddedChannel_alreadyCompletedCertPromise_handlesHandshakeBeforePipelinedRead() + throws Exception { + SelfSignedCaCertificate clientSsc = SelfSignedCaCertificate.create(new FakeClock()); + String expectedCertHash = X509Utils.getCertificateHash(clientSsc.cert()); + LocalConnectionLimiter realLimiter = new LocalConnectionLimiter(5, 5); + EppServiceHandler embeddedHandler = + new EppServiceHandler( + "".getBytes(UTF_8), + metrics, + realLimiter, + commandQuotaManager, + () -> "fake_id_token", + "test-project", + 10); + + BlockingQueue observedBodies = new LinkedBlockingQueue<>(); + RequestHandler embeddedRequestHandler = mock(RequestHandler.class); + doAnswer( + invocation -> { + FakeHttpServletRequest req = invocation.getArgument(0); + FakeHttpServletResponse rsp = invocation.getArgument(1); + assertThat(req.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(expectedCertHash); + assertThat(req.getHeader(ProxyHttpHeaders.IP_ADDRESS)).isEqualTo("192.0.2.10"); + String body = new String(req.getInputStream().readAllBytes(), UTF_8); + observedBodies.add(body); + rsp.getWriter().write("" + body + ""); + return null; + }) + .when(embeddedRequestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + embeddedHandler.requestHandler = embeddedRequestHandler; + + // Complete certPromise BEFORE channelActive runs (simulates the businessGroup race where + // eventGroup finished TLS and queued a read before channelActive ran on businessGroup). + DefaultPromise completedPromise = + new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); + completedPromise.setSuccess(clientSsc.cert()); + + EmbeddedChannel embeddedChannel = + new EmbeddedChannel( + new ChannelInitializer() { + @Override + protected void initChannel(EmbeddedChannel ch) { + ch.attr(CLIENT_CERTIFICATE_PROMISE_KEY).set(completedPromise); + ch.attr(REMOTE_ADDRESS_KEY).set("192.0.2.10"); + ch.pipeline().addLast(embeddedHandler); + } + }); + + assertThat(embeddedHandler.getState()).isEqualTo(ConnectionState.READY_UNAUTHENTICATED); + embeddedChannel.writeInbound(Unpooled.wrappedBuffer("".getBytes(UTF_8))); + + assertThat(observedBodies.poll()).isEqualTo(""); + assertThat(observedBodies.poll()).isEqualTo(""); + verify(commandQuotaManager, times(2)).acquireQuota(expectedCertHash); + embeddedChannel.finishAndReleaseAll(); + } + + @Test + void testChannelActive_crossExecutorCertPromise_dispatchesToHandlerExecutor() throws Exception { + EventExecutorGroup businessGroup = new DefaultEventExecutorGroup(1); + EventExecutor businessExecutor = businessGroup.next(); + try { + certPromise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); + when(ctx.executor()).thenReturn(businessExecutor); + when(channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY)).thenReturn(certPromiseAttr); + when(certPromiseAttr.get()).thenReturn(certPromise); + when(channel.attr(REMOTE_ADDRESS_KEY)).thenReturn(remoteAddressAttr); + when(remoteAddressAttr.get()).thenReturn("192.168.1.1"); + when(channel.attr(EppServiceHandler.CLIENT_CERTIFICATE_HASH_KEY)).thenReturn(certHashAttr); + when(certificate.getEncoded()).thenReturn(new byte[] {1, 2, 3}); + when(localConnectionLimiter.acquireIp("192.168.1.1")).thenReturn(true); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + + CountDownLatch greetingDispatched = new CountDownLatch(1); + AtomicBoolean ranOnBusinessExecutor = new AtomicBoolean(false); + doAnswer( + invocation -> { + ranOnBusinessExecutor.set(businessExecutor.inEventLoop()); + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.getWriter().write(""); + greetingDispatched.countDown(); + return null; + }) + .when(requestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + + businessExecutor + .submit( + () -> { + handler.channelActive(ctx); + return null; + }) + .sync(); + assertThat(businessExecutor.inEventLoop()).isFalse(); + + // Complete the TLS promise off businessExecutor (simulating Netty's I/O event loop). + certPromise.setSuccess(certificate); + assertThat(greetingDispatched.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(ranOnBusinessExecutor.get()).isTrue(); + assertThat(businessExecutor.submit(handler::getState).get(5, TimeUnit.SECONDS)) + .isEqualTo(ConnectionState.READY_UNAUTHENTICATED); + + businessExecutor + .submit( + () -> { + handler.channelInactive(ctx); + return null; + }) + .sync(); + verify(localConnectionLimiter).releaseIp("192.168.1.1"); + } finally { + businessGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS).syncUninterruptibly(); + } + } + + @Test + void testLocalChannel_fullPipeline_tlsLoginCommandLogout() throws Exception { + Instant certNotBefore = Instant.parse("2000-01-01T00:00:00Z"); + Instant certNotAfter = Instant.parse("2099-01-01T00:00:00Z"); + SelfSignedCaCertificate serverSsc = + SelfSignedCaCertificate.create("www.example.tld", certNotBefore, certNotAfter); + SelfSignedCaCertificate clientSsc = + SelfSignedCaCertificate.create("client.example.tld", certNotBefore, certNotAfter); + String expectedCertHash = X509Utils.getCertificateHash(clientSsc.cert()); + + EventLoopGroup eventGroup = new DefaultEventLoopGroup(1); + LocalConnectionLimiter realLimiter = new LocalConnectionLimiter(1, 1); + BlockingQueue clientReceived = new LinkedBlockingQueue<>(); + CountDownLatch serverClosed = new CountDownLatch(1); + CountDownLatch serverInactive = new CountDownLatch(1); + + EppServiceHandler localHandler = + new EppServiceHandler( + "".getBytes(UTF_8), + metrics, + realLimiter, + commandQuotaManager, + () -> "fake_id_token", + "test-project", + 30); + + RequestHandler localRequestHandler = mock(RequestHandler.class); + doAnswer( + invocation -> { + FakeHttpServletRequest req = invocation.getArgument(0); + FakeHttpServletResponse rsp = invocation.getArgument(1); + assertThat(req.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(expectedCertHash); + assertThat(req.getHeader(ProxyHttpHeaders.IP_ADDRESS)).isEqualTo("203.0.113.5"); + String body = new String(req.getInputStream().readAllBytes(), UTF_8); + if (body.contains("")) { + rsp.getWriter().write(""); + } else if (body.contains("")) { + rsp.setHeader(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, "TheRegistrar"); + rsp.setHeader("Set-Cookie", "SESSION_INFO=dGhlcmVn"); + rsp.getWriter().write("login-ok"); + } else if (body.contains("")) { + assertThat(req.getHeader(ProxyHttpHeaders.REGISTRAR_ID)).isEqualTo("TheRegistrar"); + assertThat(req.getHeader("Cookie")).isEqualTo("SESSION_INFO=dGhlcmVn"); + rsp.setHeader(ProxyHttpHeaders.EPP_SESSION, "close"); + rsp.getWriter().write("logout-ok"); + } + return null; + }) + .when(localRequestHandler) + .handleRequest(any(FakeHttpServletRequest.class), any(FakeHttpServletResponse.class)); + localHandler.requestHandler = localRequestHandler; + + SslServerInitializer sslServerInitializer = + new SslServerInitializer<>( + true, + false, + SslProvider.JDK, + Suppliers.ofInstance( + new TlsCredentials(serverSsc.key(), ImmutableList.of(serverSsc.cert())))); + + LocalAddress address = new LocalAddress("EPP_SERVICE_HANDLER_FULL_PIPELINE"); + Channel serverChannel = null; + try { + serverChannel = + new ServerBootstrap() + .group(eventGroup) + .channel(LocalServerChannel.class) + .childHandler( + new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) { + ch.attr(REMOTE_ADDRESS_KEY).set("203.0.113.5"); + ch.pipeline() + .addLast(sslServerInitializer) + .addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, -4, 4)) + .addLast(new LengthFieldPrepender(4, true)) + .addLast("EppServiceHandler", localHandler) + .addLast( + new ChannelInboundHandlerAdapter() { + @Override + public void channelInactive(ChannelHandlerContext ctx) { + serverInactive.countDown(); + ctx.fireChannelInactive(); + } + }); + ch.closeFuture().addListener(f -> serverClosed.countDown()); + } + }) + .bind(address) + .sync() + .channel(); + + Channel clientChannel = + new Bootstrap() + .group(eventGroup) + .channel(LocalChannel.class) + .handler( + new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) throws Exception { + ch.pipeline() + .addLast( + SslContextBuilder.forClient() + .trustManager(serverSsc.cert()) + .keyManager(clientSsc.key(), clientSsc.cert()) + .sslProvider(SslProvider.JDK) + .build() + .newHandler(ch.alloc(), "www.example.tld", 700)) + .addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, -4, 4)) + .addLast(new LengthFieldPrepender(4, true)) + .addLast( + new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ByteBuf buf = (ByteBuf) msg; + try { + clientReceived.add(buf.toString(UTF_8)); + } finally { + buf.release(); + } + } + }); + } + }) + .connect(address) + .sync() + .channel(); + + // 1. Server automatically sends after mTLS completes and holds IP slot. + assertThat(clientReceived.poll(5, TimeUnit.SECONDS)).isEqualTo(""); + assertThat(realLimiter.acquireIp("203.0.113.5")).isFalse(); + + // 2. Client sends and server holds registrar slot. + clientChannel + .writeAndFlush( + Unpooled.wrappedBuffer( + "TheRegistrar" + .getBytes(UTF_8))) + .sync(); + assertThat(clientReceived.poll(5, TimeUnit.SECONDS)) + .isEqualTo("login-ok"); + assertThat(realLimiter.acquireRegistrar("TheRegistrar")).isFalse(); + + // 3. Client sends and server closes connection and releases both slots in + // channelInactive before forwarding the event to the tail latch handler. + clientChannel + .writeAndFlush( + Unpooled.wrappedBuffer("".getBytes(UTF_8))) + .sync(); + assertThat(clientReceived.poll(5, TimeUnit.SECONDS)) + .isEqualTo("logout-ok"); + assertThat(serverClosed.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(serverInactive.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(localHandler.getState()).isEqualTo(ConnectionState.CLOSING); + assertThat(realLimiter.acquireIp("203.0.113.5")).isTrue(); + assertThat(realLimiter.acquireRegistrar("TheRegistrar")).isTrue(); + } finally { + if (serverChannel != null) { + serverChannel.close().syncUninterruptibly(); + } + eventGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS).syncUninterruptibly(); + } + } } diff --git a/core/src/test/java/google/registry/flows/EppRequestHandlerTest.java b/core/src/test/java/google/registry/flows/EppRequestHandlerTest.java new file mode 100644 index 00000000000..fa46ba607d2 --- /dev/null +++ b/core/src/test/java/google/registry/flows/EppRequestHandlerTest.java @@ -0,0 +1,134 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.flows; + +import static com.google.common.truth.Truth.assertThat; +import static google.registry.model.eppoutput.Result.Code.AUTHENTICATION_ERROR; +import static google.registry.model.eppoutput.Result.Code.AUTHENTICATION_ERROR_CLOSING_CONNECTION; +import static google.registry.model.eppoutput.Result.Code.SUCCESS; +import static google.registry.model.eppoutput.Result.Code.SUCCESS_AND_CLOSE; +import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import google.registry.model.eppcommon.Trid; +import google.registry.model.eppoutput.EppOutput; +import google.registry.model.eppoutput.EppResponse; +import google.registry.model.eppoutput.Result; +import google.registry.testing.FakeResponse; +import google.registry.util.ProxyHttpHeaders; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link EppRequestHandler}. */ +class EppRequestHandlerTest { + + private final EppController eppController = mock(EppController.class); + private final SessionMetadata sessionMetadata = mock(SessionMetadata.class); + private final TransportCredentials credentials = new PasswordOnlyTransportCredentials(); + private final FakeResponse response = new FakeResponse(); + private final EppRequestHandler handler = new EppRequestHandler(); + + @BeforeEach + void beforeEach() { + handler.eppController = eppController; + handler.response = response; + } + + private static EppOutput createResponseOutput(Result.Code code) { + return EppOutput.create( + new EppResponse.Builder() + .setResult(Result.create(code)) + .setTrid(Trid.create("client-trid", "server-trid")) + .build()); + } + + @Test + void testExecuteEpp_successAndClose1500_setsCloseHeader() { + when(sessionMetadata.getRegistrarId()).thenThrow(new IllegalStateException("invalidated")); + when(eppController.handleEppCommand(any(), any(), any(), anyBoolean(), anyBoolean(), any())) + .thenReturn(createResponseOutput(SUCCESS_AND_CLOSE)); + + handler.executeEpp( + sessionMetadata, credentials, EppRequestSource.TLS, false, false, "".getBytes(UTF_8)); + + assertThat(response.getStatus()).isEqualTo(SC_OK); + assertThat(response.getHeaders()).containsEntry(ProxyHttpHeaders.EPP_SESSION, "close"); + assertThat(response.getHeaders()).doesNotContainKey(ProxyHttpHeaders.LOGGED_IN_REGISTRAR); + verify(sessionMetadata).save(response); + } + + @Test + void testExecuteEpp_authErrorClosingConnection2501_setsCloseHeader() { + when(sessionMetadata.getRegistrarId()).thenReturn(null); + when(eppController.handleEppCommand(any(), any(), any(), anyBoolean(), anyBoolean(), any())) + .thenReturn(createResponseOutput(AUTHENTICATION_ERROR_CLOSING_CONNECTION)); + + handler.executeEpp( + sessionMetadata, credentials, EppRequestSource.TLS, false, false, "".getBytes(UTF_8)); + + assertThat(response.getStatus()).isEqualTo(SC_OK); + assertThat(response.getHeaders()).containsEntry(ProxyHttpHeaders.EPP_SESSION, "close"); + assertThat(response.getHeaders()).doesNotContainKey(ProxyHttpHeaders.LOGGED_IN_REGISTRAR); + verify(sessionMetadata).save(response); + } + + @Test + void testExecuteEpp_regularAuthError2200_doesNotSetCloseHeader() { + when(sessionMetadata.getRegistrarId()).thenReturn(null); + when(eppController.handleEppCommand(any(), any(), any(), anyBoolean(), anyBoolean(), any())) + .thenReturn(createResponseOutput(AUTHENTICATION_ERROR)); + + handler.executeEpp( + sessionMetadata, credentials, EppRequestSource.TLS, false, false, "".getBytes(UTF_8)); + + assertThat(response.getStatus()).isEqualTo(SC_OK); + assertThat(response.getHeaders()).doesNotContainKey(ProxyHttpHeaders.EPP_SESSION); + verify(sessionMetadata).save(response); + } + + @Test + void testExecuteEpp_success1000_setsLoggedInRegistrarAndDoesNotClose() { + when(sessionMetadata.getRegistrarId()).thenReturn("TheRegistrar"); + when(eppController.handleEppCommand(any(), any(), any(), anyBoolean(), anyBoolean(), any())) + .thenReturn(createResponseOutput(SUCCESS)); + + handler.executeEpp( + sessionMetadata, credentials, EppRequestSource.TLS, false, false, "".getBytes(UTF_8)); + + assertThat(response.getStatus()).isEqualTo(SC_OK); + assertThat(response.getHeaders()) + .containsEntry(ProxyHttpHeaders.LOGGED_IN_REGISTRAR, "TheRegistrar"); + assertThat(response.getHeaders()).doesNotContainKey(ProxyHttpHeaders.EPP_SESSION); + verify(sessionMetadata).save(response); + } + + @Test + void testExecuteEpp_controllerException_returns400AndSavesSession() { + when(eppController.handleEppCommand(any(), any(), any(), anyBoolean(), anyBoolean(), any())) + .thenThrow(new IllegalStateException("boom")); + + handler.executeEpp( + sessionMetadata, credentials, EppRequestSource.TLS, false, false, "".getBytes(UTF_8)); + + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + verify(sessionMetadata).save(response); + } +} diff --git a/core/src/test/java/google/registry/rde/RdeStagingActionTest.java b/core/src/test/java/google/registry/rde/RdeStagingActionTest.java index 537568544cc..83d7b5594d4 100644 --- a/core/src/test/java/google/registry/rde/RdeStagingActionTest.java +++ b/core/src/test/java/google/registry/rde/RdeStagingActionTest.java @@ -23,8 +23,11 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import com.google.api.services.dataflow.model.Job; import com.google.api.services.dataflow.model.LaunchFlexTemplateRequest; +import com.google.api.services.dataflow.model.LaunchFlexTemplateResponse; import com.google.cloud.storage.contrib.nio.testing.LocalStorageHelper; import com.google.common.collect.ImmutableSet; import google.registry.beam.BeamActionTestBase; @@ -34,6 +37,7 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.request.HttpException.BadRequestException; import google.registry.testing.FakeClock; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.DayOfWeek; import java.time.Duration; @@ -258,6 +262,38 @@ void testManualRun_validParameters_runsPipeline() throws Exception { .launch(eq("projectId"), eq("jobRegion"), any(LaunchFlexTemplateRequest.class)); } + @Test + void testRun_pipelineLaunchFails_returns500() throws Exception { + createTldWithEscrowEnabled("lol"); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); + when(launch.execute()).thenThrow(new IOException("dataflow unavailable")); + action.run(); + assertThat(response.getStatus()).isEqualTo(500); + assertThat(response.getPayload()).contains("Pipeline launch failed: dataflow unavailable"); + } + + @Test + void testManualRun_partialPipelineLaunchFailure_returns500() throws Exception { + createTldWithEscrowEnabled("lol"); + clock.setTo(Instant.parse("2000-01-01T00:00:00Z")); + action.manual = true; + action.directory = Optional.of("test/"); + action.modeStrings = ImmutableSet.of("full"); + action.tlds = ImmutableSet.of("lol"); + action.watermarks = + ImmutableSet.of( + Instant.parse("1999-12-31T00:00:00Z"), Instant.parse("2001-01-01T00:00:00Z")); + when(launch.execute()) + .thenThrow(new IOException("quota exceeded")) + .thenReturn(new LaunchFlexTemplateResponse().setJob(new Job().setId("jobid-second"))); + action.run(); + assertThat(response.getStatus()).isEqualTo(500); + assertThat(response.getPayload()).contains("Pipeline launch failed: quota exceeded"); + assertThat(response.getPayload()).contains("launched: jobid-second"); + verify(templates, times(2)) + .launch(eq("projectId"), eq("jobRegion"), any(LaunchFlexTemplateRequest.class)); + } + private static void createTldWithEscrowEnabled(final String tld) { createTld(tld); persistResource(Tld.get(tld).asBuilder().setEscrowEnabled(true).build()); diff --git a/core/src/test/java/google/registry/rde/RdeUploadActionTest.java b/core/src/test/java/google/registry/rde/RdeUploadActionTest.java index 4024f7b84b3..1195e6d0dfb 100644 --- a/core/src/test/java/google/registry/rde/RdeUploadActionTest.java +++ b/core/src/test/java/google/registry/rde/RdeUploadActionTest.java @@ -54,6 +54,7 @@ import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.rde.JSchSshSession.JSchSshSessionFactory; import google.registry.request.HttpException.NoContentException; +import google.registry.request.HttpException.ServiceUnavailableException; import google.registry.request.RequestParameters; import google.registry.testing.BouncyCastleProviderExtension; import google.registry.testing.CloudTasksHelper; @@ -461,7 +462,7 @@ void testRunWithLock_stagingNotFinished_throws204() { } @Test - void testRunWithLock_sftpCooldownNotPassed_throws204() { + void testRunWithLock_sftpCooldownNotPassed_throws503() { RdeUploadAction action = createAction(URI.create("sftp://user:password@localhost:32323/")); action.sftpCooldown = Duration.ofHours(2); Instant stagingCursor = Instant.parse("2010-10-18T00:00:00Z"); @@ -470,8 +471,9 @@ void testRunWithLock_sftpCooldownNotPassed_throws204() { uploadCursor.minus(Duration.ofMinutes(97)); // Within the 2-hour cooldown period. persistResource(Cursor.createScoped(RDE_STAGING, stagingCursor, Tld.get("tld"))); persistResource(Cursor.createScoped(RDE_UPLOAD_SFTP, sftpCursor, Tld.get("tld"))); - NoContentException thrown = - assertThrows(NoContentException.class, () -> action.runWithLock(uploadCursor)); + ServiceUnavailableException thrown = + assertThrows(ServiceUnavailableException.class, () -> action.runWithLock(uploadCursor)); + assertThat(thrown.getResponseCode()).isEqualTo(503); assertThat(thrown) .hasMessageThat() .isEqualTo( diff --git a/jetty/kubernetes/nomulus-backend.yaml b/jetty/kubernetes/nomulus-backend.yaml index 29995c2efab..efac7b41e3f 100644 --- a/jetty/kubernetes/nomulus-backend.yaml +++ b/jetty/kubernetes/nomulus-backend.yaml @@ -53,10 +53,14 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: backend - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # jetty/start.sh) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler diff --git a/jetty/kubernetes/nomulus-console.yaml b/jetty/kubernetes/nomulus-console.yaml index a30c277b0a5..d8f43343459 100644 --- a/jetty/kubernetes/nomulus-console.yaml +++ b/jetty/kubernetes/nomulus-console.yaml @@ -60,10 +60,14 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: console - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # jetty/start.sh) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler diff --git a/jetty/kubernetes/nomulus-epp-server.yaml b/jetty/kubernetes/nomulus-epp-server.yaml index e553426ac9c..a57b7fbd4aa 100644 --- a/jetty/kubernetes/nomulus-epp-server.yaml +++ b/jetty/kubernetes/nomulus-epp-server.yaml @@ -63,10 +63,14 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: epp-server - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # jetty/start.sh) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler diff --git a/jetty/kubernetes/nomulus-frontend.yaml b/jetty/kubernetes/nomulus-frontend.yaml index 654aab034a0..c2fb899fa45 100644 --- a/jetty/kubernetes/nomulus-frontend.yaml +++ b/jetty/kubernetes/nomulus-frontend.yaml @@ -61,10 +61,14 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: frontend - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # jetty/start.sh) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" - name: EPP image: gcr.io/GCP_PROJECT/proxy ports: @@ -95,10 +99,14 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: EPP - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # jetty/start.sh) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" --- # Only need to define the service account once per cluster. apiVersion: v1 diff --git a/jetty/kubernetes/nomulus-pubapi.yaml b/jetty/kubernetes/nomulus-pubapi.yaml index f5d898d69a8..2dd8e12812a 100644 --- a/jetty/kubernetes/nomulus-pubapi.yaml +++ b/jetty/kubernetes/nomulus-pubapi.yaml @@ -68,10 +68,14 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: pubapi - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # jetty/start.sh) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler diff --git a/jetty/start.sh b/jetty/start.sh index 134dcf07898..cd03dc7b847 100755 --- a/jetty/start.sh +++ b/jetty/start.sh @@ -36,6 +36,9 @@ JVM_OPTS=( # defense-in-depth for CVE-2026-114938 (JDK-8393212); Base64 throughput # impact in Nomulus is negligible. -XX:-UseBASE64Intrinsics + # Disable server-side TLS session tickets so cached mTLS SslContexts always + # perform full handshakes and preserve client intermediate cert chains. + -Djdk.tls.server.enableSessionTicketExtension=false -Dgoogle.registry.environment="${env}" -Djava.util.logging.config.file=/logging.properties -jar /usr/local/jetty/start.jar diff --git a/networking/build.gradle b/networking/build.gradle index cf2613fe3cf..fb96ed60472 100644 --- a/networking/build.gradle +++ b/networking/build.gradle @@ -48,6 +48,9 @@ dependencies { test { useJUnitPlatform() + // Match production JDK_JAVA_OPTIONS: disable server-side TLS session tickets so cached mTLS + // SslContexts always perform full handshakes and preserve client intermediate cert chains. + systemProperty 'jdk.tls.server.enableSessionTicketExtension', 'false' } // Make testing artifacts available to be depended up on by other projects. diff --git a/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java b/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java index 8d582053f89..0dbff44cd4e 100644 --- a/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java +++ b/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java @@ -25,6 +25,7 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.flogger.FluentLogger; +import google.registry.networking.module.CertificateSupplierModule.TlsCredentials; import google.registry.util.X509Utils.CertificateChainValidationResult; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; @@ -32,6 +33,7 @@ import io.netty.channel.ChannelInitializer; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.ssl.ClientAuth; +import io.netty.handler.ssl.OpenSslServerSessionContext; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; @@ -41,7 +43,6 @@ import io.netty.util.AttributeKey; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; -import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; @@ -51,6 +52,7 @@ import java.security.interfaces.RSAPublicKey; import java.util.Optional; import java.util.function.Supplier; +import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; @@ -127,29 +129,29 @@ public class SslServerInitializer extends ChannelInitializer< private static final int MAX_LOGGED_HOSTNAMES = 10; private static final int MAX_LOGGED_FAILURE_REASON_CHARS = 512; + private record CachedSslContext(TlsCredentials credentials, SslContext sslContext) {} + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final boolean requireClientCert; // TODO(jianglai): Always validate client certs (if required). private final boolean validateClientCert; private final SslProvider sslProvider; - // We use suppliers for the key/cert pair because they are fetched and cached from GCS, and can - // change when the artifacts on GCS changes. - private final Supplier privateKeySupplier; - private final Supplier> certificatesSupplier; + // We use an atomic supplier for the key/cert bundle because it is fetched and cached from GCS + // under a single TTL and can rotate when the PEM artifact on GCS changes. + private final Supplier tlsCredentialsSupplier; private final Optional trustManager; + private volatile CachedSslContext cachedSslContext; public SslServerInitializer( boolean requireClientCert, boolean validateClientCert, SslProvider sslProvider, - Supplier privateKeySupplier, - Supplier> certificatesSupplier) { + Supplier tlsCredentialsSupplier) { this( requireClientCert, validateClientCert, sslProvider, - privateKeySupplier, - certificatesSupplier, + tlsCredentialsSupplier, requireClientCert ? Optional.of(getDefaultTrustManager()) : Optional.empty()); } @@ -158,8 +160,7 @@ public SslServerInitializer( boolean requireClientCert, boolean validateClientCert, SslProvider sslProvider, - Supplier privateKeySupplier, - Supplier> certificatesSupplier, + Supplier tlsCredentialsSupplier, Optional trustManager) { logger.atInfo().log("Server SSL Provider: %s", sslProvider); checkArgument( @@ -171,26 +172,60 @@ public SslServerInitializer( "Trust manager is required when client certificates are required."); this.requireClientCert = requireClientCert; this.validateClientCert = validateClientCert; - this.sslProvider = sslProvider; - this.privateKeySupplier = privateKeySupplier; - this.certificatesSupplier = certificatesSupplier; + this.sslProvider = checkNotNull(sslProvider, "SSL provider cannot be null"); + this.tlsCredentialsSupplier = + checkNotNull(tlsCredentialsSupplier, "TLS credentials supplier cannot be null"); this.trustManager = trustManager; + if (requireClientCert + && !"false" + .equalsIgnoreCase(System.getProperty("jdk.tls.server.enableSessionTicketExtension"))) { + logger.atWarning().log( + "Server-side TLS session tickets are enabled" + + " (-Djdk.tls.server.enableSessionTicketExtension=false is not set); resumed mTLS" + + " sessions on BoringSSL may omit client intermediate certificates."); + } + } + + @VisibleForTesting + SslContext getOrBuildSslContext() throws SSLException { + TlsCredentials credentials = + checkNotNull(tlsCredentialsSupplier.get(), "TLS credentials cannot be null"); + CachedSslContext current = cachedSslContext; + if (current != null && current.credentials().equals(credentials)) { + return current.sslContext(); + } + synchronized (this) { + credentials = checkNotNull(tlsCredentialsSupplier.get(), "TLS credentials cannot be null"); + current = cachedSslContext; + if (current != null && current.credentials().equals(credentials)) { + return current.sslContext(); + } + SslContext rebuilt = + SslContextBuilder.forServer( + credentials.privateKey(), + credentials.certificates().toArray(new X509Certificate[0])) + .sslProvider(sslProvider) + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .clientAuth(requireClientCert ? ClientAuth.REQUIRE : ClientAuth.NONE) + .protocols(SUPPORTED_TLS_VERSIONS) + .ciphers(ALLOWED_TLS_CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .build(); + if (requireClientCert + && rebuilt.sessionContext() instanceof OpenSslServerSessionContext openSslContext) { + // Netty 4.2 ignores SslContextBuilder.sessionCacheSize(0); disable the server session + // cache explicitly (SSL_SESS_CACHE_OFF) so resumed BoringSSL sessions cannot omit client + // intermediate certificates and break post-handshake chain validation. + openSslContext.setSessionCacheEnabled(false); + } + logger.atInfo().log("Available Cipher Suites: %s", rebuilt.cipherSuites()); + cachedSslContext = new CachedSslContext(credentials, rebuilt); + return rebuilt; + } } @Override protected void initChannel(C channel) throws Exception { - SslContext sslContext = - SslContextBuilder.forServer( - privateKeySupplier.get(), - certificatesSupplier.get().toArray(new X509Certificate[0])) - .sslProvider(sslProvider) - .trustManager(InsecureTrustManagerFactory.INSTANCE) - .clientAuth(requireClientCert ? ClientAuth.REQUIRE : ClientAuth.NONE) - .protocols(SUPPORTED_TLS_VERSIONS) - .ciphers(ALLOWED_TLS_CIPHERS, SupportedCipherSuiteFilter.INSTANCE) - .build(); - - logger.atInfo().log("Available Cipher Suites: %s", sslContext.cipherSuites()); + SslContext sslContext = getOrBuildSslContext(); SslHandler sslHandler = sslContext.newHandler(channel.alloc()); sslHandler.setHandshakeTimeoutMillis(20000); @@ -204,6 +239,12 @@ protected void initChannel(C channel) throws Exception { if (future.isSuccess()) { try { SSLSession sslSession = sslHandler.engine().getSession(); + // Invalidate the server-side session immediately so neither accepted nor + // rejected/error handshakes leave a resumable entry in the stateful cache + // (JDK SSLSessionContext.setSessionCacheSize(0) means unlimited; + // invalidation does not affect this active connection or subsequent reads + // of sslSession metadata). + sslSession.invalidate(); Certificate[] peerCertificates = sslSession.getPeerCertificates(); X509Certificate clientCertificate = (X509Certificate) peerCertificates[0]; String clientCertificateHash = getCertificateHash(clientCertificate); @@ -219,13 +260,11 @@ protected void initChannel(C channel) throws Exception { } catch (CertificateNotYetValidException | CertificateExpiredException e) { validityException = e; } - // Note: initChannel builds a fresh SslContext per connection today, so - // cross-connection TLS session resumption does not occur. If SslContext is - // ever cached across connections, BoringSSL (SslProvider.OPENSSL) omits - // intermediate certificates on resumed server sessions - // (SSL_get_peer_cert_chain returns empty), which would flip chainValidated - // to false on resumed 3+ tier chains unless resumption/tickets are disabled - // for mTLS or the validation outcome is cached in SSLSession. + // Server-side session resumption is disabled for mTLS (SSL_SESS_CACHE_OFF + // on OpenSSL, unconditional sslSession.invalidate() above, and + // -Djdk.tls.server.enableSessionTicketExtension=false in production JVM + // flags) so every connection presents the full client certificate chain + // and resumed BoringSSL sessions cannot drop intermediate certificates. CertificateChainValidationResult validationResult = validityException != null ? CertificateChainValidationResult.failed( diff --git a/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java b/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java index 0b5ffa23389..54d7c19be49 100644 --- a/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java +++ b/networking/src/main/java/google/registry/networking/module/CertificateSupplierModule.java @@ -14,11 +14,12 @@ package google.registry.networking.module; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Suppliers.memoizeWithExpiration; import static com.google.common.collect.ImmutableList.toImmutableList; import static java.nio.charset.StandardCharsets.UTF_8; -import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; @@ -100,11 +101,22 @@ public enum Mode { SELF_SIGNED } - @Qualifier - @interface PemFile {} + /** + * Atomic bundle of a server TLS private key and its ordered X.509 certificate chain. + * + *

Bundling both artifacts under a single cached supplier prevents certificate rotation from + * pairing a newly fetched key with a stale certificate chain (or vice versa). + */ + public record TlsCredentials(PrivateKey privateKey, ImmutableList certificates) { + public TlsCredentials { + checkNotNull(privateKey, "Private key cannot be null"); + checkNotNull(certificates, "Certificates cannot be null"); + checkArgument(!certificates.isEmpty(), "Certificates cannot be empty"); + } + } @Qualifier - private @interface P12File {} + @interface PemFile {} @Qualifier private @interface SelfSigned {} @@ -127,31 +139,15 @@ private static ImmutableList filterAndConvert( @Singleton @Provides - static Supplier providePrivateKeySupplier( - Mode mode, - @PemFile Lazy> pemPrivateKeySupplier, - @P12File Lazy> p12PrivateKeySupplier, - @SelfSigned Lazy> selfSignedPrivateKeySupplier) { - return switch (mode) { - case PEM_FILE -> pemPrivateKeySupplier.get(); - case P12_FILE -> p12PrivateKeySupplier.get(); - case SELF_SIGNED -> selfSignedPrivateKeySupplier.get(); - default -> throw new RuntimeException("Certificate provider mode exhausted."); - }; - } - - @Singleton - @Provides - static Supplier> provideCertificatesSupplier( + static Supplier provideTlsCredentialsSupplier( Mode mode, - @PemFile Lazy>> pemCertificatesSupplier, - @P12File Lazy>> p12CertificatesSupplier, - @SelfSigned Lazy>> selfSignedCertificatesSupplier) { + @PemFile Lazy> pemTlsCredentialsSupplier, + @SelfSigned Lazy> selfSignedTlsCredentialsSupplier) { return switch (mode) { - case PEM_FILE -> pemCertificatesSupplier.get(); - case P12_FILE -> p12CertificatesSupplier.get(); - case SELF_SIGNED -> selfSignedCertificatesSupplier.get(); - default -> throw new RuntimeException("Certificate provider mode exhausted."); + case PEM_FILE -> pemTlsCredentialsSupplier.get(); + case SELF_SIGNED -> selfSignedTlsCredentialsSupplier.get(); + case P12_FILE -> + throw new UnsupportedOperationException("P12_FILE certificate mode is not supported."); }; } @@ -168,46 +164,28 @@ static SelfSignedCaCertificate provideSelfSignedCertificate(Clock clock) { @Singleton @Provides @SelfSigned - static Supplier provideSelfSignedPrivateKeySupplier(SelfSignedCaCertificate ssc) { - return Suppliers.ofInstance(ssc.key()); - } - - @Singleton - @Provides - @SelfSigned - static Supplier> provideSelfSignedCertificatesSupplier( + static Supplier provideSelfSignedTlsCredentialsSupplier( SelfSignedCaCertificate ssc) { - return Suppliers.ofInstance(ImmutableList.of(ssc.cert())); + return Suppliers.ofInstance(new TlsCredentials(ssc.key(), ImmutableList.of(ssc.cert()))); } - @Provides - @PemFile - static ImmutableList providePemObjects(@Named("pemBytes") byte[] pemBytes) { - PEMParser pemParser = - new PEMParser(new InputStreamReader(new ByteArrayInputStream(pemBytes), UTF_8)); + private static ImmutableList parsePemObjects(byte[] pemBytes) { ImmutableList.Builder listBuilder = new ImmutableList.Builder<>(); - Object obj; // PEMParser returns an object (private key, certificate, etc) each time readObject() is called, // until no more object is to be read from the file. - while (true) { - try { - obj = pemParser.readObject(); - if (obj == null) { - break; - } else { - listBuilder.add(obj); - } - } catch (IOException e) { - throw new RuntimeException("Cannot parse PEM file correctly.", e); + try (PEMParser pemParser = + new PEMParser(new InputStreamReader(new ByteArrayInputStream(pemBytes), UTF_8))) { + Object obj; + while ((obj = pemParser.readObject()) != null) { + listBuilder.add(obj); } + } catch (IOException e) { + throw new RuntimeException("Cannot parse PEM file correctly.", e); } return listBuilder.build(); } - // This binding should not be used directly. Use the supplier binding instead. - @Provides - @PemFile - static PrivateKey providePemPrivateKey(@PemFile ImmutableList pemObjects) { + private static PrivateKey extractPrivateKey(ImmutableList pemObjects) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); Function pkcs1PrivateKeyConverter = pemKeyPair -> { @@ -239,11 +217,8 @@ static PrivateKey providePemPrivateKey(@PemFile ImmutableList pemObjects return privateKeys.get(0); } - // This binding should not be used directly. Use the supplier binding instead. - @Provides - @PemFile - static ImmutableList providePemCertificates( - @PemFile ImmutableList pemObject) { + private static ImmutableList extractCertificates( + ImmutableList pemObjects) { JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC"); Function certificateConverter = certificateHolder -> { @@ -255,7 +230,7 @@ static ImmutableList providePemCertificates( } }; ImmutableList certificates = - filterAndConvert(pemObject, X509CertificateHolder.class, certificateConverter); + filterAndConvert(pemObjects, X509CertificateHolder.class, certificateConverter); checkState(!certificates.isEmpty(), "No certificates found in the pem file"); X509Certificate lastCert = null; for (X509Certificate cert : certificates) { @@ -271,37 +246,20 @@ static ImmutableList providePemCertificates( return certificates; } - @Singleton + // This binding should not be used directly. Use the supplier binding instead. @Provides @PemFile - static Supplier providePemPrivateKeySupplier( - @PemFile Provider privateKeyProvider, - @Named("remoteCertCachingDuration") Duration cachingDuration) { - return memoizeWithExpiration(privateKeyProvider::get, cachingDuration.toSeconds(), SECONDS); + static TlsCredentials providePemTlsCredentials(@Named("pemBytes") byte[] pemBytes) { + ImmutableList pemObjects = parsePemObjects(pemBytes); + return new TlsCredentials(extractPrivateKey(pemObjects), extractCertificates(pemObjects)); } @Singleton @Provides @PemFile - static Supplier> providePemCertificatesSupplier( - @PemFile Provider> certificatesProvider, + static Supplier providePemTlsCredentialsSupplier( + @PemFile Provider tlsCredentialsProvider, @Named("remoteCertCachingDuration") Duration cachingDuration) { - return memoizeWithExpiration(certificatesProvider::get, cachingDuration.toSeconds(), SECONDS); - } - - // TODO(jianglai): Implement P12 supplier or convert the file to PEM format. - @Singleton - @Provides - @P12File - static Supplier provideP12PrivateKeySupplier() { - return Suppliers.ofInstance(null); - } - - // TODO(jianglai): Implement P12 supplier or convert the file to PEM format. - @Singleton - @Provides - @P12File - static Supplier> provideP12CertificatesSupplier() { - return Suppliers.ofInstance(null); + return memoizeWithExpiration(tlsCredentialsProvider::get, cachingDuration); } } diff --git a/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java b/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java index 28b1fbefa3b..299c20e5afb 100644 --- a/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java +++ b/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java @@ -20,6 +20,7 @@ import com.google.common.base.Suppliers; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; +import google.registry.networking.module.CertificateSupplierModule.TlsCredentials; import google.registry.util.SelfSignedCaCertificate; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; @@ -284,8 +285,7 @@ public static SslServerInitializer createSslServerInitial requireClientCert, validateClientCert, sslProvider, - Suppliers.ofInstance(serverKey), - Suppliers.ofInstance(serverCerts), + Suppliers.ofInstance(new TlsCredentials(serverKey, serverCerts)), Optional.of(trustManager)); } diff --git a/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java b/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java index 9b741d30c44..439e0925e80 100644 --- a/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java +++ b/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java @@ -33,14 +33,18 @@ import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusDays; import static google.registry.util.X509Utils.getCertificateHash; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; +import google.registry.networking.module.CertificateSupplierModule.TlsCredentials; import google.registry.testing.FakeClock; import google.registry.util.SelfSignedCaCertificate; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; @@ -54,18 +58,25 @@ import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalServerChannel; import io.netty.handler.ssl.OpenSsl; +import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslProvider; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.nio.channels.ClosedChannelException; import java.security.KeyPair; import java.security.PrivateKey; +import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.time.Instant; import java.util.Collections; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Optional; @@ -73,7 +84,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import java.util.logging.Handler; @@ -85,9 +100,18 @@ import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; +import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -174,8 +198,7 @@ private ChannelHandler getServerHandler( requireClientCert, validateClientCert, sslProvider, - Suppliers.ofInstance(privateKey), - Suppliers.ofInstance(ImmutableList.copyOf(certificates))); + Suppliers.ofInstance(new TlsCredentials(privateKey, ImmutableList.copyOf(certificates)))); } private ChannelHandler getClientHandler( @@ -254,8 +277,7 @@ void testSuccess_swappedInitializerWithSslHandler(SslProvider sslProvider) throw true, false, sslProvider, - Suppliers.ofInstance(ssc.key()), - Suppliers.ofInstance(ImmutableList.of(ssc.cert()))); + Suppliers.ofInstance(new TlsCredentials(ssc.key(), ImmutableList.of(ssc.cert())))); EmbeddedChannel channel = new EmbeddedChannel(); ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(sslServerInitializer); @@ -266,6 +288,164 @@ void testSuccess_swappedInitializerWithSslHandler(SslProvider sslProvider) throw assertThat(channel.isActive()).isTrue(); } + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_cachesSslContextAndRebuildsOnAtomicRotation(SslProvider sslProvider) + throws Exception { + SelfSignedCaCertificate ssc1 = SelfSignedCaCertificate.create(SSL_HOST, new FakeClock()); + SelfSignedCaCertificate ssc2 = SelfSignedCaCertificate.create(SSL_HOST, new FakeClock()); + AtomicReference credentialsRef = + new AtomicReference<>(new TlsCredentials(ssc1.key(), ImmutableList.of(ssc1.cert()))); + SslServerInitializer initializer = + new SslServerInitializer<>(true, false, sslProvider, credentialsRef::get); + + EmbeddedChannel channel1 = new EmbeddedChannel(initializer); + SslContext firstContext = initializer.getOrBuildSslContext(); + EmbeddedChannel channel2 = new EmbeddedChannel(initializer); + SslContext reusedContext = initializer.getOrBuildSslContext(); + assertThat(reusedContext).isSameInstanceAs(firstContext); + + credentialsRef.set(new TlsCredentials(ssc2.key(), ImmutableList.of(ssc2.cert()))); + EmbeddedChannel channel3 = new EmbeddedChannel(initializer); + SslContext rotatedContext = initializer.getOrBuildSslContext(); + assertThat(rotatedContext).isNotSameInstanceAs(firstContext); + assertThat(initializer.getOrBuildSslContext()).isSameInstanceAs(rotatedContext); + + channel1.finishAndReleaseAll(); + channel2.finishAndReleaseAll(); + channel3.finishAndReleaseAll(); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_reusesCachedSslContextForReparsedIdenticalPem(SslProvider sslProvider) + throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + SelfSignedCaCertificate caSsc = SelfSignedCaCertificate.create(new FakeClock()); + KeyPair keyPair = getKeyPair(); + X509Certificate serverCert = signKeyPair(caSsc, keyPair, SSL_HOST); + byte[] pemBytes = encodePem(serverCert, caSsc.cert(), keyPair.getPrivate()); + + TlsCredentials firstCredentials = parsePemCredentials(pemBytes); + TlsCredentials secondCredentials = parsePemCredentials(pemBytes); + assertThat(firstCredentials).isNotSameInstanceAs(secondCredentials); + assertThat(firstCredentials.privateKey()).isNotSameInstanceAs(secondCredentials.privateKey()); + assertThat(firstCredentials.certificates().get(0)) + .isNotSameInstanceAs(secondCredentials.certificates().get(0)); + assertThat(firstCredentials).isEqualTo(secondCredentials); + + AtomicReference credentialsRef = new AtomicReference<>(firstCredentials); + SslServerInitializer initializer = + new SslServerInitializer<>(true, false, sslProvider, credentialsRef::get); + + SslContext firstContext = initializer.getOrBuildSslContext(); + credentialsRef.set(secondCredentials); + SslContext secondContext = initializer.getOrBuildSslContext(); + assertThat(secondContext).isSameInstanceAs(firstContext); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_staleCredentialReadDoesNotOverwriteRotatedSslContext(SslProvider sslProvider) + throws Exception { + SelfSignedCaCertificate ssc1 = SelfSignedCaCertificate.create(SSL_HOST, new FakeClock()); + SelfSignedCaCertificate ssc2 = SelfSignedCaCertificate.create(SSL_HOST, new FakeClock()); + TlsCredentials credsV1 = new TlsCredentials(ssc1.key(), ImmutableList.of(ssc1.cert())); + TlsCredentials credsV2 = new TlsCredentials(ssc2.key(), ImmutableList.of(ssc2.cert())); + + CountDownLatch threadBInsideLock = new CountDownLatch(1); + CountDownLatch threadAReadStaleV1 = new CountDownLatch(1); + AtomicReference threadBRef = new AtomicReference<>(); + AtomicInteger threadBCalls = new AtomicInteger(); + AtomicInteger threadACalls = new AtomicInteger(); + + SslServerInitializer initializer = + new SslServerInitializer<>( + true, + false, + sslProvider, + () -> { + if (Thread.currentThread() == threadBRef.get()) { + if (threadBCalls.incrementAndGet() == 2) { + // Thread B now holds synchronized (this); let Thread A read stale V1 outside + // the monitor and block waiting to enter synchronized (this). + threadBInsideLock.countDown(); + try { + if (!threadAReadStaleV1.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for Thread A fast read"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted waiting for Thread A", e); + } + } + return credsV2; + } + if (threadACalls.getAndIncrement() == 0) { + // Thread A reads stale V1 before entering synchronized (this). + threadAReadStaleV1.countDown(); + return credsV1; + } + // Thread A re-reads inside synchronized (this) and observes rotated V2. + return credsV2; + }); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future futureB = + executor.submit( + () -> { + threadBRef.set(Thread.currentThread()); + return initializer.getOrBuildSslContext(); + }); + assertThat(threadBInsideLock.await(5, TimeUnit.SECONDS)).isTrue(); + + Future futureA = executor.submit(initializer::getOrBuildSslContext); + + SslContext contextB = futureB.get(10, TimeUnit.SECONDS); + SslContext contextA = futureA.get(10, TimeUnit.SECONDS); + assertThat(contextA).isSameInstanceAs(contextB); + assertThat(initializer.getOrBuildSslContext()).isSameInstanceAs(contextB); + } finally { + executor.shutdownNow(); + } + } + + private static byte[] encodePem(Object... objects) throws Exception { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JcaPEMWriter pemWriter = new JcaPEMWriter(new OutputStreamWriter(outputStream, UTF_8))) { + for (Object object : objects) { + pemWriter.writeObject(object); + } + } + return outputStream.toByteArray(); + } + + private static TlsCredentials parsePemCredentials(byte[] pemBytes) throws Exception { + JcaPEMKeyConverter keyConverter = + new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME); + JcaX509CertificateConverter certConverter = + new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME); + PrivateKey privateKey = null; + ImmutableList.Builder certs = ImmutableList.builder(); + try (PEMParser pemParser = + new PEMParser(new InputStreamReader(new ByteArrayInputStream(pemBytes), UTF_8))) { + Object obj; + while ((obj = pemParser.readObject()) != null) { + if (obj instanceof PEMKeyPair keyPair) { + privateKey = keyConverter.getKeyPair(keyPair).getPrivate(); + } else if (obj instanceof PrivateKeyInfo keyInfo) { + privateKey = keyConverter.getPrivateKey(keyInfo); + } else if (obj instanceof X509CertificateHolder certHolder) { + certs.add(certConverter.getCertificate(certHolder)); + } + } + } + return new TlsCredentials(privateKey, certs.build()); + } + @ParameterizedTest @MethodSource("provideTestCombinations") void testSuccess_trustAnyClientCert(SslProvider sslProvider) throws Exception { @@ -332,8 +512,8 @@ void testSuccess_someCiphersNotAccepted(SslProvider sslProvider) throws Exceptio true, true, sslProvider, - Suppliers.ofInstance(serverSsc.key()), - Suppliers.ofInstance(ImmutableList.of(serverSsc.cert())))); + Suppliers.ofInstance( + new TlsCredentials(serverSsc.key(), ImmutableList.of(serverSsc.cert()))))); SelfSignedCaCertificate clientSsc = SelfSignedCaCertificate.create( "CLIENT", minusDays(Instant.now(), 2), plusDays(Instant.now(), 1)); @@ -407,6 +587,16 @@ void testFailure_clientCertExpired(SslProvider sslProvider) throws Exception { nettyExtension.getServerChannel(), channel -> channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get(), CertificateExpiredException.class); + // Even rejected handshakes must invalidate the server-side session so it cannot be resumed. + assertThat( + nettyExtension + .getServerChannel() + .pipeline() + .get(SslHandler.class) + .engine() + .getSession() + .isValid()) + .isFalse(); } @ParameterizedTest @@ -558,8 +748,9 @@ private Channel connectMutualTls( true, validateClientCert, sslProvider, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), trustManager), null, clientKey, @@ -657,8 +848,9 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { true, true, sslProvider, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), Optional.of(sharedTrustManager)), promiseObserver, sharedClientKeyPair.getPrivate(), @@ -736,8 +928,9 @@ void testSuccess_clientCertThreeTierChain_tls12(SslProvider sslProvider) throws true, true, sslProvider, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), Optional.of(sharedTrustManager))); nettyExtension.setUpClient( localAddress, @@ -846,8 +1039,9 @@ public void close() {} true, true, sslProvider, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), Optional.of(sharedTrustManager)), promiseCanceler); nettyExtension.setUpClient( @@ -895,8 +1089,9 @@ record ObservedClient(boolean chainValidated, ImmutableList hostnames) { true, true, sslProvider, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), Optional.of(sharedTrustManager)); Map observedByHash = new ConcurrentHashMap<>(); @@ -1029,7 +1224,7 @@ void testSuccess_missingIntermediateCa_chainValidatedFalseAndEmptyHostnames( @MethodSource("provideTestCombinations") void testSuccess_untrustedClientCert_stillSucceedsHandshakeWithEmptyHostnames( SslProvider sslProvider) throws Exception { - // Use the public 5-arg constructor (default JVM truststore) with an untrusted non-CA leaf so + // Use the public 4-arg constructor (default JVM truststore) with an untrusted non-CA leaf so // handshake stays open for legacy fingerprint-pinned certs while chain validation fails. X509Certificate untrustedLeafCert = signKeyPairWithSans( @@ -1046,8 +1241,9 @@ void testSuccess_untrustedClientCert_stillSucceedsHandshakeWithEmptyHostnames( true, true, sslProvider, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert()))), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert())))), null, sharedClientKeyPair.getPrivate(), untrustedLeafCert); @@ -1136,8 +1332,9 @@ void testFailure_expiredTrustedClientCertWhenValidationEnabled_doesNotSetChainAt true, true, sslProvider, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), Optional.of(sharedTrustManager))); nettyExtension.setUpClient( localAddress, @@ -1230,8 +1427,9 @@ void testFailure_validateClientCertWithoutRequireClientCert_throws() { false, true, SslProvider.JDK, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())))); + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))))); } @Test @@ -1243,8 +1441,9 @@ void testFailure_missingTrustManagerWhenClientCertRequired_throws() { true, false, SslProvider.JDK, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), null)); assertThrows( IllegalArgumentException.class, @@ -1253,11 +1452,241 @@ void testFailure_missingTrustManagerWhenClientCertRequired_throws() { true, false, SslProvider.JDK, - Suppliers.ofInstance(sharedServerSsc.key()), - Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), Optional.empty())); } + @SuppressWarnings("unused") + static Stream provideTestCombinationsWithProtocols() { + Stream.Builder args = Stream.builder(); + for (String protocol : ImmutableList.of("TLSv1.2", "TLSv1.3")) { + args.add(Arguments.of(SslProvider.JDK, protocol)); + if (OpenSsl.isAvailable()) { + args.add(Arguments.of(SslProvider.OPENSSL, protocol)); + } + } + return args.build(); + } + + @ParameterizedTest + @MethodSource("provideTestCombinationsWithProtocols") + void testSuccess_cachedSslContext_twoConnectionsThreeTierChainPreservesIntermediates( + SslProvider sslProvider, String protocol) throws Exception { + X509Certificate threeTierLeaf = + signKeyPair( + sharedIntermediateKeyPair.getPrivate(), + sharedIntermediateCa, + sharedClientKeyPair, + "ignored.cn.example", + LONG_VALID_FROM, + LONG_VALID_TO, + "epp.resumption.example"); + + SslServerInitializer sharedServerInitializer = + new SslServerInitializer<>( + true, + true, + sslProvider, + Suppliers.ofInstance( + new TlsCredentials( + sharedServerSsc.key(), ImmutableList.of(sharedServerSsc.cert()))), + Optional.of(sharedTrustManager)); + + AtomicInteger serverCertVerifications = new AtomicInteger(); + X509TrustManager baseServerTrustManager = createTrustManager(sharedServerSsc.cert()); + X509TrustManager countingServerTrustManager = + new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + baseServerTrustManager.checkClientTrusted(chain, authType); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + serverCertVerifications.incrementAndGet(); + baseServerTrustManager.checkServerTrusted(chain, authType); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return baseServerTrustManager.getAcceptedIssuers(); + } + }; + + // Share one JDK client SslContext across both connections so the client actively attempts both + // RFC 5077 TLS 1.2 session tickets and TLS 1.3 PSKs against both JDK and OPENSSL servers. + SslContext sharedClientSslContext = + SslContextBuilder.forClient() + .trustManager(countingServerTrustManager) + .keyManager(sharedClientKeyPair.getPrivate(), threeTierLeaf, sharedIntermediateCa) + .sslProvider(SslProvider.JDK) + .protocols(protocol) + .build(); + + record ObservedConnection( + boolean chainValidated, + ImmutableList hostnames, + int peerCertCount, + String sessionIdHex) {} + + List> observedConnections = + ImmutableList.of(new CompletableFuture<>(), new CompletableFuture<>()); + AtomicInteger connectionIndex = new AtomicInteger(); + LocalAddress localAddress = + new LocalAddress("SESSION_RESUMPTION_3TIER_" + sslProvider + "_" + protocol); + EventLoopGroup eventLoopGroup = new DefaultEventLoopGroup(2); + Channel serverChannel = null; + try { + serverChannel = + new ServerBootstrap() + .group(eventLoopGroup) + .channel(LocalServerChannel.class) + .childHandler( + new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) { + int idx = connectionIndex.getAndIncrement(); + ch.pipeline() + .addLast(sharedServerInitializer) + .addLast( + new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(ChannelHandlerContext ctx) + throws Exception { + ch.attr(CLIENT_CERTIFICATE_PROMISE_KEY) + .get() + .addListener( + future -> { + if (future.isSuccess()) { + try { + SSLSession session = + ch.pipeline() + .get(SslHandler.class) + .engine() + .getSession(); + boolean validated = + ch.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY) + .get(); + ImmutableList hosts = + ch.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get(); + String sessionId = + HexFormat.of().formatHex(session.getId()); + observedConnections + .get(idx) + .complete( + new ObservedConnection( + validated, + hosts, + session.getPeerCertificates().length, + sessionId)); + } catch (SSLPeerUnverifiedException + | RuntimeException e) { + observedConnections + .get(idx) + .completeExceptionally(e); + } + } else { + observedConnections + .get(idx) + .completeExceptionally(future.cause()); + } + }); + super.channelActive(ctx); + } + + @Override + @SuppressWarnings("FutureReturnValueIgnored") + public void channelRead(ChannelHandlerContext ctx, Object msg) { + // Echo application data so TLS 1.3 NewSessionTicket records + // sent after Finished are flushed and processed by the client + // before connection #1 closes. + ctx.writeAndFlush(msg); + } + }); + } + }) + .bind(localAddress) + .syncUninterruptibly() + .channel(); + + for (int i = 0; i < 2; i++) { + CountDownLatch echoReceived = new CountDownLatch(1); + Channel clientChannel = + new Bootstrap() + .group(eventLoopGroup) + .channel(LocalChannel.class) + .handler( + new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) { + SslHandler sslHandler = + sharedClientSslContext.newHandler(ch.alloc(), SSL_HOST, SSL_PORT); + SSLEngine sslEngine = sslHandler.engine(); + SSLParameters sslParameters = sslEngine.getSSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + sslEngine.setSSLParameters(sslParameters); + ch.pipeline() + .addLast(sslHandler) + .addLast( + new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ByteBuf buf = (ByteBuf) msg; + try { + if ("ping".equals(buf.toString(UTF_8))) { + echoReceived.countDown(); + } + } finally { + buf.release(); + } + } + }); + } + }) + .connect(localAddress) + .syncUninterruptibly() + .channel(); + try { + clientChannel + .pipeline() + .get(SslHandler.class) + .handshakeFuture() + .get(10, TimeUnit.SECONDS); + clientChannel + .writeAndFlush(Unpooled.wrappedBuffer("ping".getBytes(UTF_8))) + .syncUninterruptibly(); + assertThat(echoReceived.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + clientChannel.close().syncUninterruptibly(); + } + } + + ObservedConnection first = observedConnections.get(0).get(10, TimeUnit.SECONDS); + ObservedConnection second = observedConnections.get(1).get(10, TimeUnit.SECONDS); + assertThat(first.chainValidated()).isTrue(); + assertThat(first.hostnames()).containsExactly("epp.resumption.example"); + assertThat(first.peerCertCount()).isEqualTo(2); + assertThat(second.chainValidated()).isTrue(); + assertThat(second.hostnames()).containsExactly("epp.resumption.example"); + assertThat(second.peerCertCount()).isEqualTo(2); + if (!first.sessionIdHex().isEmpty() && !second.sessionIdHex().isEmpty()) { + assertThat(second.sessionIdHex()).isNotEqualTo(first.sessionIdHex()); + } + // Every connection must perform a full handshake (verifying the server cert twice) rather + // than resuming via session ID or stateless NewSessionTicket. + assertThat(serverCertVerifications.get()).isEqualTo(2); + } finally { + if (serverChannel != null) { + serverChannel.close().syncUninterruptibly(); + } + eventLoopGroup.shutdownGracefully().syncUninterruptibly(); + } + } + @Test void testFormatHostnamesForLog_boundsOutput() { assertThrows(NullPointerException.class, () -> formatHostnamesForLog(null)); diff --git a/networking/src/test/java/google/registry/networking/module/CertificateSupplierModuleTest.java b/networking/src/test/java/google/registry/networking/module/CertificateSupplierModuleTest.java index 13acae86ac3..1338fdc4e4b 100644 --- a/networking/src/test/java/google/registry/networking/module/CertificateSupplierModuleTest.java +++ b/networking/src/test/java/google/registry/networking/module/CertificateSupplierModuleTest.java @@ -20,12 +20,12 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertThrows; -import com.google.common.collect.ImmutableList; import dagger.BindsInstance; import dagger.Component; import dagger.Module; import dagger.Provides; import google.registry.networking.module.CertificateSupplierModule.Mode; +import google.registry.networking.module.CertificateSupplierModule.TlsCredentials; import google.registry.testing.FakeClock; import google.registry.util.Clock; import google.registry.util.SelfSignedCaCertificate; @@ -38,6 +38,7 @@ import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.junit.jupiter.api.BeforeEach; @@ -59,6 +60,17 @@ private static TestComponent createComponentForPem(Object... objects) throws Exc .build(); } + private static byte[] encodePem(Object... objects) throws Exception { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + try (JcaPEMWriter pemWriter = + new JcaPEMWriter(new OutputStreamWriter(byteArrayOutputStream, UTF_8))) { + for (Object object : objects) { + pemWriter.writeObject(object); + } + } + return byteArrayOutputStream.toByteArray(); + } + @BeforeEach void beforeEach() throws Exception { ssc = SelfSignedCaCertificate.create(new FakeClock()); @@ -70,15 +82,104 @@ void beforeEach() throws Exception { @Test void testSuccess() throws Exception { component = createComponentForPem(cert, ssc.cert(), key); - assertThat(component.privateKeySupplier().get()).isEqualTo(key); - assertThat(component.certificatesSupplier().get()).containsExactly(cert, ssc.cert()).inOrder(); + TlsCredentials credentials = component.tlsCredentialsSupplier().get(); + assertThat(credentials.privateKey()).isEqualTo(key); + assertThat(credentials.certificates()).containsExactly(cert, ssc.cert()).inOrder(); } @Test void testSuccess_certificateChainNotContinuous() throws Exception { component = createComponentForPem(cert, key, ssc.cert()); - assertThat(component.privateKeySupplier().get()).isEqualTo(key); - assertThat(component.certificatesSupplier().get()).containsExactly(cert, ssc.cert()).inOrder(); + TlsCredentials credentials = component.tlsCredentialsSupplier().get(); + assertThat(credentials.privateKey()).isEqualTo(key); + assertThat(credentials.certificates()).containsExactly(cert, ssc.cert()).inOrder(); + } + + @Test + void testSuccess_selfSignedMode() throws Exception { + component = + DaggerCertificateSupplierModuleTest_TestComponent.builder() + .certificateModule(CertificateModule.createCertificateModuleForPem()) + .useMode(Mode.SELF_SIGNED) + .build(); + TlsCredentials credentials = component.tlsCredentialsSupplier().get(); + assertThat(credentials.privateKey()).isNotNull(); + assertThat(credentials.certificates()).hasSize(1); + } + + @Test + void testFailure_p12ModeUnsupported() throws Exception { + component = + DaggerCertificateSupplierModuleTest_TestComponent.builder() + .certificateModule( + CertificateModule.createCertificateModuleForPem(cert, ssc.cert(), key)) + .useMode(Mode.P12_FILE) + .build(); + UnsupportedOperationException thrown = + assertThrows(UnsupportedOperationException.class, () -> component.tlsCredentialsSupplier()); + assertThat(thrown).hasMessageThat().contains("P12_FILE"); + } + + @Test + void testSuccess_singleFetchCachesAtomically() throws Exception { + KeyPair rotatedKeyPair = getKeyPair(); + PrivateKey rotatedKey = rotatedKeyPair.getPrivate(); + X509Certificate rotatedCert = signKeyPair(ssc, rotatedKeyPair, "rotated.tld"); + + byte[] firstPem = encodePem(cert, ssc.cert(), key); + byte[] secondPem = encodePem(rotatedCert, ssc.cert(), rotatedKey); + AtomicInteger fetchCount = new AtomicInteger(); + + component = + DaggerCertificateSupplierModuleTest_TestComponent.builder() + .certificateModule( + new CertificateModule( + () -> fetchCount.getAndIncrement() == 0 ? firstPem : secondPem, + Duration.ofDays(1))) + .useMode(Mode.PEM_FILE) + .build(); + + TlsCredentials first = component.tlsCredentialsSupplier().get(); + TlsCredentials second = component.tlsCredentialsSupplier().get(); + assertThat(fetchCount.get()).isEqualTo(1); + assertThat(first).isSameInstanceAs(second); + assertThat(first.privateKey()).isEqualTo(key); + assertThat(first.certificates()).containsExactly(cert, ssc.cert()).inOrder(); + } + + @Test + void testSuccess_atomicRotationAfterExpiration() throws Exception { + KeyPair rotatedKeyPair = getKeyPair(); + PrivateKey rotatedKey = rotatedKeyPair.getPrivate(); + X509Certificate rotatedCert = signKeyPair(ssc, rotatedKeyPair, "rotated.tld"); + + byte[] firstPem = encodePem(cert, ssc.cert(), key); + byte[] secondPem = encodePem(rotatedCert, ssc.cert(), rotatedKey); + AtomicInteger fetchCount = new AtomicInteger(); + + component = + DaggerCertificateSupplierModuleTest_TestComponent.builder() + .certificateModule( + new CertificateModule( + () -> fetchCount.getAndIncrement() == 0 ? firstPem : secondPem, + Duration.ofNanos(1))) + .useMode(Mode.PEM_FILE) + .build(); + + Supplier supplier = component.tlsCredentialsSupplier(); + TlsCredentials first = supplier.get(); + assertThat(first.privateKey()).isEqualTo(key); + assertThat(first.certificates()).containsExactly(cert, ssc.cert()).inOrder(); + + long before = System.nanoTime(); + while (System.nanoTime() - before <= 1L) { + // Spin briefly until the 1ns expiration window elapses without sleeping. + } + + TlsCredentials rotated = supplier.get(); + assertThat(fetchCount.get()).isEqualTo(2); + assertThat(rotated.privateKey()).isEqualTo(rotatedKey); + assertThat(rotated.certificates()).containsExactly(rotatedCert, ssc.cert()).inOrder(); } @Test @@ -86,7 +187,7 @@ void testSuccess_certificateChainNotContinuous() throws Exception { void testFailure_noPrivateKey() throws Exception { component = createComponentForPem(cert, ssc.cert()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> component.privateKeySupplier().get()); + assertThrows(IllegalStateException.class, () -> component.tlsCredentialsSupplier().get()); assertThat(thrown).hasMessageThat().contains("0 keys are found"); } @@ -95,7 +196,7 @@ void testFailure_noPrivateKey() throws Exception { void testFailure_twoPrivateKeys() throws Exception { component = createComponentForPem(cert, ssc.cert(), key, ssc.key()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> component.privateKeySupplier().get()); + assertThrows(IllegalStateException.class, () -> component.tlsCredentialsSupplier().get()); assertThat(thrown).hasMessageThat().contains("2 keys are found"); } @@ -104,7 +205,7 @@ void testFailure_twoPrivateKeys() throws Exception { void testFailure_certificatesOutOfOrder() throws Exception { component = createComponentForPem(ssc.cert(), cert, key); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> component.certificatesSupplier().get()); + assertThrows(IllegalStateException.class, () -> component.tlsCredentialsSupplier().get()); assertThat(thrown).hasMessageThat().contains("is not signed by"); } @@ -113,41 +214,36 @@ void testFailure_certificatesOutOfOrder() throws Exception { void testFailure_noCertificates() throws Exception { component = createComponentForPem(key); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> component.certificatesSupplier().get()); + assertThrows(IllegalStateException.class, () -> component.tlsCredentialsSupplier().get()); assertThat(thrown).hasMessageThat().contains("No certificates"); } @Module static class CertificateModule { - private final byte[] pemBytes; + private final Supplier pemBytesSupplier; + private final Duration cachingDuration; - private CertificateModule(byte[] pemBytes) { - this.pemBytes = pemBytes.clone(); + private CertificateModule(Supplier pemBytesSupplier, Duration cachingDuration) { + this.pemBytesSupplier = pemBytesSupplier; + this.cachingDuration = cachingDuration; } static CertificateModule createCertificateModuleForPem(Object... objects) throws Exception { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - try (JcaPEMWriter pemWriter = - new JcaPEMWriter(new OutputStreamWriter(byteArrayOutputStream, UTF_8))) { - for (Object object : objects) { - pemWriter.writeObject(object); - } - } - return new CertificateModule(byteArrayOutputStream.toByteArray()); + byte[] encoded = encodePem(objects); + return new CertificateModule(encoded::clone, Duration.ofDays(1)); } @Provides @Named("pemBytes") byte[] providePemBytes() { - return pemBytes.clone(); + return pemBytesSupplier.get().clone(); } @Provides @Named("remoteCertCachingDuration") Duration provideCachingDuration() { - // Make the supplier always return the save value for test to save time. - return Duration.ofDays(1); + return cachingDuration; } @Provides @@ -157,19 +253,16 @@ Clock provideClock() { } /** - * Test component that exposes the certificates and private key. + * Test component that exposes the atomic TLS credentials supplier. * *

Depending on what {@link Mode} is provided to the component, it will return certificates and - * private key extracted from the correspondonig format. Self-signed mode is not tested as they - * are only used in tests. + * private key extracted from the corresponding format. */ @Singleton @Component(modules = {CertificateSupplierModule.class, CertificateModule.class}) interface TestComponent { - Supplier privateKeySupplier(); - - Supplier> certificatesSupplier(); + Supplier tlsCredentialsSupplier(); @Component.Builder interface Builder { diff --git a/proxy/Dockerfile b/proxy/Dockerfile index b31e2d0c7ab..6ee632426c3 100644 --- a/proxy/Dockerfile +++ b/proxy/Dockerfile @@ -1,6 +1,7 @@ FROM eclipse-temurin:25 ADD build/libs/proxy_server.jar . # Disable C2 Base64 SIMD intrinsics as defense-in-depth for CVE-2026-114938 -# (JDK-8393212). -ENTRYPOINT ["java", "-XX:-UseBASE64Intrinsics", "-jar", "proxy_server.jar"] +# (JDK-8393212), and disable server-side TLS session tickets so cached mTLS +# SslContexts never resume without full client certificate chains. +ENTRYPOINT ["java", "-XX:-UseBASE64Intrinsics", "-Djdk.tls.server.enableSessionTicketExtension=false", "-jar", "proxy_server.jar"] EXPOSE 30000 30002 30012 diff --git a/proxy/kubernetes/proxy-deployment-alpha.yaml b/proxy/kubernetes/proxy-deployment-alpha.yaml index 06b3a473c06..fd00be22317 100644 --- a/proxy/kubernetes/proxy-deployment-alpha.yaml +++ b/proxy/kubernetes/proxy-deployment-alpha.yaml @@ -46,7 +46,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-crash-canary.yaml b/proxy/kubernetes/proxy-deployment-crash-canary.yaml index 06622266ed5..f6963b20629 100644 --- a/proxy/kubernetes/proxy-deployment-crash-canary.yaml +++ b/proxy/kubernetes/proxy-deployment-crash-canary.yaml @@ -46,7 +46,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy-canary - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-crash.yaml b/proxy/kubernetes/proxy-deployment-crash.yaml index cd419a84e27..dd0ab30c1ae 100644 --- a/proxy/kubernetes/proxy-deployment-crash.yaml +++ b/proxy/kubernetes/proxy-deployment-crash.yaml @@ -46,7 +46,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-production-canary.yaml b/proxy/kubernetes/proxy-deployment-production-canary.yaml index 3364c746837..518a7c6a9c0 100644 --- a/proxy/kubernetes/proxy-deployment-production-canary.yaml +++ b/proxy/kubernetes/proxy-deployment-production-canary.yaml @@ -53,7 +53,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy-canary - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-production.yaml b/proxy/kubernetes/proxy-deployment-production.yaml index 1c05986ec0f..acd4118edf4 100644 --- a/proxy/kubernetes/proxy-deployment-production.yaml +++ b/proxy/kubernetes/proxy-deployment-production.yaml @@ -53,7 +53,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-qa-canary.yaml b/proxy/kubernetes/proxy-deployment-qa-canary.yaml index 0806afe597d..89a23790cd8 100644 --- a/proxy/kubernetes/proxy-deployment-qa-canary.yaml +++ b/proxy/kubernetes/proxy-deployment-qa-canary.yaml @@ -46,7 +46,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy-canary - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-qa.yaml b/proxy/kubernetes/proxy-deployment-qa.yaml index 1fc27c992d8..e5268c3d55b 100644 --- a/proxy/kubernetes/proxy-deployment-qa.yaml +++ b/proxy/kubernetes/proxy-deployment-qa.yaml @@ -46,7 +46,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-sandbox-canary.yaml b/proxy/kubernetes/proxy-deployment-sandbox-canary.yaml index dfc4dbc1f45..dd47fb0594e 100644 --- a/proxy/kubernetes/proxy-deployment-sandbox-canary.yaml +++ b/proxy/kubernetes/proxy-deployment-sandbox-canary.yaml @@ -53,7 +53,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy-canary - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/kubernetes/proxy-deployment-sandbox.yaml b/proxy/kubernetes/proxy-deployment-sandbox.yaml index 51051add290..6cc0362e5ed 100644 --- a/proxy/kubernetes/proxy-deployment-sandbox.yaml +++ b/proxy/kubernetes/proxy-deployment-sandbox.yaml @@ -53,7 +53,11 @@ spec: fieldPath: metadata.namespace - name: CONTAINER_NAME value: proxy - # TODO(b/587369531): Remove once all rollback-eligible images disable - # Base64 intrinsics or bundle a patched JDK 25. + # TODO(b/587369531): Remove -XX:-UseBASE64Intrinsics once all + # rollback-eligible images disable Base64 intrinsics or bundle a + # patched JDK 25. + # Keep -Djdk.tls.server.enableSessionTicketExtension=false (also set in + # proxy/Dockerfile) to disable mTLS TLS session tickets for cached + # SslContexts. - name: JDK_JAVA_OPTIONS - value: "-XX:-UseBASE64Intrinsics" + value: "-XX:-UseBASE64Intrinsics -Djdk.tls.server.enableSessionTicketExtension=false" diff --git a/proxy/src/main/java/google/registry/proxy/EppProtocolModule.java b/proxy/src/main/java/google/registry/proxy/EppProtocolModule.java index f3aa4575272..ae2ca2dd2b4 100644 --- a/proxy/src/main/java/google/registry/proxy/EppProtocolModule.java +++ b/proxy/src/main/java/google/registry/proxy/EppProtocolModule.java @@ -21,6 +21,7 @@ import dagger.Provides; import dagger.multibindings.IntoSet; import google.registry.networking.handler.SslServerInitializer; +import google.registry.networking.module.CertificateSupplierModule.TlsCredentials; import google.registry.proxy.HttpsRelayProtocolModule.HttpsRelayProtocol; import google.registry.proxy.Protocol.BackendProtocol; import google.registry.proxy.Protocol.FrontendProtocol; @@ -45,8 +46,6 @@ import jakarta.inject.Qualifier; import jakarta.inject.Singleton; import java.io.IOException; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Supplier; @@ -168,11 +167,8 @@ static EppServiceHandler provideEppServiceHandler( @Provides @EppProtocol static SslServerInitializer provideSslServerInitializer( - SslProvider sslProvider, - Supplier privateKeySupplier, - Supplier> certificatesSupplier) { - return new SslServerInitializer<>( - true, false, sslProvider, privateKeySupplier, certificatesSupplier); + SslProvider sslProvider, Supplier tlsCredentialsSupplier) { + return new SslServerInitializer<>(true, false, sslProvider, tlsCredentialsSupplier); } @Provides diff --git a/proxy/src/main/java/google/registry/proxy/handler/ProxyProtocolHandler.java b/proxy/src/main/java/google/registry/proxy/handler/ProxyProtocolHandler.java index 6a314abdb63..4d25aa9ec87 100644 --- a/proxy/src/main/java/google/registry/proxy/handler/ProxyProtocolHandler.java +++ b/proxy/src/main/java/google/registry/proxy/handler/ProxyProtocolHandler.java @@ -21,6 +21,7 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.codec.TooLongFrameException; import io.netty.util.AttributeKey; import jakarta.inject.Inject; import java.net.InetSocketAddress; @@ -56,13 +57,25 @@ public class ProxyProtocolHandler extends ByteToMessageDecoder { public static final AttributeKey REMOTE_ADDRESS_KEY = AttributeKey.valueOf("REMOTE_ADDRESS_KEY"); + /** + * Maximum PROXY protocol v1 header length in bytes including trailing CRLF (HAProxy PROXY + * protocol v1 specification section 2.1). + */ + static final int MAX_PROXY_HEADER_LENGTH = 107; + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // The proxy header must start with this prefix. // Sample header: "PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\n". private static final byte[] HEADER_PREFIX = "PROXY".getBytes(US_ASCII); - private boolean finished = false; + private enum DecodeState { + READING, + FINISHED, + FAILED + } + + private DecodeState decodeState = DecodeState.READING; private String proxyHeader = null; @Inject @@ -71,7 +84,7 @@ public class ProxyProtocolHandler extends ByteToMessageDecoder { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { super.channelRead(ctx, msg); - if (finished) { + if (decodeState == DecodeState.FINISHED) { String remoteIP; if (proxyHeader != null) { logger.atFine().log("PROXIED CONNECTION: %s", ctx.channel()); @@ -122,18 +135,27 @@ private static String getSourceIP(ChannelHandlerContext ctx) { /** * Attempts to decode an internally accumulated buffer and find the proxy protocol header. * - *

When the connection is not proxied (i. e. the initial bytes are not "PROXY"), simply set - * {@link #finished} to true and allow the handler to be removed. Otherwise the handler waits - * until there's enough bytes to parse the header, save the parsed header to {@link #proxyHeader}, - * and then mark {@link #finished}. + *

When the connection is not proxied (i. e. the initial bytes are not "PROXY"), simply mark + * {@link DecodeState#FINISHED} and allow the handler to be removed. Otherwise the handler waits + * until there are enough bytes to parse the header (up to {@link #MAX_PROXY_HEADER_LENGTH} bytes + * including CRLF), saves the parsed header to {@link #proxyHeader}, and marks {@link + * DecodeState#FINISHED}. If no CRLF is seen within {@link #MAX_PROXY_HEADER_LENGTH} bytes, the + * connection is closed immediately to prevent unbounded buffer growth. * * @param in internally accumulated buffer, newly arrived bytes are appended to it. * @param out objects passed to the next handler, in this case nothing is ever passed because the * header itself is processed and written to the attribute of the proxy, and the handler is * then removed from the pipeline. */ + @SuppressWarnings("FutureReturnValueIgnored") @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { + if (decodeState != DecodeState.READING) { + if (decodeState == DecodeState.FAILED) { + in.skipBytes(in.readableBytes()); + } + return; + } // Wait until there are more bytes available than the header's length before processing. if (in.readableBytes() >= HEADER_PREFIX.length) { if (containsHeader(in)) { @@ -142,42 +164,53 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { // to be SSL enabled. So the beginning of the inbound message upon connection can only be // either the proxy header (when proxied), or SSL handshake request (when not proxied), // which does not start with "PROXY". Therefore it is safe to assume that if the beginning - // of the message contains "PROXY", it must be proxied, and must contain \r\n. + // of the message contains "PROXY", it must be proxied, and must contain \r\n within + // MAX_PROXY_HEADER_LENGTH bytes. int eol = findEndOfLine(in); - // If eol is not found, that is because that we do not yet have enough inbound message, do - // nothing and wait for more bytes to be readable. eol will eventually be positive because - // of the reasoning above: The connection starts with "PROXY", so it must be a proxied - // connection and contain \r\n. if (eol >= 0) { // ByteBuf.readBytes is called so that the header is processed and not passed to handlers // further in the pipeline. - byte[] headerBytes = new byte[eol]; + int headerLength = eol - in.readerIndex(); + byte[] headerBytes = new byte[headerLength]; in.readBytes(headerBytes); proxyHeader = new String(headerBytes, US_ASCII); // Skip \r\n. in.skipBytes(2); // Proxy header processed, mark finished so that this handler is removed. - finished = true; + decodeState = DecodeState.FINISHED; + } else if (in.readableBytes() >= MAX_PROXY_HEADER_LENGTH) { + decodeState = DecodeState.FAILED; + in.skipBytes(in.readableBytes()); + logger.atWarning().log( + "PROXY protocol v1 header exceeded %d bytes without CRLF for channel %s, closing", + MAX_PROXY_HEADER_LENGTH, ctx.channel()); + ctx.close(); + throw new TooLongFrameException( + String.format( + "PROXY protocol v1 header exceeded maximum length of %d bytes", + MAX_PROXY_HEADER_LENGTH)); } } else { // The inbound message does not contain a proxy header, mark finished so that this handler // is removed. Note that no inbound bytes are actually processed by this handler because we // did not call ByteBuf.readBytes(), but ByteBuf.getByte(), which does not change reader // index of the ByteBuf. So any inbound byte is then passed to the next handler to process. - finished = true; + decodeState = DecodeState.FINISHED; } } } /** - * Returns the index in the buffer of the end of line found. Returns -1 if no end of line was - * found in the buffer. + * Returns the index in the buffer of the end of line found within {@link + * #MAX_PROXY_HEADER_LENGTH} bytes of {@code buffer.readerIndex()}. Returns -1 if no end of line + * was found within that limit. */ private static int findEndOfLine(final ByteBuf buffer) { - final int n = buffer.writerIndex(); - for (int i = buffer.readerIndex(); i < n; i++) { - final byte b = buffer.getByte(i); - if (b == '\r' && i < n - 1 && buffer.getByte(i + 1) == '\n') { + final int readerIndex = buffer.readerIndex(); + final int maxSearchEnd = + readerIndex + Math.min(buffer.readableBytes(), MAX_PROXY_HEADER_LENGTH); + for (int i = readerIndex; i < maxSearchEnd - 1; i++) { + if (buffer.getByte(i) == '\r' && buffer.getByte(i + 1) == '\n') { return i; // \r\n } } diff --git a/proxy/src/main/java/google/registry/proxy/handler/QuotaHandler.java b/proxy/src/main/java/google/registry/proxy/handler/QuotaHandler.java index 014ff8a5a53..94d50010414 100644 --- a/proxy/src/main/java/google/registry/proxy/handler/QuotaHandler.java +++ b/proxy/src/main/java/google/registry/proxy/handler/QuotaHandler.java @@ -18,6 +18,7 @@ import static google.registry.proxy.Protocol.PROTOCOL_KEY; import static google.registry.proxy.handler.EppServiceHandler.CLIENT_CERTIFICATE_HASH_KEY; +import com.google.common.annotations.VisibleForTesting; import google.registry.proxy.EppProtocolModule.EppProtocol; import google.registry.proxy.metric.FrontendMetrics; import google.registry.proxy.quota.QuotaManager; @@ -26,8 +27,9 @@ import google.registry.proxy.quota.QuotaManager.QuotaResponse; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.util.ReferenceCountUtil; import jakarta.inject.Inject; -import java.util.concurrent.Future; +import javax.annotation.Nullable; /** * Handler that checks quota fulfillment and terminates connection if necessary. @@ -38,9 +40,23 @@ */ public abstract class QuotaHandler extends ChannelInboundHandlerAdapter { + /** Explicit quota lease lifecycle state for a connection. */ + @VisibleForTesting + enum LeaseState { + /** Quota has not yet been requested on this connection. */ + UNCHECKED, + /** Quota was granted and is currently leased for this connection. */ + LEASED, + /** Quota was denied; all subsequent pipelined frames must be dropped. */ + REJECTED, + /** Connection became inactive and any leased quota has been returned. */ + RELEASED + } + protected final QuotaManager quotaManager; - protected QuotaResponse quotaResponse; protected final FrontendMetrics metrics; + protected LeaseState leaseState = LeaseState.UNCHECKED; + @Nullable protected QuotaResponse quotaResponse; protected QuotaHandler(QuotaManager quotaManager, FrontendMetrics metrics) { this.quotaManager = quotaManager; @@ -54,17 +70,26 @@ protected QuotaHandler(QuotaManager quotaManager, FrontendMetrics metrics) { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if (quotaResponse == null) { - String userId = getUserId(ctx); - checkNotNull(userId, "Cannot obtain User ID"); - quotaResponse = quotaManager.acquireQuota(new QuotaRequest(userId)); - if (!quotaResponse.success()) { - String protocolName = ctx.channel().attr(PROTOCOL_KEY).get().name(); - metrics.registerQuotaRejection(protocolName, isUserIdPii() ? "none" : userId); - throw new OverQuotaException(protocolName, isUserIdPii() ? "none" : userId); + switch (leaseState) { + case UNCHECKED -> { + String userId = getUserId(ctx); + checkNotNull(userId, "Cannot obtain User ID"); + QuotaResponse response = quotaManager.acquireQuota(new QuotaRequest(userId)); + if (!response.success()) { + leaseState = LeaseState.REJECTED; + ReferenceCountUtil.release(msg); + String protocolName = ctx.channel().attr(PROTOCOL_KEY).get().name(); + metrics.registerQuotaRejection(protocolName, isUserIdPii() ? "none" : userId); + throw new OverQuotaException(protocolName, isUserIdPii() ? "none" : userId); + } + quotaResponse = response; + leaseState = LeaseState.LEASED; + ctx.fireChannelRead(msg); } + case LEASED -> ctx.fireChannelRead(msg); + case REJECTED -> ReferenceCountUtil.release(msg); + case RELEASED -> ReferenceCountUtil.release(msg); } - ctx.fireChannelRead(msg); } /** @@ -114,15 +139,16 @@ boolean isUserIdPii() { *

A connection with concurrent quota needs to do this in order to maintain its quota number * invariance. */ + @SuppressWarnings("FutureReturnValueIgnored") @Override public void channelInactive(ChannelHandlerContext ctx) { // If no reads occurred before the connection is inactive (for example when the handshake - // is not successful), no quota is leased and therefore no return is needed. - // Note that the quota response can be a failure, in which case no token was leased to us from - // the token store. Consequently no return is necessary. - if (quotaResponse != null && quotaResponse.success()) { - Future unusedFuture = quotaManager.releaseQuota(QuotaRebate.create(quotaResponse)); + // is not successful), or if quota was rejected or already released, no return is needed. + if (leaseState == LeaseState.LEASED) { + quotaManager.releaseQuota(QuotaRebate.create(checkNotNull(quotaResponse))); + quotaResponse = null; } + leaseState = LeaseState.RELEASED; ctx.fireChannelInactive(); } } diff --git a/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java b/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java index a1ad456827e..688788915c1 100644 --- a/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java +++ b/proxy/src/test/java/google/registry/proxy/handler/EppQuotaHandlerTest.java @@ -26,12 +26,15 @@ import com.google.common.collect.ImmutableList; import google.registry.proxy.Protocol; import google.registry.proxy.handler.QuotaHandler.EppQuotaHandler; +import google.registry.proxy.handler.QuotaHandler.LeaseState; import google.registry.proxy.handler.QuotaHandler.OverQuotaException; import google.registry.proxy.metric.FrontendMetrics; import google.registry.proxy.quota.QuotaManager; import google.registry.proxy.quota.QuotaManager.QuotaRebate; import google.registry.proxy.quota.QuotaManager.QuotaRequest; import google.registry.proxy.quota.QuotaManager.QuotaResponse; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.embedded.EmbeddedChannel; @@ -167,4 +170,56 @@ void testSuccess_twoChannels_sameUserIds() { verify(metrics).registerQuotaRejection("epp", clientCertHash); verifyNoMoreInteractions(metrics); } + + @Test + void testFailure_pipelinedFramesAfterQuotaRejection_droppedAndReleased() { + when(quotaManager.acquireQuota(new QuotaRequest(clientCertHash))) + .thenReturn(new QuotaResponse(false, clientCertHash, now)); + + ByteBuf firstFrame = Unpooled.buffer(8).writeBytes(new byte[] {1, 2, 3, 4}); + OverQuotaException e = + assertThrows(OverQuotaException.class, () -> channel.writeInbound(firstFrame)); + assertThat(e).hasMessageThat().contains(clientCertHash); + assertThat(handler.leaseState).isEqualTo(LeaseState.REJECTED); + assertThat(firstFrame.refCnt()).isEqualTo(0); + assertThat((Object) channel.readInbound()).isNull(); + + // Pipelined frame arrives before async ctx.close() completes: must be dropped, not forwarded. + ByteBuf pipelinedFrame = Unpooled.buffer(8).writeBytes(new byte[] {5, 6, 7, 8}); + assertThat(channel.writeInbound(pipelinedFrame)).isFalse(); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(pipelinedFrame.refCnt()).isEqualTo(0); + + assertThat(channel.close().isSuccess()).isTrue(); + assertThat(handler.leaseState).isEqualTo(LeaseState.RELEASED); + verify(quotaManager).acquireQuota(new QuotaRequest(clientCertHash)); + verifyNoMoreInteractions(quotaManager); + verify(metrics).registerQuotaRejection("epp", clientCertHash); + verifyNoMoreInteractions(metrics); + } + + @Test + void testChannelInactive_idempotentReleaseAndDropsSubsequentFrames() { + when(quotaManager.acquireQuota(new QuotaRequest(clientCertHash))) + .thenReturn(new QuotaResponse(true, clientCertHash, now)); + + assertThat(channel.writeInbound(message)).isTrue(); + assertThat((Object) channel.readInbound()).isEqualTo(message); + assertThat(handler.leaseState).isEqualTo(LeaseState.LEASED); + + channel.pipeline().fireChannelInactive(); + assertThat(handler.leaseState).isEqualTo(LeaseState.RELEASED); + // Firing channelInactive again must not double-release quota. + channel.pipeline().fireChannelInactive(); + + ByteBuf strayFrame = Unpooled.buffer(4).writeInt(42); + assertThat(channel.writeInbound(strayFrame)).isFalse(); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(strayFrame.refCnt()).isEqualTo(0); + + verify(quotaManager).acquireQuota(new QuotaRequest(clientCertHash)); + verify(quotaManager) + .releaseQuota(QuotaRebate.create(new QuotaResponse(true, clientCertHash, now))); + verifyNoMoreInteractions(quotaManager); + } } diff --git a/proxy/src/test/java/google/registry/proxy/handler/ProxyProtocolHandlerTest.java b/proxy/src/test/java/google/registry/proxy/handler/ProxyProtocolHandlerTest.java index de75b512f0f..e319134b8a9 100644 --- a/proxy/src/test/java/google/registry/proxy/handler/ProxyProtocolHandlerTest.java +++ b/proxy/src/test/java/google/registry/proxy/handler/ProxyProtocolHandlerTest.java @@ -15,12 +15,15 @@ package google.registry.proxy.handler; import static com.google.common.truth.Truth.assertThat; +import static google.registry.proxy.handler.ProxyProtocolHandler.MAX_PROXY_HEADER_LENGTH; import static google.registry.proxy.handler.ProxyProtocolHandler.REMOTE_ADDRESS_KEY; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertThrows; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.handler.codec.TooLongFrameException; import org.junit.jupiter.api.Test; /** Unit tests for {@link ProxyProtocolHandler}. */ @@ -125,4 +128,70 @@ void testSuccess_proxyHeaderNotPresent_multipleFrames() { assertThat(channel.pipeline().get(ProxyProtocolHandler.class)).isNull(); assertThat(channel.isActive()).isTrue(); } + + @Test + void testSuccess_proxyHeaderAtExact107ByteCap() { + // 105-byte header + 2-byte CRLF = 107 bytes (exact HAProxy PROXY protocol v1 cap). + String paddedHeader = + "PROXY TCP6 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff " + + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535000\r\n"; + assertThat(paddedHeader.length()).isEqualTo(MAX_PROXY_HEADER_LENGTH); + String message = "tls-payload"; + assertThat( + channel.writeInbound(Unpooled.wrappedBuffer((paddedHeader + message).getBytes(UTF_8)))) + .isTrue(); + assertThat(((ByteBuf) channel.readInbound()).toString(UTF_8)).isEqualTo(message); + assertThat(channel.attr(REMOTE_ADDRESS_KEY).get()) + .isEqualTo("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + assertThat(channel.pipeline().get(ProxyProtocolHandler.class)).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testSuccess_validProxyHeaderFollowedByLargePayloadOver107Bytes() { + header = String.format(HEADER_TEMPLATE, 4, "172.0.0.1", "255.255.255.255", "234", "123"); + String largePayload = "X".repeat(300); + assertThat( + channel.writeInbound(Unpooled.wrappedBuffer((header + largePayload).getBytes(UTF_8)))) + .isTrue(); + assertThat(((ByteBuf) channel.readInbound()).toString(UTF_8)).isEqualTo(largePayload); + assertThat(channel.attr(REMOTE_ADDRESS_KEY).get()).isEqualTo("172.0.0.1"); + assertThat(channel.pipeline().get(ProxyProtocolHandler.class)).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testFailure_proxyHeaderExceeds107BytesWithoutCrlf_singleFrame() { + String oversized = "PROXY " + "A".repeat(MAX_PROXY_HEADER_LENGTH - 6); + assertThat(oversized.length()).isEqualTo(MAX_PROXY_HEADER_LENGTH); + assertThrows( + TooLongFrameException.class, + () -> channel.writeInbound(Unpooled.wrappedBuffer(oversized.getBytes(UTF_8)))); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isFalse(); + } + + @Test + void testFailure_proxyHeaderExceeds107BytesWithoutCrlf_multipleFrames() { + String chunk1 = "PROXY " + "A".repeat(54); // 60 bytes + String chunk2 = "B".repeat(MAX_PROXY_HEADER_LENGTH - 60); // 47 bytes -> total 107 without CRLF + assertThat(channel.writeInbound(Unpooled.wrappedBuffer(chunk1.getBytes(UTF_8)))).isFalse(); + assertThat(channel.isActive()).isTrue(); + assertThrows( + TooLongFrameException.class, + () -> channel.writeInbound(Unpooled.wrappedBuffer(chunk2.getBytes(UTF_8)))); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isFalse(); + } + + @Test + void testFailure_proxyHeader108BytesWithCrlf_rejected() { + String oversizedWithCrlf = "PROXY " + "A".repeat(MAX_PROXY_HEADER_LENGTH - 7) + "\r\n"; + assertThat(oversizedWithCrlf.length()).isEqualTo(MAX_PROXY_HEADER_LENGTH + 1); + assertThrows( + TooLongFrameException.class, + () -> channel.writeInbound(Unpooled.wrappedBuffer(oversizedWithCrlf.getBytes(UTF_8)))); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isFalse(); + } }