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

chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-jsieve.git

commit 592e44ea975c492eef1ec123c9ec39cc9695be39
Author: Benoit TELLIER <[email protected]>
AuthorDate: Thu Nov 26 08:43:54 2026 +0100

    [FIX] MailUtils: look up the spellings of a header name linearly
    
    getMatchingHeader called getHeader once per spelling of the name among
    the header names of the mail. An adapter whose getHeader ignores case,
    as JavaMail's does and James's relies on, answers the values of every
    spelling to each call: k spellings of a name made k calls of k values,
    k squared strings gathered before the evaluation budget could charge
    them. A mail of a few tens of thousands of case variants of a long name
    exhausted the heap for any script testing that name.
    
    When a name has several spellings, the adapter is asked a case spelling
    of a header name that the mail does not hold: an adapter matching the
    exact name answers no value for it, one ignoring case answers some. The
    latter is then asked one spelling per family of case spellings, the
    former still every spelling. Finding the absent spelling tries each
    family at most as many times as it has members, so it stays linear in
    the header names. A mail holding every case spelling of every name, a
    crafted one only, is looked up as by an adapter ignoring case.
---
 .../java/org/apache/jsieve/mail/MailUtils.java     | 84 +++++++++++++++++++++-
 .../org/apache/jsieve/EvaluationBudgetTest.java    | 77 ++++++++++++++++++++
 2 files changed, 159 insertions(+), 2 deletions(-)

diff --git a/core/src/main/java/org/apache/jsieve/mail/MailUtils.java 
b/core/src/main/java/org/apache/jsieve/mail/MailUtils.java
index 167d356..a122e3d 100644
--- a/core/src/main/java/org/apache/jsieve/mail/MailUtils.java
+++ b/core/src/main/java/org/apache/jsieve/mail/MailUtils.java
@@ -20,7 +20,11 @@
 package org.apache.jsieve.mail;
 
 import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 import org.apache.jsieve.comparators.AsciiCasemap;
 
@@ -56,13 +60,89 @@ public class MailUtils {
      */
     static public List<String> getMatchingHeader(MailAdapter mail, String name)
             throws SieveMailException {
-        final List<String> matchedHeaderValues = new ArrayList<String>(32);
         // Header names are compared with i;ascii-casemap (RFC 5228 section 
2.7)
         final String asciiUpperCaseName = AsciiCasemap.toAsciiUpperCase(name);
-        for (String headerName: mail.getHeaderNames()) {
+        final List<String> headerNames = mail.getHeaderNames();
+        final List<String> matchingNames = new ArrayList<String>();
+        for (String headerName: headerNames) {
             if 
(AsciiCasemap.toAsciiUpperCase(headerName.trim()).equals(asciiUpperCaseName))
+                matchingNames.add(headerName);
+        }
+        final List<String> matchedHeaderValues = new ArrayList<String>(32);
+        if (matchingNames.isEmpty()) {
+            return matchedHeaderValues;
+        }
+        final boolean ignoresCase = matchingNames.size() > 1
+            && getHeaderIgnoresCase(mail, headerNames, matchingNames.get(0));
+        // Spellings differing in their whitespace are asked each, whatever 
the adapter
+        final Set<String> askedSpellings = new HashSet<String>();
+        for (String headerName : matchingNames) {
+            if (!ignoresCase || 
askedSpellings.add(AsciiCasemap.toAsciiUpperCase(headerName))) {
                 matchedHeaderValues.addAll(mail.getHeader(headerName));
+            }
         }
         return matchedHeaderValues;
     }
+
+    /**
+     * Whether the getHeader of the adapter ignores the case of the name, as
+     * the one of JavaMail does: then each spelling of a name answers the
+     * values of all of them, and asking each of k spellings would answer k
+     * times k values. The adapter is asked a case spelling of a header name
+     * that the mail does not hold: an adapter matching the exact name answers
+     * no value for it. The spellings of the given name are tried first, then
+     * those of the other names, each family of spellings at most as many
+     * times as it has members, so that this is linear in the header names.
+     * When the mail holds every case spelling of every name, which no mail
+     * but a crafted one does, the adapter is deemed to ignore case: only the
+     * values of one spelling are looked up.
+     */
+    private static boolean getHeaderIgnoresCase(MailAdapter mail, List<String> 
headerNames, String name)
+            throws SieveMailException {
+        final Set<String> names = new HashSet<String>(headerNames);
+        final Map<String, Integer> families = new LinkedHashMap<String, 
Integer>();
+        families.put(AsciiCasemap.toAsciiUpperCase(name), 0);
+        for (String headerName : headerNames) {
+            families.merge(AsciiCasemap.toAsciiUpperCase(headerName), 1, 
Integer::sum);
+        }
+        for (Map.Entry<String, Integer> family : families.entrySet()) {
+            final String absent = absentSpelling(family.getKey(), 
family.getValue(), names);
+            if (absent != null) {
+                return !mail.getHeader(absent).isEmpty();
+            }
+        }
+        return true;
+    }
+
+    /**
+     * A spelling of the given upper case name, differing in the case of its
+     * ASCII letters, that is not among the names, or null when the given
+     * number of members of the family already holds all of them.
+     */
+    private static String absentSpelling(String upperCaseName, int members, 
Set<String> names) {
+        final List<Integer> letters = new ArrayList<Integer>();
+        for (int i = 0; i < upperCaseName.length(); i++) {
+            final char c = upperCaseName.charAt(i);
+            if (c >= 'A' && c <= 'Z') {
+                letters.add(i);
+            }
+        }
+        if (letters.size() < 31 && (1 << letters.size()) <= members) {
+            return null;
+        }
+        // members + 1 distinct spellings: at least one of them is absent
+        final char[] spelling = upperCaseName.toCharArray();
+        for (int mask = 0; mask <= members; mask++) {
+            for (int bit = 0; bit < letters.size(); bit++) {
+                final int index = letters.get(bit);
+                final boolean lower = bit < 31 && (mask & (1 << bit)) != 0;
+                spelling[index] = lower ? 
Character.toLowerCase(upperCaseName.charAt(index)) : 
upperCaseName.charAt(index);
+            }
+            final String candidate = new String(spelling);
+            if (!names.contains(candidate)) {
+                return candidate;
+            }
+        }
+        return null;
+    }
 }
diff --git a/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java 
b/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java
index cfa7a9c..1ab89a7 100644
--- a/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java
+++ b/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java
@@ -25,7 +25,9 @@ import static 
org.assertj.core.api.Assertions.assertThatThrownBy;
 
 import java.io.ByteArrayInputStream;
 import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
 import java.util.Collections;
+import java.util.List;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
@@ -36,6 +38,8 @@ import org.apache.jsieve.comparators.Matches;
 import org.apache.jsieve.exception.SieveException;
 import org.apache.jsieve.mail.ActionDiscard;
 import org.apache.jsieve.mail.ActionKeep;
+import org.apache.jsieve.mail.MailUtils;
+import org.apache.jsieve.mail.SieveMailException;
 import org.apache.jsieve.utils.JUnitUtils;
 import org.apache.jsieve.utils.SieveMailAdapter;
 import org.junit.Test;
@@ -166,6 +170,42 @@ public class EvaluationBudgetTest {
             .hasMessageContaining("budget");
     }
 
+    @Test(timeout = 10_000)
+    public void 
theSpellingsOfANameShouldBeLookedUpLinearlyWhenTheAdapterIgnoresCase() throws 
Exception {
+        SieveMailAdapter mail = mailWithSpellings(new 
CaseInsensitiveMailAdapter(), "XXXXXXXXXXXXXX", 10_000);
+
+        assertThat(MailUtils.getMatchingHeader(mail, 
"xxxxxxxxxxxxxx")).hasSize(10_000);
+        factoryWithBudget(10_000_000).interpret(mail, script("if exists 
\"XXXXXXXXXXXXXX\" { discard; }"));
+        
assertThat(mail.getActions()).singleElement().isInstanceOf(ActionDiscard.class);
+    }
+
+    @Test
+    public void 
theSpellingsOfANameShouldEachBeLookedUpWhenTheAdapterMatchesTheExactName() 
throws Exception {
+        SieveMailAdapter mail = mailWithSpellings((SieveMailAdapter) 
JUnitUtils.createMail(), "XXXXXXXXXXXXXX", 100);
+
+        assertThat(MailUtils.getMatchingHeader(mail, 
"xxxxxxxxxxxxxx")).hasSize(100).doesNotHaveDuplicates();
+    }
+
+    @Test
+    public void 
spellingsSharingAValueShouldEachBeLookedUpWhenTheAdapterMatchesTheExactName() 
throws Exception {
+        SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
+        mail.getMessage().addHeader("X-Spam", "yes");
+        mail.getMessage().addHeader("x-spam", "yes");
+        mail.getMessage().addHeader("X-SPAM", "no");
+
+        assertThat(MailUtils.getMatchingHeader(mail, 
"x-spam")).containsExactlyInAnyOrder("yes", "yes", "no");
+    }
+
+    @Test
+    public void 
spellingsSharingAValueShouldBeLookedUpOnceWhenTheAdapterIgnoresCase() throws 
Exception {
+        SieveMailAdapter mail = new CaseInsensitiveMailAdapter();
+        mail.getMessage().addHeader("X-Spam", "yes");
+        mail.getMessage().addHeader("x-spam", "yes");
+        mail.getMessage().addHeader("X-SPAM", "no");
+
+        assertThat(MailUtils.getMatchingHeader(mail, 
"x-spam")).containsExactlyInAnyOrder("yes", "yes", "no");
+    }
+
     @Test
     public void aHeaderNameShouldBeLookedUpOncePerEvaluation() throws 
Exception {
         SieveMailAdapter mail = mailWithHeaders(10_000);
@@ -330,6 +370,43 @@ public class EvaluationBudgetTest {
         return mail;
     }
 
+    /**
+     * Adds the given number of spellings of the name, differing in the case
+     * of their letters, each with its own value.
+     */
+    private static SieveMailAdapter mailWithSpellings(SieveMailAdapter mail, 
String name, int count) throws Exception {
+        for (int i = 0; i < count; i++) {
+            StringBuilder spelling = new StringBuilder(name);
+            for (int bit = 0; bit < name.length(); bit++) {
+                if ((i & (1 << bit)) != 0) {
+                    spelling.setCharAt(bit, 
Character.toLowerCase(name.charAt(bit)));
+                }
+            }
+            mail.getMessage().addHeader(spelling.toString(), "value" + i);
+        }
+        return mail;
+    }
+
+    /**
+     * Answers the fields of every case of the name, as JavaMail does and as
+     * James's adapter relies on.
+     */
+    private static class CaseInsensitiveMailAdapter extends SieveMailAdapter {
+        CaseInsensitiveMailAdapter() {
+            super(((SieveMailAdapter) JUnitUtils.createMail()).getMessage());
+        }
+
+        @Override
+        public List<String> getHeader(String name) throws SieveMailException {
+            try {
+                String[] values = getMessage().getHeader(name);
+                return values == null ? Collections.emptyList() : 
Arrays.asList(values);
+            } catch (javax.mail.MessagingException e) {
+                throw new SieveMailException(e);
+            }
+        }
+    }
+
     private static SieveMailAdapter mailWithSubject(String subject) throws 
Exception {
         SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
         mail.getMessage().setHeader("Subject", subject);


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to