This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new a99c28cb2b77 CAMEL-27890: camel-netty-http - Tell the client the 
connection is closed on early error responses (#31160)
a99c28cb2b77 is described below

commit a99c28cb2b77523b67bef0c335e3a1cd95e10af5
Author: AurĂ©lien Pupier <[email protected]>
AuthorDate: Tue Dec 1 13:35:53 2026 +0100

    CAMEL-27890: camel-netty-http - Tell the client the connection is closed on 
early error responses (#31160)
    
    Co-authored-by: IBM Bob <[email protected]>
---
 .../http/handlers/HttpServerChannelHandler.java    | 32 +++----
 .../HttpServerMultiplexChannelHandler.java         |  9 +-
 ...NettyHttpErrorResponseClosesConnectionTest.java | 98 ++++++++++++++++++++++
 .../NettyHttpSharedSecurityConfigurationTest.java  | 26 ++++++
 4 files changed, 144 insertions(+), 21 deletions(-)

diff --git 
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
 
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
index f744215c4abb..e5655bdcebe3 100644
--- 
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
+++ 
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java
@@ -29,6 +29,7 @@ import javax.security.auth.Subject;
 import javax.security.auth.login.LoginException;
 
 import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.DecoderResult;
 import io.netty.handler.codec.http.DefaultFullHttpResponse;
@@ -126,8 +127,7 @@ public class HttpServerChannelHandler extends 
ServerChannelHandler {
             HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
BAD_REQUEST);
             response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
             response.headers().set(Exchange.CONTENT_LENGTH, 0);
-            ctx.writeAndFlush(response);
-            ctx.channel().close();
+            writeAndClose(ctx, response);
             return;
         }
 
@@ -137,8 +137,7 @@ public class HttpServerChannelHandler extends 
ServerChannelHandler {
             HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
SERVICE_UNAVAILABLE);
             response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
             response.headers().set(Exchange.CONTENT_LENGTH, 0);
-            ctx.writeAndFlush(response);
-            ctx.channel().close();
+            writeAndClose(ctx, response);
             return;
         }
 
@@ -147,16 +146,14 @@ public class HttpServerChannelHandler extends 
ServerChannelHandler {
             HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
METHOD_NOT_ALLOWED);
             response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
             response.headers().set(Exchange.CONTENT_LENGTH, 0);
-            ctx.writeAndFlush(response);
-            ctx.channel().close();
+            writeAndClose(ctx, response);
             return;
         }
         if ("TRACE".equals(request.method().name()) && 
!consumer.getEndpoint().isTraceEnabled()) {
             HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
METHOD_NOT_ALLOWED);
             response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
             response.headers().set(Exchange.CONTENT_LENGTH, 0);
-            ctx.writeAndFlush(response);
-            ctx.channel().close();
+            writeAndClose(ctx, response);
             return;
         }
         // must include HOST header as required by HTTP 1.1
@@ -165,8 +162,7 @@ public class HttpServerChannelHandler extends 
ServerChannelHandler {
             //response.setChunked(false);
             response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
             response.headers().set(Exchange.CONTENT_LENGTH, 0);
-            ctx.writeAndFlush(response);
-            ctx.channel().close();
+            writeAndClose(ctx, response);
             return;
         }
 
@@ -199,8 +195,7 @@ public class HttpServerChannelHandler extends 
ServerChannelHandler {
                 HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
BAD_REQUEST);
                 response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
                 response.headers().set(Exchange.CONTENT_LENGTH, 0);
-                ctx.writeAndFlush(response);
-                ctx.channel().close();
+                writeAndClose(ctx, response);
                 return;
             }
 
@@ -244,9 +239,7 @@ public class HttpServerChannelHandler extends 
ServerChannelHandler {
                     response.headers().set("WWW-Authenticate", "Basic 
realm=\"" + security.getRealm() + "\"");
                     response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
                     response.headers().set(Exchange.CONTENT_LENGTH, 0);
-                    ctx.writeAndFlush(response);
-                    // close the channel
-                    ctx.channel().close();
+                    writeAndClose(ctx, response);
                     return;
                 } else {
                     LOG.debug("Http Basic Auth authorized for username: {}", 
principal.getUsername());
@@ -260,6 +253,15 @@ public class HttpServerChannelHandler extends 
ServerChannelHandler {
         super.channelRead0(ctx, msg);
     }
 
+    /**
+     * Writes the response, tells the client that the connection is closed so 
that it does not keep the channel in a
+     * pool for reuse, and closes the channel once the response is written.
+     */
+    static void writeAndClose(ChannelHandlerContext ctx, HttpResponse 
response) {
+        response.headers().set(NettyHttpConstants.CONNECTION, 
HttpHeaderValues.CLOSE.toString());
+        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
+    }
+
     private String extractTarget(URI uri) {
         String target = uri.getPath();
 
diff --git 
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java
 
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java
index 6b0304a00092..7fb34dee6db6 100644
--- 
a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java
+++ 
b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java
@@ -151,8 +151,7 @@ public class HttpServerMultiplexChannelHandler extends 
SimpleChannelInboundHandl
                 response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
                 response.headers().set(Exchange.CONTENT_LENGTH, 0);
                 response.headers().set("Allow", allowedMethods);
-                ctx.writeAndFlush(response);
-                ctx.close();
+                HttpServerChannelHandler.writeAndClose(ctx, response);
             } else {
                 Attribute<HttpServerChannelHandler> attr = 
ctx.channel().attr(SERVER_HANDLER_KEY);
                 // store handler as attachment
@@ -177,8 +176,7 @@ public class HttpServerMultiplexChannelHandler extends 
SimpleChannelInboundHandl
             }
             response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
             response.headers().set(Exchange.CONTENT_LENGTH, 0);
-            ctx.writeAndFlush(response);
-            ctx.close();
+            HttpServerChannelHandler.writeAndClose(ctx, response);
         }
     }
 
@@ -202,8 +200,7 @@ public class HttpServerMultiplexChannelHandler extends 
SimpleChannelInboundHandl
                 HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
NOT_FOUND);
                 response.headers().set(NettyHttpConstants.CONTENT_TYPE, 
"text/plain");
                 response.headers().set(Exchange.CONTENT_LENGTH, 0);
-                ctx.writeAndFlush(response);
-                ctx.close();
+                HttpServerChannelHandler.writeAndClose(ctx, response);
             }
         }
     }
diff --git 
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpErrorResponseClosesConnectionTest.java
 
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpErrorResponseClosesConnectionTest.java
new file mode 100644
index 000000000000..2ac80ad2a9a5
--- /dev/null
+++ 
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpErrorResponseClosesConnectionTest.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.camel.component.netty.http;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpRequest.BodyPublishers;
+import java.net.http.HttpResponse;
+import java.net.http.HttpResponse.BodyHandlers;
+import java.time.Duration;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+/**
+ * The server closes the channel after it has sent an error response itself, 
so the response must tell the client that
+ * the connection is closed. Otherwise a keep-alive client, such as the Camel 
producer, keeps the channel in a pool and
+ * the next request randomly fails on the closed channel.
+ */
+class NettyHttpErrorResponseClosesConnectionTest extends BaseNettyTestSupport {
+
+    private HttpResponse<String> send(String method, String path) throws 
Exception {
+        HttpRequest request = 
HttpRequest.newBuilder(URI.create("http://localhost:"; + getPort() + path))
+                .method(method, BodyPublishers.noBody())
+                .timeout(Duration.ofSeconds(30))
+                .build();
+        try (HttpClient client = HttpClient.newHttpClient()) {
+            return client.send(request, BodyHandlers.ofString());
+        }
+    }
+
+    private void assertClosesConnection(int expectedStatus, 
HttpResponse<String> response) {
+        assertEquals(expectedStatus, response.statusCode());
+        assertEquals("close", 
response.headers().firstValue("Connection").orElse(null));
+    }
+
+    @Test
+    void testNotFound() throws Exception {
+        assertClosesConnection(404, send("GET", "/nowhere"));
+    }
+
+    @Test
+    void testMethodNotAllowedWhenNoConsumerMatchesTheMethod() throws Exception 
{
+        assertClosesConnection(405, send("POST", "/getonly"));
+    }
+
+    @Test
+    void testMethodNotAllowedForTrace() throws Exception {
+        assertClosesConnection(405, send("TRACE", "/any"));
+    }
+
+    @Test
+    void testOptions() throws Exception {
+        HttpResponse<String> response = send("OPTIONS", "/any");
+        assertNotNull(response.headers().firstValue("Allow").orElse(null));
+        assertClosesConnection(200, response);
+    }
+
+    @Test
+    void testServiceUnavailableWhenConsumerIsSuspended() throws Exception {
+        NettyHttpConsumer consumer = (NettyHttpConsumer) 
context.getRoute("any").getConsumer();
+        consumer.suspend();
+
+        assertClosesConnection(503, send("GET", "/any"));
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("netty-http:http://0.0.0.0:{{port}}/any";).routeId("any")
+                        .transform().constant("Any OK");
+
+                
from("netty-http:http://0.0.0.0:{{port}}/getonly?httpMethodRestrict=GET";)
+                        .transform().constant("Get OK");
+            }
+        };
+    }
+}
diff --git 
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpSharedSecurityConfigurationTest.java
 
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpSharedSecurityConfigurationTest.java
index 8464090fa0fb..b7b9cdb79685 100644
--- 
a/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpSharedSecurityConfigurationTest.java
+++ 
b/components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpSharedSecurityConfigurationTest.java
@@ -16,6 +16,14 @@
  */
 package org.apache.camel.component.netty.http;
 
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpRequest.BodyPublishers;
+import java.net.http.HttpResponse;
+import java.net.http.HttpResponse.BodyHandlers;
+import java.time.Duration;
+
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelExecutionException;
 import org.apache.camel.builder.RouteBuilder;
@@ -80,6 +88,24 @@ class NettyHttpSharedSecurityConfigurationTest extends 
BaseNettyTestSupport {
         assertNotSame(adminEndpoint.getSecurityConfiguration(), 
publicEndpoint.getSecurityConfiguration());
     }
 
+    @Test
+    void testUnauthorizedResponseClosesConnection() throws Exception {
+        // The 401 is sent before the channel is closed by the server, so the 
response must say so. Otherwise the
+        // Camel producer pools the channel and a following request randomly 
fails on the closed channel.
+        HttpRequest request = 
HttpRequest.newBuilder(URI.create("http://localhost:"; + getPort() + "/admin"))
+                .POST(BodyPublishers.ofString("Hello Admin"))
+                .timeout(Duration.ofSeconds(30))
+                .build();
+
+        HttpResponse<String> response;
+        try (HttpClient client = HttpClient.newHttpClient()) {
+            response = client.send(request, BodyHandlers.ofString());
+        }
+
+        assertEquals(401, response.statusCode());
+        assertEquals("close", 
response.headers().firstValue("Connection").orElse(null));
+    }
+
     @Test
     void testAuthenticationEnforcement() {
         // Unauthenticated request to admin route should fail with 401

Reply via email to