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 6945a3f502370fb92cc7f1ea53a5750fef31a91a
Author: Benoit TELLIER <[email protected]>
AuthorDate: Wed Nov 18 22:34:45 2026 +0100

    [FIX] Redirect: bound the addresses an evaluation redirects to
    
    redirect added an action each time it ran, with no limit: a mailbox
    user uploading a script of thousands of redirect lines made every mail
    they received send a copy per line, to third parties of their choice
    or many times to the same one, from the server.
    
    An evaluation now redirects once to each address, addresses differing
    only by the case of their domain being the same, the local part being
    case-sensitive (RFC 5321 section 2.4), and to at most a number of
    distinct addresses, 32 by default (SieveFactory#DEFAULT_MAX_REDIRECTS):
    beyond, the evaluation fails with a SieveException and none of its
    actions is executed. The limit is set through
    ConfigurationManager#setMaxRedirects or the SieveFactory constructor. A
    SieveContext not built by SieveFactory does not limit redirects, as it
    does not limit comparisons.
---
 .../java/org/apache/jsieve/BaseSieveContext.java   |  28 ++++
 .../org/apache/jsieve/CommandStateManager.java     |  31 +++++
 .../org/apache/jsieve/ConfigurationManager.java    |  17 ++-
 .../main/java/org/apache/jsieve/SieveContext.java  |  10 ++
 .../main/java/org/apache/jsieve/SieveFactory.java  |  33 ++++-
 .../java/org/apache/jsieve/commands/Redirect.java  |  13 ++
 .../java/org/apache/jsieve/RedirectLimitTest.java  | 154 +++++++++++++++++++++
 7 files changed, 284 insertions(+), 2 deletions(-)

diff --git a/core/src/main/java/org/apache/jsieve/BaseSieveContext.java 
b/core/src/main/java/org/apache/jsieve/BaseSieveContext.java
index 566ac2c..65fcd9d 100644
--- a/core/src/main/java/org/apache/jsieve/BaseSieveContext.java
+++ b/core/src/main/java/org/apache/jsieve/BaseSieveContext.java
@@ -40,6 +40,8 @@ public class BaseSieveContext extends SieveContext {
 
     private long remainingComparisonBudget;
 
+    private final int maxRedirects;
+
     public BaseSieveContext(final CommandManager commandManager,
                             final ComparatorManager comparatorManager,
                             final TestManager testManager) {
@@ -54,10 +56,28 @@ public class BaseSieveContext extends SieveContext {
                             final ComparatorManager comparatorManager,
                             final TestManager testManager,
                             final long comparisonBudget) {
+        this(commandManager, comparatorManager, testManager, comparisonBudget, 
Integer.MAX_VALUE);
+    }
+
+    /**
+     * @param comparisonBudget the number of characters the comparisons of an
+     * evaluation may compare, see {@link #chargeComparison(long)}
+     * @param maxRedirects the number of distinct addresses an evaluation may
+     * redirect the mail to, see {@link #getMaxRedirects()}
+     */
+    public BaseSieveContext(final CommandManager commandManager,
+                            final ComparatorManager comparatorManager,
+                            final TestManager testManager,
+                            final long comparisonBudget,
+                            final int maxRedirects) {
         if (comparisonBudget < 0) {
             throw new IllegalArgumentException("The comparison budget cannot 
be negative");
         }
+        if (maxRedirects < 0) {
+            throw new IllegalArgumentException("The maximum number of 
redirects cannot be negative");
+        }
         this.remainingComparisonBudget = comparisonBudget;
+        this.maxRedirects = maxRedirects;
         this.commandStateManager = new CommandStateManager();
         this.conditionManager = new ConditionManager();
         this.testManager = testManager;
@@ -133,6 +153,14 @@ public class BaseSieveContext extends SieveContext {
         return testManager;
     }
 
+    /**
+     * @see SieveContext#getMaxRedirects()
+     */
+    @Override
+    public int getMaxRedirects() {
+        return maxRedirects;
+    }
+
     /**
      * @see SieveContext#chargeComparison(long)
      */
diff --git a/core/src/main/java/org/apache/jsieve/CommandStateManager.java 
b/core/src/main/java/org/apache/jsieve/CommandStateManager.java
index 43ca621..9ec4e6c 100644
--- a/core/src/main/java/org/apache/jsieve/CommandStateManager.java
+++ b/core/src/main/java/org/apache/jsieve/CommandStateManager.java
@@ -19,6 +19,10 @@
 
 package org.apache.jsieve;
 
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+
 /**
  * Thread singleton class CommandStateManager records the state of a Sieve
  * evaluation.
@@ -50,6 +54,11 @@ public class CommandStateManager {
      */
     private boolean vacationProcessed = false;
 
+    /**
+     * The addresses redirected to, their domain lower-cased
+     */
+    private final Set<String> redirectAddresses = new HashSet<>();
+
     /**
      * Constructor for CommandStateManager.
      */
@@ -160,4 +169,26 @@ public class CommandStateManager {
     public void setVacationProcessed(boolean vacationProcessed) {
         this.vacationProcessed = vacationProcessed;
     }
+
+    /**
+     * Records a redirect to the address. Addresses differing only by the case
+     * of their domain are the same: the local part is case-sensitive (RFC
+     * 5321 section 2.4).
+     *
+     * @param address not null
+     * @return false when the evaluation already redirected to the address
+     */
+    public boolean addRedirect(String address) {
+        final int at = address.lastIndexOf('@');
+        final String key = at < 0 ? address
+                : address.substring(0, at) + 
address.substring(at).toLowerCase(Locale.ROOT);
+        return redirectAddresses.add(key);
+    }
+
+    /**
+     * @return the number of distinct addresses the evaluation redirected to
+     */
+    public int getRedirectCount() {
+        return redirectAddresses.size();
+    }
 }
diff --git a/core/src/main/java/org/apache/jsieve/ConfigurationManager.java 
b/core/src/main/java/org/apache/jsieve/ConfigurationManager.java
index 3389c1b..41fd84d 100644
--- a/core/src/main/java/org/apache/jsieve/ConfigurationManager.java
+++ b/core/src/main/java/org/apache/jsieve/ConfigurationManager.java
@@ -99,6 +99,8 @@ public class ConfigurationManager {
 
     private long comparisonBudget = SieveFactory.DEFAULT_COMPARISON_BUDGET;
 
+    private int maxRedirects = SieveFactory.DEFAULT_MAX_REDIRECTS;
+
     private static final Logger LOGGER = 
LoggerFactory.getLogger(ConfigurationManager.class);
 
     /**
@@ -296,8 +298,21 @@ public class ConfigurationManager {
         this.comparisonBudget = comparisonBudget;
     }
 
+    /**
+     * Sets the number of distinct addresses a single evaluation may redirect
+     * the mail to, {@link SieveFactory#DEFAULT_MAX_REDIRECTS} by default.
+     *
+     * @param maxRedirects not negative
+     */
+    public void setMaxRedirects(int maxRedirects) {
+        if (maxRedirects < 0) {
+            throw new IllegalArgumentException("The maximum number of 
redirects cannot be negative");
+        }
+        this.maxRedirects = maxRedirects;
+    }
+
     public SieveFactory build() {
         return new SieveFactory(getCommandManager(), getComparatorManager(),
-                getTestManager(), comparisonBudget);
+                getTestManager(), comparisonBudget, maxRedirects);
     }
 }
diff --git a/core/src/main/java/org/apache/jsieve/SieveContext.java 
b/core/src/main/java/org/apache/jsieve/SieveContext.java
index f0109f8..de455eb 100644
--- a/core/src/main/java/org/apache/jsieve/SieveContext.java
+++ b/core/src/main/java/org/apache/jsieve/SieveContext.java
@@ -93,6 +93,16 @@ public abstract class SieveContext {
     public void chargeComparison(long cost) throws SieveException {
     }
 
+    /**
+     * Gets the number of distinct addresses an evaluation may redirect the
+     * mail to. By default, it is not limited.
+     *
+     * @return not negative
+     */
+    public int getMaxRedirects() {
+        return Integer.MAX_VALUE;
+    }
+
     /**
      * Raw header values already decoded, with their decoded value. A context
      * lives for one evaluation: this holds at most the header values of the
diff --git a/core/src/main/java/org/apache/jsieve/SieveFactory.java 
b/core/src/main/java/org/apache/jsieve/SieveFactory.java
index f38e07f..cebb917 100644
--- a/core/src/main/java/org/apache/jsieve/SieveFactory.java
+++ b/core/src/main/java/org/apache/jsieve/SieveFactory.java
@@ -83,6 +83,15 @@ public class SieveFactory {
 
     private final long comparisonBudget;
 
+    /**
+     * Default number of distinct addresses a single evaluation may redirect
+     * the mail to: each redirect sends a copy of the mail, a site policy
+     * limit as allowed by RFC 5228 section 2.10.4.
+     */
+    public static final int DEFAULT_MAX_REDIRECTS = 32;
+
+    private final int maxRedirects;
+
     /**
      * Constructor for SieveFactory, using the
      * {@link #DEFAULT_COMPARISON_BUDGET}.
@@ -104,14 +113,36 @@ public class SieveFactory {
             final ComparatorManager comparatorManager,
             final TestManager testManager,
             final long comparisonBudget) {
+        this(commandManager, comparatorManager, testManager, comparisonBudget, 
DEFAULT_MAX_REDIRECTS);
+    }
+
+    /**
+     * Constructor for SieveFactory.
+     *
+     * @param comparisonBudget the number of characters the comparisons of a
+     * single evaluation may compare. An evaluation going beyond fails
+     * with a {@link SieveException}.
+     * @param maxRedirects the number of distinct addresses a single
+     * evaluation may redirect the mail to. An evaluation going beyond fails
+     * with a {@link SieveException}, and none of its actions is executed.
+     */
+    public SieveFactory(final CommandManager commandManager,
+            final ComparatorManager comparatorManager,
+            final TestManager testManager,
+            final long comparisonBudget,
+            final int maxRedirects) {
         super();
         if (comparisonBudget < 0) {
             throw new IllegalArgumentException("The comparison budget cannot 
be negative");
         }
+        if (maxRedirects < 0) {
+            throw new IllegalArgumentException("The maximum number of 
redirects cannot be negative");
+        }
         this.commandManager = commandManager;
         this.comparatorManager = comparatorManager;
         this.testManager = testManager;
         this.comparisonBudget = comparisonBudget;
+        this.maxRedirects = maxRedirects;
     }
 
     /**
@@ -174,7 +205,7 @@ public class SieveFactory {
     public void evaluate(MailAdapter mail, Node startNode)
             throws SieveException {
         final SieveContext context = new BaseSieveContext(commandManager,
-                comparatorManager, testManager, comparisonBudget);
+                comparatorManager, testManager, comparisonBudget, 
maxRedirects);
         try {
             // Ensure that the context is set on the mail
             mail.setContext(context);
diff --git a/core/src/main/java/org/apache/jsieve/commands/Redirect.java 
b/core/src/main/java/org/apache/jsieve/commands/Redirect.java
index 3b8b999..85d5a56 100644
--- a/core/src/main/java/org/apache/jsieve/commands/Redirect.java
+++ b/core/src/main/java/org/apache/jsieve/commands/Redirect.java
@@ -21,6 +21,7 @@ package org.apache.jsieve.commands;
 
 import org.apache.jsieve.Arguments;
 import org.apache.jsieve.Block;
+import org.apache.jsieve.CommandStateManager;
 import org.apache.jsieve.SieveContext;
 import org.apache.jsieve.StringListArgument;
 import org.apache.jsieve.exception.SieveException;
@@ -57,6 +58,18 @@ public class Redirect extends AbstractActionCommand {
         String recipient = ((StringListArgument) arguments
                 .getArgumentList().get(0)).getList().get(0);
 
+        final CommandStateManager state = context.getCommandStateManager();
+        if (!state.addRedirect(recipient)) {
+            // The address already gets a copy of the mail
+            return null;
+        }
+        if (state.getRedirectCount() > context.getMaxRedirects()) {
+            // Each redirect sends a copy of the mail: site policy limits
+            // them (RFC 5228 section 2.10.4)
+            throw context.getCoordinate().commandException(
+                    "Too many redirect actions: at most " + 
context.getMaxRedirects()
+                    + " distinct addresses");
+        }
         mail.addAction(new ActionRedirect(recipient));
 
         return null;
diff --git a/core/src/test/java/org/apache/jsieve/RedirectLimitTest.java 
b/core/src/test/java/org/apache/jsieve/RedirectLimitTest.java
new file mode 100644
index 0000000..ef86795
--- /dev/null
+++ b/core/src/test/java/org/apache/jsieve/RedirectLimitTest.java
@@ -0,0 +1,154 @@
+/****************************************************************
+ * 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.jsieve;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.apache.jsieve.exception.SieveException;
+import org.apache.jsieve.mail.ActionKeep;
+import org.apache.jsieve.mail.ActionRedirect;
+import org.apache.jsieve.utils.JUnitUtils;
+import org.apache.jsieve.utils.SieveMailAdapter;
+import org.junit.Test;
+
+/**
+ * Each redirect sends a copy of the mail: an evaluation redirects to a
+ * bounded number of distinct addresses, and once to each.
+ */
+public class RedirectLimitTest {
+
+    @Test
+    public void redirectsUpToTheLimitShouldBeExecuted() throws Exception {
+        RecordingMailAdapter mail = new RecordingMailAdapter();
+
+        factoryWithMaxRedirects(3).interpret(mail, script(redirects(3)));
+
+        assertThat(mail.executed).isTrue();
+        
assertThat(mail.getActions()).hasSize(3).allMatch(ActionRedirect.class::isInstance);
+    }
+
+    @Test
+    public void 
redirectsBeyondTheLimitShouldFailTheEvaluationWithoutExecutingAnything() throws 
Exception {
+        RecordingMailAdapter mail = new RecordingMailAdapter();
+
+        assertThatThrownBy(() -> factoryWithMaxRedirects(3).interpret(mail, 
script(redirects(4))))
+            .isInstanceOf(SieveException.class)
+            .hasMessageContaining("Too many redirect");
+        assertThat(mail.executed).isFalse();
+    }
+
+    @Test
+    public void theDefaultLimitShouldApply() throws Exception {
+        RecordingMailAdapter mail = new RecordingMailAdapter();
+        String script = redirects(SieveFactory.DEFAULT_MAX_REDIRECTS + 1);
+
+        assertThatThrownBy(() -> new 
ConfigurationManager().build().interpret(mail, script(script)))
+            .isInstanceOf(SieveException.class)
+            .hasMessageContaining("Too many redirect");
+        assertThat(mail.executed).isFalse();
+    }
+
+    @Test
+    public void aRepeatedAddressShouldBeRedirectedToOnce() throws Exception {
+        SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
+        String script = "redirect \"[email protected]\";".repeat(1_000)
+            + "redirect \"[email protected]\";";
+
+        factoryWithMaxRedirects(1).interpret(mail, script(script));
+
+        
assertThat(mail.getActions()).singleElement().isInstanceOf(ActionRedirect.class);
+        assertThat(((ActionRedirect) 
mail.getActions().get(0)).getAddress()).isEqualTo("[email protected]");
+    }
+
+    @Test
+    public void localPartsDifferingByCaseShouldBeDistinctAddresses() throws 
Exception {
+        SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
+
+        factoryWithMaxRedirects(2).interpret(mail,
+            script("redirect \"[email protected]\"; redirect 
\"[email protected]\";"));
+
+        
assertThat(mail.getActions()).hasSize(2).allMatch(ActionRedirect.class::isInstance);
+    }
+
+    @Test
+    public void theLimitShouldBeCountedPerEvaluation() throws Exception {
+        SieveFactory factory = factoryWithMaxRedirects(2);
+
+        for (int i = 0; i < 3; i++) {
+            SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
+            factory.interpret(mail, script(redirects(2)));
+            assertThat(mail.getActions()).hasSize(2);
+        }
+    }
+
+    @Test
+    public void aZeroLimitShouldForbidRedirectsOnly() throws Exception {
+        SieveMailAdapter mail = (SieveMailAdapter) JUnitUtils.createMail();
+
+        factoryWithMaxRedirects(0).interpret(mail, script("keep;"));
+
+        
assertThat(mail.getActions()).singleElement().isInstanceOf(ActionKeep.class);
+        assertThatThrownBy(() -> factoryWithMaxRedirects(0)
+                .interpret(JUnitUtils.createMail(), script(redirects(1))))
+            .isInstanceOf(SieveException.class);
+    }
+
+    @Test
+    public void aNegativeLimitShouldBeRejected() {
+        assertThatThrownBy(() -> new 
ConfigurationManager().setMaxRedirects(-1))
+            .isInstanceOf(IllegalArgumentException.class);
+    }
+
+    private static class RecordingMailAdapter extends SieveMailAdapter {
+        private boolean executed;
+
+        RecordingMailAdapter() {
+            super(((SieveMailAdapter) JUnitUtils.createMail()).getMessage());
+        }
+
+        @Override
+        public void executeActions() throws SieveException {
+            executed = true;
+            super.executeActions();
+        }
+    }
+
+    private static String redirects(int count) {
+        return IntStream.range(0, count)
+            .mapToObj(i -> "redirect \"target" + i + "@example.org\";")
+            .collect(Collectors.joining(" "));
+    }
+
+    private static SieveFactory factoryWithMaxRedirects(int maxRedirects) 
throws Exception {
+        ConfigurationManager configurationManager = new ConfigurationManager();
+        configurationManager.setMaxRedirects(maxRedirects);
+        return configurationManager.build();
+    }
+
+    private static ByteArrayInputStream script(String script) {
+        return new 
ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8));
+    }
+}


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

Reply via email to