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


The following commit(s) were added to refs/heads/master by this push:
     new 2273f87  [FIX] Address, Header, Exists, Envelope: charge the header 
lookups and address parsing
2273f87 is described below

commit 2273f87ce30333e507266ed5d7853d8afef4bef4
Author: Benoit TELLIER <[email protected]>
AuthorDate: Wed Nov 25 09:22:03 2026 +0100

    [FIX] Address, Header, Exists, Envelope: charge the header lookups and 
address parsing
    
    The evaluation budget charged the comparisons only. The lookups of the
    headers and the parsing of the addresses, done once per key by address,
    were not charged.
    
    SieveContext now looks a header name up and parses its addresses once
    per evaluation, and charges the header names walked and the values read
    or parsed. Envelope looks an envelope part up once per test and charges
    it too.
---
 .../main/java/org/apache/jsieve/SieveContext.java  | 93 ++++++++++++++++++++++
 .../main/java/org/apache/jsieve/tests/Address.java | 15 ++--
 .../main/java/org/apache/jsieve/tests/Exists.java  |  2 +-
 .../main/java/org/apache/jsieve/tests/Header.java  |  4 +-
 .../org/apache/jsieve/tests/optional/Envelope.java | 29 ++++++-
 .../org/apache/jsieve/EvaluationBudgetTest.java    | 77 +++++++++++++++++-
 6 files changed, 203 insertions(+), 17 deletions(-)

diff --git a/core/src/main/java/org/apache/jsieve/SieveContext.java 
b/core/src/main/java/org/apache/jsieve/SieveContext.java
index de455eb..66afdee 100644
--- a/core/src/main/java/org/apache/jsieve/SieveContext.java
+++ b/core/src/main/java/org/apache/jsieve/SieveContext.java
@@ -20,10 +20,13 @@
 package org.apache.jsieve;
 
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 import org.apache.james.mime4j.util.MimeUtil;
+import org.apache.jsieve.exception.InternetAddressException;
 import org.apache.jsieve.exception.SieveException;
+import org.apache.jsieve.mail.MailAdapter;
 
 /**
  * Context for sieve operations.
@@ -126,4 +129,94 @@ public abstract class SieveContext {
         }
         return decodedHeaderValues.computeIfAbsent(rawValue, 
MimeUtil::unscrambleHeaderValue);
     }
+
+    /**
+     * Header values already looked up, by the header name of the script.
+     */
+    private Map<String, List<String>> matchingHeaders;
+
+    /**
+     * Addresses already parsed, by the header name of the script.
+     */
+    private Map<String, MailAdapter.Address[]> parsedAddresses;
+
+    /**
+     * The characters of the header names of the mail, plus one per name, or
+     * -1 before they are counted.
+     */
+    private long headerNamesLength = -1;
+
+    /**
+     * Looks up the values of the headers of the mail with the given name, see
+     * {@link MailAdapter#getMatchingHeader(String)}. A name is looked up once
+     * per context, that is per evaluation. A lookup is charged to the
+     * evaluation budget: the header names of the mail it walks, the name, and
+     * the values it returns.
+     *
+     * @param mail not null
+     * @param name not null
+     * @return the values, not null
+     * @throws SieveException when the budget is exhausted or the mail cannot 
be read
+     */
+    public List<String> getMatchingHeader(MailAdapter mail, String name) 
throws SieveException {
+        if (matchingHeaders == null) {
+            matchingHeaders = new HashMap<>();
+        }
+        List<String> values = matchingHeaders.get(name);
+        if (values == null) {
+            chargeComparison(headerNamesLength(mail) + name.length() + 1L);
+            values = mail.getMatchingHeader(name);
+            chargeComparison(length(values));
+            matchingHeaders.put(name, values);
+        }
+        return values;
+    }
+
+    /**
+     * Parses the addresses of the headers of the mail with the given name,
+     * see {@link MailAdapter#parseAddresses(String)}: none when they do not
+     * parse as address lists. A name is parsed once per context, that is per
+     * evaluation. A parse is charged to the evaluation budget: the header
+     * names of the mail it walks and the values it parses.
+     *
+     * @param mail not null
+     * @param headerName not null
+     * @return the addresses, not null
+     * @throws SieveException when the budget is exhausted or the mail cannot 
be read
+     */
+    public MailAdapter.Address[] parseAddresses(MailAdapter mail, String 
headerName) throws SieveException {
+        if (parsedAddresses == null) {
+            parsedAddresses = new HashMap<>();
+        }
+        MailAdapter.Address[] addresses = parsedAddresses.get(headerName);
+        if (addresses == null) {
+            final List<String> values = getMatchingHeader(mail, headerName);
+            chargeComparison(headerNamesLength(mail) + length(values));
+            try {
+                addresses = mail.parseAddresses(headerName);
+            } catch (InternetAddressException e) {
+                addresses = new MailAdapter.Address[0];
+            }
+            parsedAddresses.put(headerName, addresses);
+        }
+        return addresses;
+    }
+
+    private long headerNamesLength(MailAdapter mail) throws SieveException {
+        if (headerNamesLength < 0) {
+            final List<String> headerNames = mail.getHeaderNames();
+            final long length = length(headerNames);
+            chargeComparison(length);
+            headerNamesLength = length;
+        }
+        return headerNamesLength;
+    }
+
+    private static long length(List<String> strings) {
+        long length = 0;
+        for (String string : strings) {
+            length += string.length() + 1L;
+        }
+        return length;
+    }
 }
diff --git a/core/src/main/java/org/apache/jsieve/tests/Address.java 
b/core/src/main/java/org/apache/jsieve/tests/Address.java
index ae5de9c..2ef4f88 100644
--- a/core/src/main/java/org/apache/jsieve/tests/Address.java
+++ b/core/src/main/java/org/apache/jsieve/tests/Address.java
@@ -23,10 +23,8 @@ import static 
org.apache.jsieve.tests.AddressPartTags.LOCALPART_TAG;
 
 import org.apache.jsieve.SieveContext;
 import org.apache.jsieve.comparators.ComparatorUtils;
-import org.apache.jsieve.exception.InternetAddressException;
 import org.apache.jsieve.exception.SieveException;
 import org.apache.jsieve.mail.MailAdapter;
-import org.apache.jsieve.mail.SieveMailException;
 
 /**
  * Class Address implements the Addresss Test as defined in RFC 3028, section
@@ -43,7 +41,7 @@ public class Address extends AbstractComparatorTest {
     protected boolean match(MailAdapter mail, String addressPart,
             String comparator, String matchType, String headerName, String key,
             SieveContext context) throws SieveException {
-        final MailAdapter.Address[] addresses = getMatchingValues(mail, 
headerName);
+        final MailAdapter.Address[] addresses = getMatchingValues(mail, 
headerName, context);
         final int length = addresses.length;
         int i = 0;
         boolean isMatched = false;
@@ -57,15 +55,12 @@ public class Address extends AbstractComparatorTest {
     /**
      * The addresses of the header, none when its value does not parse as an
      * address list: an address that is not syntactically valid is not matched
-     * (RFC 5228 section 2.7.4), whatever the address part.
+     * (RFC 5228 section 2.7.4), whatever the address part. The header is
+     * parsed once per evaluation, whatever the number of keys.
      */
     private MailAdapter.Address[] getMatchingValues(MailAdapter mail,
-            String valueName) throws SieveMailException {
-        try {
-            return mail.parseAddresses(valueName);
-        } catch (InternetAddressException e) {
-            return new MailAdapter.Address[0];
-        }
+            String valueName, SieveContext context) throws SieveException {
+        return context.parseAddresses(mail, valueName);
     }
 
     protected boolean match(String addressPart, String comparator,
diff --git a/core/src/main/java/org/apache/jsieve/tests/Exists.java 
b/core/src/main/java/org/apache/jsieve/tests/Exists.java
index 3e9225b..f3dc828 100644
--- a/core/src/main/java/org/apache/jsieve/tests/Exists.java
+++ b/core/src/main/java/org/apache/jsieve/tests/Exists.java
@@ -52,7 +52,7 @@ public class Exists extends AbstractTest {
         
         boolean found = true;
         for (final String arg:argumentList) {
-            List<String> headers = mail.getMatchingHeader(arg);
+            List<String> headers = context.getMatchingHeader(mail, arg);
             found = !headers.isEmpty();
             if (!found) {
                 break;
diff --git a/core/src/main/java/org/apache/jsieve/tests/Header.java 
b/core/src/main/java/org/apache/jsieve/tests/Header.java
index 7097184..b4b4535 100644
--- a/core/src/main/java/org/apache/jsieve/tests/Header.java
+++ b/core/src/main/java/org/apache/jsieve/tests/Header.java
@@ -197,8 +197,8 @@ public class Header extends AbstractTest {
         boolean isMatched = false;
         Iterator headerNamesIter = headerNames.iterator();
         while (!isMatched && headerNamesIter.hasNext()) {
-            isMatched = match(comparator, matchType, mail
-                    .getMatchingHeader((String) headerNamesIter.next()), keys,
+            isMatched = match(comparator, matchType, context
+                    .getMatchingHeader(mail, (String) headerNamesIter.next()), 
keys,
                     context);
         }
         return isMatched;
diff --git a/core/src/main/java/org/apache/jsieve/tests/optional/Envelope.java 
b/core/src/main/java/org/apache/jsieve/tests/optional/Envelope.java
index a82c379..0979125 100644
--- a/core/src/main/java/org/apache/jsieve/tests/optional/Envelope.java
+++ b/core/src/main/java/org/apache/jsieve/tests/optional/Envelope.java
@@ -370,7 +370,12 @@ public class Envelope extends AbstractComparatorTest {
     protected boolean match(MailAdapter mail, String addressPart,
             String comparator, String matchType, String headerName, String key,
             SieveContext context) throws SieveException {
-        final List<String> headerValues = getMatchingValues(mail, headerName);
+        return match(addressPart, comparator, matchType,
+                getMatchingValues(mail, headerName), key, context);
+    }
+
+    private boolean match(String addressPart, String comparator, String 
matchType,
+            List<String> headerValues, String key, SieveContext context) 
throws SieveException {
         boolean isMatched = false;
         for (final String value:headerValues) {
             isMatched = match(addressPart, comparator, matchType, value, key, 
context);
@@ -381,4 +386,26 @@ public class Envelope extends AbstractComparatorTest {
         return isMatched;
     }
 
+    /**
+     * Looks the envelope part up once, whatever the number of keys, and
+     * charges the lookup to the evaluation budget: the name and the values.
+     */
+    @Override
+    protected boolean match(MailAdapter mail, String addressPart,
+            String comparator, String matchType, String headerName, 
List<String> keys,
+            SieveContext context) throws SieveException {
+        final List<String> headerValues = getMatchingValues(mail, headerName);
+        long length = headerName.length() + 1L;
+        for (final String value:headerValues) {
+            length += value.length() + 1L;
+        }
+        context.chargeComparison(length);
+        for (final String key:keys) {
+            if (match(addressPart, comparator, matchType, headerValues, key, 
context)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
 }
diff --git a/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java 
b/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java
index ffa14b5..cfa7a9c 100644
--- a/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java
+++ b/core/src/test/java/org/apache/jsieve/EvaluationBudgetTest.java
@@ -25,6 +25,7 @@ import static 
org.assertj.core.api.Assertions.assertThatThrownBy;
 
 import java.io.ByteArrayInputStream;
 import java.nio.charset.StandardCharsets;
+import java.util.Collections;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
@@ -125,6 +126,56 @@ public class EvaluationBudgetTest {
         
assertThat(mail.getActions()).singleElement().isInstanceOf(ActionDiscard.class);
     }
 
+    @Test
+    public void theParseOfAnAddressHeaderShouldBeCharged() throws Exception {
+        SieveMailAdapter mail = mailWithFrom("(" + "a".repeat(1_000_000) + ") 
<");
+        String script = "if address :all \"From\" \"key\" { discard; }";
+
+        assertThatThrownBy(() -> factoryWithBudget(1_000_000).interpret(mail, 
script(script)))
+            .isInstanceOf(SieveException.class)
+            .hasMessageContaining("budget");
+    }
+
+    @Test
+    public void anAddressHeaderShouldBeParsedOnceWhateverTheNumberOfKeys() 
throws Exception {
+        SieveMailAdapter mail = mailWithFrom("(" + "a".repeat(100_000) + ") 
<");
+        String script = "if address :all \"From\" [" + keys(10_000) + "] { 
discard; }";
+
+        factoryWithBudget(1_000_000).interpret(mail, script(script));
+
+        
assertThat(mail.getActions()).singleElement().isInstanceOf(ActionKeep.class);
+    }
+
+    @Test
+    public void theHeaderLookupsOfExistsShouldBeCharged() throws Exception {
+        SieveMailAdapter mail = mailWithHeaders(10_000);
+        String script = "if exists [" + headerNames(10_000) + "] { discard; }";
+
+        assertThatThrownBy(() -> factoryWithBudget(10_000_000).interpret(mail, 
script(script)))
+            .isInstanceOf(SieveException.class)
+            .hasMessageContaining("budget");
+    }
+
+    @Test
+    public void theHeaderLookupsOfHeaderShouldBeCharged() throws Exception {
+        SieveMailAdapter mail = mailWithHeaders(10_000);
+        String script = "if header :is [" + 
headerNames(10_000).replace("X-Header-", "X-Absent-") + "] \"key\" { discard; 
}";
+
+        assertThatThrownBy(() -> factoryWithBudget(10_000_000).interpret(mail, 
script(script)))
+            .isInstanceOf(SieveException.class)
+            .hasMessageContaining("budget");
+    }
+
+    @Test
+    public void aHeaderNameShouldBeLookedUpOncePerEvaluation() throws 
Exception {
+        SieveMailAdapter mail = mailWithHeaders(10_000);
+        String script = "if exists [" + String.join(", ", 
Collections.nCopies(10_000, "\"X-Header-1\"")) + "] { discard; }";
+
+        factoryWithBudget(10_000_000).interpret(mail, script(script));
+
+        
assertThat(mail.getActions()).singleElement().isInstanceOf(ActionDiscard.class);
+    }
+
     @Test
     public void theGlobMatcherShouldBeChargedTheCharactersItComparesAgain() 
throws Exception {
         // Each of the ~1000 attempts compares up to 100 characters before 
failing
@@ -185,7 +236,7 @@ public class EvaluationBudgetTest {
     public void comparisonsWithinTheBudgetShouldBeEvaluated() throws Exception 
{
         SieveMailAdapter mail = mailWithSubject("Gone for holidays");
 
-        factoryWithBudget(40).interpret(mail, script(CONTAINS_SCRIPT));
+        factoryWithBudget(70).interpret(mail, script(CONTAINS_SCRIPT));
 
         
assertThat(mail.getActions()).singleElement().isInstanceOf(ActionDiscard.class);
     }
@@ -204,14 +255,14 @@ public class EvaluationBudgetTest {
         SieveMailAdapter mail = mailWithSubject("Gone for holidays");
         String script = CONTAINS_SCRIPT + CONTAINS_SCRIPT;
 
-        assertThatThrownBy(() -> factoryWithBudget(40).interpret(mail, 
script(script)))
+        assertThatThrownBy(() -> factoryWithBudget(70).interpret(mail, 
script(script)))
             .isInstanceOf(SieveException.class)
             .hasMessageContaining("budget");
     }
 
     @Test
     public void theBudgetShouldBeRenewedForEachEvaluation() throws Exception {
-        SieveFactory factory = factoryWithBudget(40);
+        SieveFactory factory = factoryWithBudget(70);
 
         for (int i = 0; i < 3; i++) {
             SieveMailAdapter mail = mailWithSubject("Gone for holidays");
@@ -259,6 +310,26 @@ public class EvaluationBudgetTest {
         return (SieveMailAdapter) JUnitUtils.copyMail(mail);
     }
 
+    private static String headerNames(int count) {
+        return IntStream.range(0, count)
+            .mapToObj(i -> "\"X-Header-" + i + "\"")
+            .collect(Collectors.joining(", "));
+    }
+
+    private static SieveMailAdapter mailWithFrom(String from) throws Exception 
{
+        SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
+        mail.getMessage().setHeader("From", from);
+        return mail;
+    }
+
+    private static SieveMailAdapter mailWithHeaders(int count) throws 
Exception {
+        SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
+        for (int i = 0; i < count; i++) {
+            mail.getMessage().addHeader("X-Header-" + i, "value");
+        }
+        return mail;
+    }
+
     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