Croway commented on code in PR #30509:
URL: https://github.com/apache/camel/pull/30509#discussion_r4644650425


##########
components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java:
##########
@@ -568,6 +573,15 @@ public HttpResponse toNettyResponse(Message message, 
NettyHttpConfiguration conf
         // must use entrySet to ensure case of keys is preserved
         for (Map.Entry<String, Object> entry : 
message.getHeaders().entrySet()) {
             String key = entry.getKey();
+            if (!HttpHelper.isValidHeaderName(key)) {

Review Comment:
   **A route that calls another HTTP endpoint now runs, then fails, and the 
client still gets a 500**
   
   This check only covers the consumer's response. The producers still copy 
every message header into the request they send: `toNettyRequest` in this file 
(`request.headers().add(key, headerValue)`) and `HttpProducer` in camel-http 
(`httpRequest.addHeader`). So when a route forwards the request, the text this 
PR now accepts reaches the producer as a header name.
   
   Body `Hi, I'm [email protected]. My order is late, can you refund it?`, 
posted as form data:
   
   | route | PR head | merge base `c24222f` |
   |---|---|---|
   | netty-http consumer → `to("netty-http:...")` | the route runs, then the 
producer fails with `IllegalArgumentException: a header name can only contain 
"token" characters, but found invalid character 0x2c at index 2 of header 'Hi, 
I'm [email protected]. ...'`. The client gets a 500 | the route does not run, 
and the connection is closed without a response |
   | jetty consumer → `to("http:...?bridgeEndpoint=true")` → jetty backend | 
the route runs and the header is sent. The backend answers 400 
(`HttpOperationFailedException ... statusCode: 400`), and the client gets a 500 
| the route does not run, 500 |
   
   So for these routes the request from the issue still ends in a 500, but now 
after the route has run, that is after any side effect that comes before the 
`to`. Text that contains a `=`, such as `Hi alice, order=42`, already fails 
this way on the merge base. This PR extends it to any text without `=`.
   
   Suggestion: also skip a header whose name is not a token in the producers, 
with the same `HttpHelper.isValidHeaderName`, at least in `toNettyRequest` and 
`HttpProducer`, and add a test that forwards such a request.
   
   <details><summary>Reproducer (camel-netty-http): fails on the PR head with 
500 at the status assertion</summary>
   
   ```java
   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.HttpResponse;
   import java.util.concurrent.atomic.AtomicInteger;
   
   import org.apache.camel.builder.RouteBuilder;
   import org.junit.jupiter.api.Test;
   
   import static org.junit.jupiter.api.Assertions.assertEquals;
   
   public class NettyHttpForwardFormTextTest extends BaseNettyTestSupport {
   
       private static final String TEXT = "Hi, I'm [email protected]. My order 
is late, can you refund it?";
   
       private final AtomicInteger frontRuns = new AtomicInteger();
       private final AtomicInteger backRuns = new AtomicInteger();
   
       @Test
       void formTextIsForwarded() throws Exception {
           try (HttpClient client = HttpClient.newHttpClient()) {
               HttpRequest request = 
HttpRequest.newBuilder(URI.create("http://localhost:"; + port.getPort() + 
"/front"))
                       .header("Content-Type", 
"application/x-www-form-urlencoded")
                       .POST(HttpRequest.BodyPublishers.ofString(TEXT)).build();
               HttpResponse<String> response = client.send(request, 
HttpResponse.BodyHandlers.ofString());
               assertEquals(1, frontRuns.get());
               // 500 on the PR head: the netty-http producer fails on the 
header name, after the route has run
               assertEquals(200, response.statusCode());
               assertEquals("back ok", response.body());
           }
           assertEquals(1, backRuns.get());
       }
   
       @Override
       protected RouteBuilder createRouteBuilder() {
           return new RouteBuilder() {
               public void configure() {
                   from("netty-http:http://localhost:{{port}}/front";)
                           .process(e -> frontRuns.incrementAndGet())
                           .to("netty-http:http://localhost:{{port}}/back";);
   
                   from("netty-http:http://localhost:{{port}}/back";)
                           .process(e -> backRuns.incrementAndGet())
                           .setBody(constant("back ok"));
               }
           };
       }
   }
   ```
   </details>



##########
components/camel-http-common/src/main/java/org/apache/camel/http/common/DefaultHttpBinding.java:
##########
@@ -311,16 +311,18 @@ protected void readFormUrlEncodedBody(HttpServletRequest 
request, Message messag
                 String text = message.getBody(String.class);
                 if (org.apache.camel.util.ObjectHelper.isNotEmpty(text)) {
                     for (String param : text.split("&")) {
-                        String[] pair = param.split("=", 2);
-                        if (pair.length == 2) {
-                            String name = URLDecoder.decode(pair[0], charset);
-                            String value = URLDecoder.decode(pair[1], charset);
-                            if (headerFilterStrategy != null
-                                    && 
!headerFilterStrategy.applyFilterToExternalHeaders(name, value, 
message.getExchange())) {
-                                HttpHelper.appendHeader(headers, name, value);
-                            }
-                        } else {
-                            throw new IllegalArgumentException("Invalid 
parameter, expected to be a pair but was " + param);
+                        if (param.isEmpty()) {
+                            // an empty field, as in a=1&&b=2, has no name
+                            continue;
+                        }
+                        // a field without = is a name with an empty value, as 
in the URL-encoded form parser
+                        // of the WHATWG URL standard, which is what browsers 
and Vert.x do
+                        int pos = param.indexOf('=');
+                        String name = URLDecoder.decode(pos < 0 ? param : 
param.substring(0, pos), charset);

Review Comment:
   **A `%` in the text still fails the request with a 500 before the route 
runs**
   
   `URLDecoder.decode` throws `IllegalArgumentException` on a `%` that is not 
followed by two hex digits. So the text this PR lets through still fails when 
it contains such a `%`: for example `curl -d "Save 50% now"`, or JSON posted 
with `curl -d` and no `-H`, such as `{"discount":"50%"}`. The WHATWG parser 
that the comment refers to leaves such a sequence as it is. The new 
upgrade-guide entry ("A text body that a client sends as form data [...] now 
reaches the route") does not hold for these bodies.
   
   Observed with a jetty consumer, which uses `DefaultHttpBinding`, and a JDK 
`HttpClient` POST with `Content-Type: application/x-www-form-urlencoded`:
   
   | body | PR head | merge base `c24222f` |
   |---|---|---|
   | `Save 50 percent now` | 200, the route runs | 500 |
   | `Save 50% now` | 500, the route does not run | 500 |
   | `{"discount":"50%"}` | 500, the route does not run | 500 |
   
   On the PR head, the 500 logs `Error handling request due to: URLDecoder: 
Illegal hex characters in escape (%) pattern - not a hexadecimal digit: " " = 
32`.
   
   `DefaultNettyHttpBinding` decodes the same way when `urlDecodeHeaders=true` 
(not the default). I did not run that case.
   
   Suggestion: decode as the WHATWG parser does, leaving a `%` that is not 
followed by two hex digits as it is. Catching the `IllegalArgumentException` 
and keeping the raw text, as `HttpHelper.decodePathParameter` does, would also 
do. Then add a body with a stray `%` to `DefaultHttpBindingFormUrlEncodedTest`.
   
   <details><summary>Reproducer (camel-jetty): fails on the PR head at the 
<code>Save 50% now</code> line</summary>
   
   ```java
   package org.apache.camel.component.jetty;
   
   import java.net.URI;
   import java.net.http.HttpClient;
   import java.net.http.HttpRequest;
   import java.net.http.HttpResponse;
   import java.util.concurrent.atomic.AtomicInteger;
   
   import org.apache.camel.builder.RouteBuilder;
   import org.junit.jupiter.api.Test;
   
   import static org.junit.jupiter.api.Assertions.assertEquals;
   
   public class FormTextWithPercentTest extends BaseJettyTest {
   
       private final AtomicInteger runs = new AtomicInteger();
   
       @Test
       void textWithPercentReachesTheRoute() throws Exception {
           // 200 on the PR head
           assertEquals(200, post("Save 50 percent now"));
           // 500 on the PR head, and the route does not run
           assertEquals(200, post("Save 50% now"));
           assertEquals(200, post("{\"discount\":\"50%\"}"));
           assertEquals(3, runs.get());
       }
   
       private int post(String body) throws Exception {
           try (HttpClient client = HttpClient.newHttpClient()) {
               HttpRequest request = 
HttpRequest.newBuilder(URI.create("http://localhost:"; + getPort() + "/echo"))
                       .header("Content-Type", 
"application/x-www-form-urlencoded")
                       .POST(HttpRequest.BodyPublishers.ofString(body)).build();
               return client.send(request, 
HttpResponse.BodyHandlers.ofString()).statusCode();
           }
       }
   
       @Override
       protected RouteBuilder createRouteBuilder() {
           return new RouteBuilder() {
               public void configure() {
                   from("jetty:http://localhost:{{port}}/echo";)
                           .process(e -> runs.incrementAndGet())
                           .setBody(constant("echo ok"));
               }
           };
       }
   }
   ```
   </details>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to