oscerd commented on code in PR #26659:
URL: https://github.com/apache/camel/pull/26659#discussion_r4071365988


##########
components/camel-mail/src/test/java/org/apache/camel/component/mail/MailPoisonMessageTest.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.mail;
+
+import java.time.Duration;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import jakarta.mail.Address;
+import jakarta.mail.Message;
+import jakarta.mail.MessagingException;
+import jakarta.mail.Session;
+import jakarta.mail.internet.InternetAddress;
+import jakarta.mail.internet.MimeBodyPart;
+import jakarta.mail.internet.MimeMessage;
+import jakarta.mail.internet.MimeMultipart;
+
+import org.apache.camel.attachment.Attachment;
+import org.eclipse.angus.mail.imap.SortTerm;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.mockito.Mockito.when;
+
+/**
+ * A single malformed or merely unusual message must not put the consumer into 
a state it never recovers from. Each of
+ * these previously aborted or hung the poll, and repeated on every subsequent 
poll until the message was removed out of
+ * band.
+ */
+class MailPoisonMessageTest {
+
+    @Test
+    void sortingToleratesAMessageWithoutTheSortedOnHeader() throws Exception {
+        // Subject is optional in RFC 5322, so a message may legitimately 
carry none
+        Message withSubject = mockMessage("subject");
+        Message withoutSubject = mockMessage(null);
+
+        Message[] messages = { withSubject, withoutSubject };
+        assertDoesNotThrow(() -> MailSorter.sortMessages(messages, new 
SortTerm[] { SortTerm.SUBJECT }));
+    }
+
+    @Test
+    void deeplyNestedMultipartDoesNotExhaustTheStack() {
+        assertDoesNotThrow(() -> {
+            MimeMultipart nested = new MimeMultipart();
+            MimeBodyPart leaf = new MimeBodyPart();
+            leaf.setText("payload");
+            nested.addBodyPart(leaf);
+
+            for (int i = 0; i < 8000; i++) {
+                MimeBodyPart wrapper = new MimeBodyPart();
+                wrapper.setContent(nested);
+                // setContent(Multipart) does not update the part's 
Content-Type header until the
+                // enclosing message is saved, and MailBinding dispatches on 
isMimeType("multipart/*"),
+                // so the header has to be set explicitly for this to exercise 
the recursion at all
+                wrapper.setHeader("Content-Type", nested.getContentType());
+                MimeMultipart outer = new MimeMultipart();
+                outer.addBodyPart(wrapper);
+                nested = outer;
+            }
+
+            Map<String, Attachment> map = new HashMap<>();
+            new MailBinding().extractAttachmentsFromMultipart(nested, map);
+        });
+    }
+
+    @Test
+    void emptyMultipartDoesNotSpinForever() {
+        assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
+            MimeMessage message = new 
MimeMessage(Session.getDefaultInstance(new java.util.Properties()));

Review Comment:
   Done in 659b83c — added `import java.util.Properties;` and use the simple 
name.
   
   _Claude Code on behalf of oscerd_
   



##########
components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java:
##########
@@ -73,6 +73,8 @@
 public class MailBinding {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(MailBinding.class);
+
+    private static final int MAX_MULTIPART_DEPTH = 20;

Review Comment:
   Good call. 20 was a defensive bound — real mail nests only a few multipart 
levels, and before this change the recursion was unbounded, so a crafted deeply 
nested message could throw `StackOverflowError` before the message was even 
processed, aborting the poll on every retry.
   
   To address the backward-compatibility concern, 659b83c makes it a 
configurable `maxMultipartDepth` option on `MailConfiguration` (default 20), 
threaded into `MailBinding`, so a deployment that legitimately produces deeper 
nesting can raise it. Catalog and DSL regenerated for the new option, and a 
test asserts the configured bound is honoured.
   
   _Claude Code on behalf of oscerd_
   



##########
components/camel-mail/src/main/java/org/apache/camel/component/mail/MailSorter.java:
##########
@@ -114,38 +114,59 @@ private static void sortMessages(Message[] messages, 
final List<SortTermWithDesc
      * @throws jakarta.mail.MessagingException If message data could not be 
read.
      */
     private static int compareMessageProperty(Message msg1, Message msg2, 
SortTerm property) throws MessagingException {
+        // Every value read here is optional in RFC 5322 or may be absent on 
the server, so each comparison
+        // must tolerate a missing value. A message legitimately lacking the 
sorted-on property previously
+        // threw from inside the comparator and aborted the whole poll, on 
every subsequent poll.
         if (property.equals(SortTerm.TO)) {
-            InternetAddress addr1 = (InternetAddress) 
msg1.getRecipients(Message.RecipientType.TO)[0];
-            InternetAddress addr2 = (InternetAddress) 
msg2.getRecipients(Message.RecipientType.TO)[0];
-            return addr1.getAddress().compareTo(addr2.getAddress());
+            return 
compareNullable(firstAddress(msg1.getRecipients(Message.RecipientType.TO)),
+                    
firstAddress(msg2.getRecipients(Message.RecipientType.TO)));
         } else if (property.equals(SortTerm.CC)) {
-            InternetAddress addr1 = (InternetAddress) 
msg1.getRecipients(Message.RecipientType.CC)[0];
-            InternetAddress addr2 = (InternetAddress) 
msg2.getRecipients(Message.RecipientType.CC)[0];
-            return addr1.getAddress().compareTo(addr2.getAddress());
+            return 
compareNullable(firstAddress(msg1.getRecipients(Message.RecipientType.CC)),
+                    
firstAddress(msg2.getRecipients(Message.RecipientType.CC)));
         } else if (property.equals(SortTerm.FROM)) {
-            InternetAddress addr1 = (InternetAddress) msg1.getFrom()[0];
-            InternetAddress addr2 = (InternetAddress) msg2.getFrom()[0];
-            return addr1.getAddress().compareTo(addr2.getAddress());
+            return compareNullable(firstAddress(msg1.getFrom()), 
firstAddress(msg2.getFrom()));
         } else if (property.equals(SortTerm.ARRIVAL)) {
-            Date arr1 = msg1.getReceivedDate();
-            Date arr2 = msg2.getReceivedDate();
-            return arr1.compareTo(arr2);
+            return compareNullable(msg1.getReceivedDate(), 
msg2.getReceivedDate());
         } else if (property.equals(SortTerm.DATE)) {
-            Date sent1 = msg1.getSentDate();
-            Date sent2 = msg2.getSentDate();
-            return sent1.compareTo(sent2);
+            return compareNullable(msg1.getSentDate(), msg2.getSentDate());
         } else if (property.equals(SortTerm.SIZE)) {
-            int size1 = msg1.getSize();
-            int size2 = msg2.getSize();
-            return Integer.compare(size1, size2);
+            return Integer.compare(msg1.getSize(), msg2.getSize());
         } else if (property.equals(SortTerm.SUBJECT)) {
-            String sub1 = msg1.getSubject();
-            String sub2 = msg2.getSubject();
-            return sub1.compareTo(sub2);
+            return compareNullable(msg1.getSubject(), msg2.getSubject());
         }
         throw new IllegalArgumentException(String.format("Unknown sort term: 
%s", property.toString()));
     }
 
+    /**
+     * Returns the address of the first entry, or null when the message 
carries none.
+     */
+    private static String firstAddress(Address[] addresses) {
+        if (addresses == null || addresses.length == 0) {
+            return null;
+        }
+        if (addresses[0] instanceof InternetAddress internetAddress) {
+            return internetAddress.getAddress();
+        }
+        return addresses[0].toString();
+    }
+
+    /**
+     * Compares two optional values, ordering a missing one first. Sorting 
must not depend on every message carrying the
+     * sorted-on property.
+     */
+    private static <T extends Comparable<T>> int compareNullable(T value1, T 
value2) {
+        if (value1 == null && value2 == null) {
+            return 0;
+        }
+        if (value1 == null) {
+            return -1;
+        }
+        if (value2 == null) {
+            return 1;
+        }

Review Comment:
   I kept the current behaviour (a missing value sorts first) rather than 
returning 0. Returning 0 only when one side is null would make the comparator 
non-transitive: with `a=null` and `b < c`, we'd have `compare(a, b) == 0` and 
`compare(a, c) == 0` but `compare(b, c) != 0`, which violates the `Comparator` 
general contract and can make `TimSort` throw *"Comparison method violates its 
general contract!"*. Ordering a missing value first keeps a consistent total 
order.
   
   You noted the current choice is fine too — just flagging the transitivity 
reason in case it's useful.
   
   _Claude Code on behalf of oscerd_
   



-- 
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