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

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

commit 9e94b3ff52f1da5fba0347bf9beedb4413f22973
Author: Benoit TELLIER <[email protected]>
AuthorDate: Tue Nov 10 09:26:39 2026 +0100

    [FIX] SPF: limit the time of a check and the void lookups
    
    A check had no time limit: FutureSPFResult waited with no deadline and
    SynchronousSPFExecutor ran every lookup in sequence on the calling
    thread. A record of 10 mx terms, each of 10 names, makes about 111
    lookups, which an authoritative server under the sender's control can
    each delay to just under the resolver timeout: one MAIL FROM held an
    SMTP thread for minutes. Nor were void lookups limited (RFC 7208 4.6.4,
    "SHOULD limit "void lookups" to two").
    
    Time: SPF.setTimeBudget, 20 seconds by default (RFC 7208 4.6.4, "at
    least 20 seconds"), sets a deadline in SPFSession, which the three
    executors check before each lookup: once it is spent, the check gives
    temperror. FutureSPFResult.getResult(timeout, unit) waits at most the
    given time, then gives temperror.
    
    Void lookups: SPFSession counts the lookup of an a, mx, ptr or exists
    term that answers NXDOMAIN or no record, and gives permerror beyond
    SPF.setMaxVoidLookups, 2 by default. Only the lookup of the term
    counts, not the address lookups of the MX or PTR names: an MX host
    without AAAA for an IPv6 client is common. An include or redirect
    without record is already a permerror. An a term whose target is not a
    valid name makes no lookup and no longer counts as one.
    
    The RFC 4408 suites, which predate the void limit, check the limit of
    10 terms with names without records: run them without the void limit.
    The lookup limit tests of %{p} give their a terms an address.
---
 .../org/apache/james/jspf/core/SPFSession.java     |  63 ++++++++++++
 .../jspf/executor/AsynchronousSPFExecutor.java     |   8 ++
 .../james/jspf/executor/FutureSPFResult.java       |  39 ++++++++
 .../jspf/executor/StagedMultipleSPFExecutor.java   |  13 ++-
 .../jspf/executor/SynchronousSPFExecutor.java      |   2 +
 .../main/java/org/apache/james/jspf/impl/SPF.java  |  33 ++++++
 .../org/apache/james/jspf/terms/AMechanism.java    |   5 +-
 .../apache/james/jspf/terms/ExistsMechanism.java   |   1 +
 .../org/apache/james/jspf/terms/MXMechanism.java   |   2 +
 .../org/apache/james/jspf/terms/PTRMechanism.java  |   2 +
 .../org/apache/james/jspf/AbstractYamlTest.java    |   9 ++
 .../org/apache/james/jspf/RFC4408YamlTest.java     |   8 ++
 .../org/apache/james/jspf/SPFExecutorBaseTest.java | 111 +++++++++++++++++++--
 .../james/jspf/executor/FutureSPFResultTest.java   |  49 +++++++++
 14 files changed, 336 insertions(+), 9 deletions(-)

diff --git a/resolver/src/main/java/org/apache/james/jspf/core/SPFSession.java 
b/resolver/src/main/java/org/apache/james/jspf/core/SPFSession.java
index bca2cb4..a88147b 100644
--- a/resolver/src/main/java/org/apache/james/jspf/core/SPFSession.java
+++ b/resolver/src/main/java/org/apache/james/jspf/core/SPFSession.java
@@ -21,6 +21,7 @@
 package org.apache.james.jspf.core;
 
 import org.apache.james.jspf.core.exceptions.PermErrorException;
+import org.apache.james.jspf.core.exceptions.TempErrorException;
 import org.xbill.DNS.Name;
 import org.xbill.DNS.TextParseException;
 
@@ -29,6 +30,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Stack;
+import java.util.concurrent.TimeUnit;
 import java.util.function.Predicate;
 
 /**
@@ -114,6 +116,20 @@ public class SPFSession implements MacroData {
      */
     public static final int MAX_DEPTH = 10;
 
+    /**
+     * The default limit of void lookups, RFC 7208 4.6.4
+     */
+    public static final int DEFAULT_MAX_VOID_LOOKUPS = 2;
+
+    private int voidLookups = 0;
+
+    private int maxVoidLookups = DEFAULT_MAX_VOID_LOOKUPS;
+
+    // the System.nanoTime() after which no lookup is made, when hasDeadline
+    private long deadline;
+
+    private boolean hasDeadline = false;
+
     private String explanation = null;
 
     private String currentResult = null;
@@ -321,6 +337,53 @@ public class SPFSession implements MacroData {
                         + currentDepth);
     }
 
+    /**
+     * Set the limit of void lookups, a negative limit for none
+     *
+     * @param maxVoidLookups the number of void lookups allowed
+     */
+    public void setMaxVoidLookups(int maxVoidLookups) {
+        this.maxVoidLookups = maxVoidLookups;
+    }
+
+    /**
+     * Count the answer of the lookup a term makes: a void lookup, NXDOMAIN or 
no answer, beyond the limit is a
+     * PermErrorException. See RFC 7208 4.6.4
+     *
+     * @param records the answer of the lookup, null when the name does not 
exist
+     */
+    public void countVoidLookup(List<String> records) throws 
PermErrorException {
+        if (records != null && !records.isEmpty()) {
+            return;
+        }
+        voidLookups++;
+        if (maxVoidLookups >= 0 && voidLookups > maxVoidLookups) {
+            throw new PermErrorException("Maximum void lookups done: " + 
voidLookups);
+        }
+    }
+
+    /**
+     * Set the time the check may take from now: once it is spent, the next 
DNS lookup is a TempErrorException.
+     * See RFC 7208 4.6.4
+     *
+     * @param timeBudgetMillis the time in milliseconds, 0 or less for no limit
+     */
+    public void setTimeBudget(long timeBudgetMillis) {
+        this.hasDeadline = timeBudgetMillis > 0;
+        this.deadline = System.nanoTime() + 
TimeUnit.MILLISECONDS.toNanos(timeBudgetMillis);
+    }
+
+    /**
+     * Called by the executors before each DNS lookup
+     *
+     * @throws TempErrorException once the time budget of the check is spent
+     */
+    public void checkTimeBudget() throws TempErrorException {
+        if (hasDeadline && System.nanoTime() - deadline >= 0) {
+            throw new TempErrorException("Time budget of the SPF check spent");
+        }
+    }
+
     /**
      * Set the currentDomain
      * 
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/executor/AsynchronousSPFExecutor.java
 
b/resolver/src/main/java/org/apache/james/jspf/executor/AsynchronousSPFExecutor.java
index cef29e6..91a2a8f 100644
--- 
a/resolver/src/main/java/org/apache/james/jspf/executor/AsynchronousSPFExecutor.java
+++ 
b/resolver/src/main/java/org/apache/james/jspf/executor/AsynchronousSPFExecutor.java
@@ -35,6 +35,7 @@ import org.apache.james.jspf.core.SPFCheckerExceptionCatcher;
 import org.apache.james.jspf.core.SPFSession;
 import org.apache.james.jspf.core.exceptions.SPFErrorConstants;
 import org.apache.james.jspf.core.exceptions.SPFResultException;
+import org.apache.james.jspf.core.exceptions.TempErrorException;
 import org.apache.james.jspf.core.exceptions.TimeoutException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -93,6 +94,13 @@ public class AsynchronousSPFExecutor implements SPFExecutor {
 
     private void handleCont(SPFSession session, FutureSPFResult result, 
DNSLookupContinuation cont, SPFChecker checker) {
         if (cont != null) {
+            try {
+                // RFC 7208 4.6.4: a check whose time budget is spent is a 
temperror
+                session.checkTimeBudget();
+            } catch (TempErrorException e) {
+                handleErrorAndComplete(session, result, e);
+                return;
+            }
             // if the checker returns a continuation we return it
             lookUp(cont.getRequest())
                 .thenAccept(results -> onResponse(session, result, cont, new 
DNSResponse(results), checker))
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/executor/FutureSPFResult.java 
b/resolver/src/main/java/org/apache/james/jspf/executor/FutureSPFResult.java
index e1ab25d..a495de9 100644
--- a/resolver/src/main/java/org/apache/james/jspf/executor/FutureSPFResult.java
+++ b/resolver/src/main/java/org/apache/james/jspf/executor/FutureSPFResult.java
@@ -22,8 +22,10 @@ package org.apache.james.jspf.executor;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.james.jspf.core.SPFSession;
+import org.apache.james.jspf.core.exceptions.SPFErrorConstants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -95,6 +97,43 @@ public class FutureSPFResult extends SPFResult {
         }
     }
 
+    /**
+     * Waits until the SPFResult is set, at most the given time
+     *
+     * @return true if the SPFResult is set
+     */
+    private synchronized boolean checkReady(long timeout, TimeUnit unit) {
+        long deadline = System.nanoTime() + unit.toNanos(timeout);
+        while (!isReady) {
+            long remaining = deadline - System.nanoTime();
+            if (remaining <= 0) {
+                return false;
+            }
+            try {
+                waiters++;
+                TimeUnit.NANOSECONDS.timedWait(this, remaining);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                return isReady;
+            } finally {
+                waiters--;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Waits for the result at most the given time
+     *
+     * @return the result, or temperror if it is not set in time (RFC 7208 
4.6.4)
+     */
+    public String getResult(long timeout, TimeUnit unit) {
+        if (!checkReady(timeout, unit)) {
+            return SPFErrorConstants.TEMP_ERROR_CONV;
+        }
+        return super.getResult();
+    }
+
     /**
      * @see org.apache.james.jspf.executor.SPFResult#getExplanation()
      */
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/executor/StagedMultipleSPFExecutor.java
 
b/resolver/src/main/java/org/apache/james/jspf/executor/StagedMultipleSPFExecutor.java
index 8bfa696..87fd221 100644
--- 
a/resolver/src/main/java/org/apache/james/jspf/executor/StagedMultipleSPFExecutor.java
+++ 
b/resolver/src/main/java/org/apache/james/jspf/executor/StagedMultipleSPFExecutor.java
@@ -31,6 +31,7 @@ import org.apache.james.jspf.core.SPFCheckerExceptionCatcher;
 import org.apache.james.jspf.core.SPFSession;
 import org.apache.james.jspf.core.exceptions.SPFErrorConstants;
 import org.apache.james.jspf.core.exceptions.SPFResultException;
+import org.apache.james.jspf.core.exceptions.TempErrorException;
 import org.apache.james.jspf.core.exceptions.TimeoutException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -178,6 +179,13 @@ public class StagedMultipleSPFExecutor implements 
SPFExecutor, Runnable {
         sessions.put(new Integer(nextId), session);
         results.put(new Integer(nextId), result);
         session.setAttribute(ATTRIBUTE_STAGED_EXECUTOR_CONTINUATION, cont);
+        try {
+            // RFC 7208 4.6.4: a check whose time budget is spent is a 
temperror
+            session.checkTimeBudget();
+        } catch (TempErrorException e) {
+            responseQueue.insertResponse(new IResponseImpl(new 
Integer(nextId), e));
+            return;
+        }
         try {
             dnsProbe.getRecordsAsynch(cont.getRequest(), nextId, 
responseQueue);
         } catch (RuntimeException e) {
@@ -221,7 +229,10 @@ public class StagedMultipleSPFExecutor implements 
SPFExecutor, Runnable {
         DNSLookupContinuation cont = (DNSLookupContinuation) 
session.getAttribute(ATTRIBUTE_STAGED_EXECUTOR_CONTINUATION);
         try {
             DNSResponse response;
-            if (resp.getException() instanceof TimeoutException) {
+            if (resp.getException() instanceof TempErrorException) {
+                // the time budget of the check is spent
+                throw (TempErrorException) resp.getException();
+            } else if (resp.getException() instanceof TimeoutException) {
                 response = new DNSResponse((TimeoutException) 
resp.getException());
             } else if (resp.getException() != null) {
                 // a lookup error, as dnsjava's on an answer it cannot handle: 
temperror (RFC 7208 4.4)
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/executor/SynchronousSPFExecutor.java
 
b/resolver/src/main/java/org/apache/james/jspf/executor/SynchronousSPFExecutor.java
index d1fd264..ca793f3 100644
--- 
a/resolver/src/main/java/org/apache/james/jspf/executor/SynchronousSPFExecutor.java
+++ 
b/resolver/src/main/java/org/apache/james/jspf/executor/SynchronousSPFExecutor.java
@@ -54,6 +54,8 @@ public class SynchronousSPFExecutor implements SPFExecutor {
                 DNSLookupContinuation cont = checker.checkSPF(session);
                 // if the checker returns a continuation we return it
                 while (cont != null) {
+                    // RFC 7208 4.6.4: a check whose time budget is spent is a 
temperror
+                    session.checkTimeBudget();
                     DNSResponse response;
                     try {
                         response = new DNSResponse(dnsProbe.getRecords(cont
diff --git a/resolver/src/main/java/org/apache/james/jspf/impl/SPF.java 
b/resolver/src/main/java/org/apache/james/jspf/impl/SPF.java
index 8b4f264..aae949a 100644
--- a/resolver/src/main/java/org/apache/james/jspf/impl/SPF.java
+++ b/resolver/src/main/java/org/apache/james/jspf/impl/SPF.java
@@ -232,6 +232,15 @@ public class SPF implements SPFChecker {
 
     private SPFExecutor executor;
 
+    /**
+     * RFC 7208 4.6.4: "at least 20 seconds"
+     */
+    public static final long DEFAULT_TIME_BUDGET_MILLIS = 20000;
+
+    private long timeBudgetMillis = DEFAULT_TIME_BUDGET_MILLIS;
+
+    private int maxVoidLookups = SPFSession.DEFAULT_MAX_VOID_LOOKUPS;
+
     /**
      * Creates an instance with the provided dnsService and executor.
      *
@@ -349,6 +358,10 @@ public class SPF implements SPFChecker {
 
         // Setup the data
         spfData = new SPFSession(mailFrom, hostName, ipAddress);
+        synchronized (this) {
+            spfData.setMaxVoidLookups(maxVoidLookups);
+            spfData.setTimeBudget(timeBudgetMillis);
+        }
       
 
         SPFChecker resultHandler = new DefaultSPFChecker();
@@ -444,6 +457,26 @@ public class SPF implements SPFChecker {
         dnsProbe.setTimeOut(timeOut);
     }
     
+    /**
+     * Set the time a whole check may take, in milliseconds: once it is spent, 
the check gives temperror before its
+     * next DNS lookup (RFC 7208 4.6.4). The default is 20 seconds, 0 or less 
for no limit.
+     *
+     * @param timeBudgetMillis the time in milliseconds
+     */
+    public synchronized void setTimeBudget(long timeBudgetMillis) {
+        this.timeBudgetMillis = timeBudgetMillis;
+    }
+
+    /**
+     * Set the number of void lookups, of a name that does not exist or has no 
record, allowed to the terms of a
+     * check: beyond it the check gives permerror (RFC 7208 4.6.4). The 
default is 2, a negative limit for none.
+     *
+     * @param maxVoidLookups the number of void lookups allowed
+     */
+    public synchronized void setMaxVoidLookups(int maxVoidLookups) {
+        this.maxVoidLookups = maxVoidLookups;
+    }
+
     /**
      * Set the default explanation which will be used if no explanation is 
found in the SPF Record
      *  
diff --git a/resolver/src/main/java/org/apache/james/jspf/terms/AMechanism.java 
b/resolver/src/main/java/org/apache/james/jspf/terms/AMechanism.java
index f5b4ba8..a32bbe8 100644
--- a/resolver/src/main/java/org/apache/james/jspf/terms/AMechanism.java
+++ b/resolver/src/main/java/org/apache/james/jspf/terms/AMechanism.java
@@ -82,7 +82,9 @@ public class AMechanism extends GenericMechanism implements 
SPFCheckerDNSRespons
                     DNSRequest request = new DNSRequest(host, validIPV4Address 
? DNSRequest.A : DNSRequest.AAAA);
                     return new DNSLookupContinuation(request, AMechanism.this);
                 } catch (NoneException e) {
-                    return onDNSResponse(new DNSResponse((List<String>) null), 
spfData);
+                    // the expanded target is not a valid domain name: no 
match, without a lookup
+                    spfData.setAttribute(Directive.ATTRIBUTE_MECHANISM_RESULT, 
Boolean.FALSE);
+                    return null;
                 }
             // PermError / TempError
             // TODO: Should we replace this with the "right" Exceptions ?
@@ -255,6 +257,7 @@ public class AMechanism extends GenericMechanism implements 
SPFCheckerDNSRespons
         } catch (TimeoutException e) {
             throw new TempErrorException("Timeout querying dns server");
         }
+        spfSession.countVoidLookup(listAData);
         // no a records just return null
         if (listAData == null) {
             spfSession.setAttribute(Directive.ATTRIBUTE_MECHANISM_RESULT, 
Boolean.FALSE);
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/terms/ExistsMechanism.java 
b/resolver/src/main/java/org/apache/james/jspf/terms/ExistsMechanism.java
index 1d4d912..d9e40cf 100644
--- a/resolver/src/main/java/org/apache/james/jspf/terms/ExistsMechanism.java
+++ b/resolver/src/main/java/org/apache/james/jspf/terms/ExistsMechanism.java
@@ -92,6 +92,7 @@ public class ExistsMechanism extends GenericMechanism 
implements SPFCheckerDNSRe
             // RFC 7208 5: a failed lookup of the target is a temperror, not a 
missing name
             throw new TempErrorException("Timeout querying dns server");
         }
+        spfSession.countVoidLookup(aRecords);
         
         if (aRecords != null && aRecords.size() > 0) {
             spfSession.setAttribute(Directive.ATTRIBUTE_MECHANISM_RESULT, 
Boolean.TRUE);
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/terms/MXMechanism.java 
b/resolver/src/main/java/org/apache/james/jspf/terms/MXMechanism.java
index cd33a6f..7675453 100644
--- a/resolver/src/main/java/org/apache/james/jspf/terms/MXMechanism.java
+++ b/resolver/src/main/java/org/apache/james/jspf/terms/MXMechanism.java
@@ -117,6 +117,8 @@ public class MXMechanism extends AMechanism implements 
DNSServiceEnabled, SPFChe
             if (records == null) {
             
                 records = response.getResponse();
+                // the MX lookup of the term, not the address lookups of its 
names
+                spfSession.countVoidLookup(records);
 
                 if (records == null) {
                     // no mx record found
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/terms/PTRMechanism.java 
b/resolver/src/main/java/org/apache/james/jspf/terms/PTRMechanism.java
index 374d799..6b5eb5f 100644
--- a/resolver/src/main/java/org/apache/james/jspf/terms/PTRMechanism.java
+++ b/resolver/src/main/java/org/apache/james/jspf/terms/PTRMechanism.java
@@ -147,6 +147,8 @@ public class PTRMechanism extends GenericMechanism 
implements DNSServiceEnabled,
             if (domainList == null) {
             
                 domainList = response.getResponse();
+                // the PTR lookup of the term, not the address lookups of its 
names
+                spfSession.countVoidLookup(domainList);
                 
                 // No PTR records found
                 if (domainList == null) {
diff --git a/resolver/src/test/java/org/apache/james/jspf/AbstractYamlTest.java 
b/resolver/src/test/java/org/apache/james/jspf/AbstractYamlTest.java
index fa977f8..12c1ed8 100644
--- a/resolver/src/test/java/org/apache/james/jspf/AbstractYamlTest.java
+++ b/resolver/src/test/java/org/apache/james/jspf/AbstractYamlTest.java
@@ -47,6 +47,7 @@ import org.apache.james.jspf.executor.SynchronousSPFExecutor;
 import org.apache.james.jspf.impl.DNSServiceAsynchSimulator;
 import org.apache.james.jspf.impl.DNSServiceXBillImpl;
 import org.apache.james.jspf.impl.DefaultTermsFactory;
+import org.apache.james.jspf.core.SPFSession;
 import org.apache.james.jspf.impl.SPF;
 import org.apache.james.jspf.parser.RFC4408SPF1Parser;
 import org.apache.james.jspf.tester.DNSTestingServer;
@@ -164,6 +165,7 @@ public abstract class AbstractYamlTest extends TestCase {
             throw new UnsupportedOperationException("Unknown executor type");
         }
         spf = new SPF(dns, parser, macroExpand, executor);
+        spf.setMaxVoidLookups(getMaxVoidLookups());
 
         if (test != null) {
             String next = test;
@@ -271,6 +273,13 @@ public abstract class AbstractYamlTest extends TestCase {
         }
     }
 
+    /**
+     * @return the limit of void lookups of the checks, RFC 7208 4.6.4
+     */
+    protected int getMaxVoidLookups() {
+        return SPFSession.DEFAULT_MAX_VOID_LOOKUPS;
+    }
+
     protected int getDnsServiceMockStyle() {
         return dnsServiceMockStyle;
     }
diff --git a/resolver/src/test/java/org/apache/james/jspf/RFC4408YamlTest.java 
b/resolver/src/test/java/org/apache/james/jspf/RFC4408YamlTest.java
index 32a0766..c915f8e 100644
--- a/resolver/src/test/java/org/apache/james/jspf/RFC4408YamlTest.java
+++ b/resolver/src/test/java/org/apache/james/jspf/RFC4408YamlTest.java
@@ -53,6 +53,14 @@ public class RFC4408YamlTest extends AbstractYamlTest {
         return YAMLFILE2;
     }
 
+    /**
+     * RFC 4408 has no limit of void lookups: its suites check the limit of 10 
terms with names without records, as
+     * mech-at-limit and include-at-limit
+     */
+    protected int getMaxVoidLookups() {
+        return -1;
+    }
+
     public static Test suite() throws IOException {
         return new RFC4408Suite();
     }
diff --git 
a/resolver/src/test/java/org/apache/james/jspf/SPFExecutorBaseTest.java 
b/resolver/src/test/java/org/apache/james/jspf/SPFExecutorBaseTest.java
index bd4e1c1..2cc5650 100644
--- a/resolver/src/test/java/org/apache/james/jspf/SPFExecutorBaseTest.java
+++ b/resolver/src/test/java/org/apache/james/jspf/SPFExecutorBaseTest.java
@@ -104,7 +104,8 @@ public abstract class SPFExecutorBaseTest {
     }
 
     // hostname has the record, and 1.2.3.4 the validated PTR name 
good.<hostname>: good.<hostname>._p.<hostname> exists,
-    // and good.<hostname>._exp.<hostname> holds the explanation "explained"
+    // and good.<hostname>._exp.<hostname> holds the explanation "explained". 
The names x<i>.<hostname> of
+    // aTermsOfAnotherAddress have the address 192.0.2.1
     private static FakeResolver pMacroRecord(String hostname, String record) 
throws IOException {
         String good = "good." + hostname;
         FakeResolver fakeResolver = new FakeResolver();
@@ -115,11 +116,15 @@ public abstract class SPFExecutorBaseTest {
         fakeResolver.addRecord(new ARecord(Name.fromString(good + "._p." + 
hostname + "."), DClass.IN, 30L,
             InetAddress.getByName("127.0.0.2")));
         fakeResolver.addRecord(new TXTRecord(Name.fromString(good + "._exp." + 
hostname + "."), DClass.IN, 30L, "explained"));
+        for (int i = 1; i <= 10; i++) {
+            fakeResolver.addRecord(new ARecord(Name.fromString("x" + i + "." + 
hostname + "."), DClass.IN, 30L,
+                InetAddress.getByName("192.0.2.1")));
+        }
         return fakeResolver;
     }
 
-    // the "a" terms of n names under hostname without address
-    private static String aTermsWithoutAddress(String hostname, int n) {
+    // the "a" terms of n names x<i>.<hostname>, which pMacroRecord gives 
another address than 1.2.3.4: not void lookups
+    private static String aTermsOfAnotherAddress(String hostname, int n) {
         return IntStream.rangeClosed(1, n).mapToObj(i -> "a:x" + i + "." + 
hostname).collect(Collectors.joining(" "));
     }
 
@@ -887,7 +892,7 @@ public abstract class SPFExecutorBaseTest {
         String hostname = "pmacrocount.spfexecutor.fake";
         // 9 a terms and exists: 10 terms that query DNS, then the PTR lookup 
of %{p}
         FakeResolver fakeResolver = pMacroRecord(hostname,
-            "v=spf1 " + aTermsWithoutAddress(hostname, 9) + " exists:%{p}._p." 
+ hostname + " -all");
+            "v=spf1 " + aTermsOfAnotherAddress(hostname, 9) + " 
exists:%{p}._p." + hostname + " -all");
 
         SPFResult result = createCustomSPF(new 
DNSServiceXBillImpl(fakeResolver)).checkSPF("1.2.3.4", "a_user@" + hostname, 
hostname);
 
@@ -900,7 +905,7 @@ public abstract class SPFExecutorBaseTest {
         String hostname = "pmacrowithin.spfexecutor.fake";
         // 8 a terms, exists and the PTR lookup of %{p}: 10
         FakeResolver fakeResolver = pMacroRecord(hostname,
-            "v=spf1 " + aTermsWithoutAddress(hostname, 8) + " exists:%{p}._p." 
+ hostname + " -all");
+            "v=spf1 " + aTermsOfAnotherAddress(hostname, 8) + " 
exists:%{p}._p." + hostname + " -all");
 
         SPFResult result = createCustomSPF(new 
DNSServiceXBillImpl(fakeResolver)).checkSPF("1.2.3.4", "a_user@" + hostname, 
hostname);
 
@@ -912,7 +917,7 @@ public abstract class SPFExecutorBaseTest {
         String hostname = "pmacroexp.spfexecutor.fake";
         // 10 a terms, then exp=, whose PTR lookup of %{p} comes after the 
check
         FakeResolver fakeResolver = pMacroRecord(hostname,
-            "v=spf1 " + aTermsWithoutAddress(hostname, 10) + " -all 
exp=%{p}._exp." + hostname);
+            "v=spf1 " + aTermsOfAnotherAddress(hostname, 10) + " -all 
exp=%{p}._exp." + hostname);
 
         SPFResult result = createCustomSPF(new 
DNSServiceXBillImpl(fakeResolver)).checkSPF("1.2.3.4", "a_user@" + hostname, 
hostname);
 
@@ -926,7 +931,7 @@ public abstract class SPFExecutorBaseTest {
         String hostname = "pmacroexptext.spfexecutor.fake";
         // 10 a terms, then the explanation "from %{p}", expanded after the 
check
         FakeResolver fakeResolver = pMacroRecord(hostname,
-            "v=spf1 " + aTermsWithoutAddress(hostname, 10) + " -all exp=e." + 
hostname);
+            "v=spf1 " + aTermsOfAnotherAddress(hostname, 10) + " -all exp=e." 
+ hostname);
         fakeResolver.addRecord(new TXTRecord(Name.fromString("e." + hostname + 
"."), DClass.IN, 30L, "from %{p}"));
 
         SPFResult result = createCustomSPF(new 
DNSServiceXBillImpl(fakeResolver)).checkSPF("1.2.3.4", "a_user@" + hostname, 
hostname);
@@ -1676,4 +1681,96 @@ public abstract class SPFExecutorBaseTest {
         // RFC 7208 5: a DNS error of a mechanism lookup is a temperror, the 
deny list does not fail open
         assertEquals(SPFErrorConstants.TEMP_ERROR_CONV, result.getResult());
     }
+
+    @Test(timeout = 10000)
+    public void shouldReturnPermErrorBeyondTwoVoidLookups() throws IOException 
{
+        String hostname = "voidOverLimit.spfexecutor.fake";
+        SPFResult result = checkRecord(hostname,
+            "v=spf1 a:n1." + hostname + " mx:n2." + hostname + " exists:n3." + 
hostname + " ip4:1.2.3.4 -all", "1.2.3.4");
+
+        // RFC 7208 4.6.4: "SHOULD limit "void lookups" to two"
+        assertEquals(SPFErrorConstants.PERM_ERROR_CONV, result.getResult());
+    }
+
+    @Test(timeout = 10000)
+    public void shouldAllowTwoVoidLookups() throws IOException {
+        String hostname = "voidAtLimit.spfexecutor.fake";
+        SPFResult result = checkRecord(hostname,
+            "v=spf1 a:n1." + hostname + " exists:n2." + hostname + " 
ip4:1.2.3.4 -all", "1.2.3.4");
+
+        assertEquals(SPFErrorConstants.PASS_CONV, result.getResult());
+    }
+
+    @Test(timeout = 10000)
+    public void shouldAllowVoidLookupsWhenTheLimitIsDisabled() throws 
IOException {
+        String hostname = "voidDisabled.spfexecutor.fake";
+        FakeResolver fakeResolver = new FakeResolver();
+        fakeResolver.addRecord(new TXTRecord(Name.fromString(hostname + "."), 
DClass.IN, 30L,
+            "v=spf1 a:n1." + hostname + " mx:n2." + hostname + " exists:n3." + 
hostname + " ip4:1.2.3.4 -all"));
+        SPF spf = createCustomSPF(new DNSServiceXBillImpl(fakeResolver));
+        spf.setMaxVoidLookups(-1);
+
+        SPFResult result = spf.checkSPF("1.2.3.4", "a_user@" + hostname, 
hostname);
+
+        assertEquals(SPFErrorConstants.PASS_CONV, result.getResult());
+    }
+
+    @Test(timeout = 10000)
+    public void shouldNotCountTheAddressLookupsOfTheMxNamesAsVoidLookups() 
throws IOException {
+        String hostname = "voidMxNames.spfexecutor.fake";
+        FakeResolver fakeResolver = new FakeResolver();
+        fakeResolver.addRecord(new TXTRecord(Name.fromString(hostname + "."), 
DClass.IN, 30L,
+            "v=spf1 mx ip4:1.2.3.4 -all"));
+        // 3 MX names without address, as MX hosts without AAAA for an IPv6 
client
+        for (int i = 1; i <= 3; i++) {
+            fakeResolver.addRecord(new MXRecord(Name.fromString(hostname + 
"."), DClass.IN, 30L, i,
+                Name.fromString("mx" + i + "." + hostname + ".")));
+        }
+
+        SPFResult result = createCustomSPF(new 
DNSServiceXBillImpl(fakeResolver)).checkSPF("1.2.3.4", "a_user@" + hostname, 
hostname);
+
+        // the mx term makes one lookup that is not void
+        assertEquals(SPFErrorConstants.PASS_CONV, result.getResult());
+    }
+
+    @Test(timeout = 10000)
+    public void shouldReturnTempErrorOnceTheTimeBudgetIsSpent() throws 
IOException {
+        String hostname = "timeBudget.spfexecutor.fake";
+        FakeResolver fakeResolver = new FakeResolver();
+        fakeResolver.addRecord(longTxtRecord(hostname,
+            "v=spf1 " + IntStream.rangeClosed(1, 9).mapToObj(i -> "a:h" + i + 
"." + hostname).collect(Collectors.joining(" "))
+                + " -all"));
+        for (int i = 1; i <= 9; i++) {
+            fakeResolver.addRecord(new ARecord(Name.fromString("h" + i + "." + 
hostname + "."), DClass.IN, 30L,
+                InetAddress.getByName("192.0.2.1")));
+        }
+        // each lookup answers after 100 ms, as an authoritative server 
delaying its answers
+        DNSService slowDns = new DNSServiceXBillImpl(fakeResolver) {
+            @Override
+            public List<String> getRecords(DNSRequest request) throws 
TimeoutException {
+                pause();
+                return super.getRecords(request);
+            }
+
+            @Override
+            public CompletionStage<List<String>> getRecordsAsync(DNSRequest 
request) {
+                return CompletableFuture.runAsync(this::pause).thenCompose(v 
-> super.getRecordsAsync(request));
+            }
+
+            private void pause() {
+                try {
+                    Thread.sleep(100);
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                }
+            }
+        };
+        SPF spf = createCustomSPF(slowDns);
+        spf.setTimeBudget(300);
+
+        SPFResult result = spf.checkSPF("1.2.3.4", "a_user@" + hostname, 
hostname);
+
+        // RFC 7208 4.6.4: once the time limit is exceeded, "the result of 
authorization SHOULD be "temperror""
+        assertEquals(SPFErrorConstants.TEMP_ERROR_CONV, result.getResult());
+    }
 }
diff --git 
a/resolver/src/test/java/org/apache/james/jspf/executor/FutureSPFResultTest.java
 
b/resolver/src/test/java/org/apache/james/jspf/executor/FutureSPFResultTest.java
new file mode 100644
index 0000000..1873a96
--- /dev/null
+++ 
b/resolver/src/test/java/org/apache/james/jspf/executor/FutureSPFResultTest.java
@@ -0,0 +1,49 @@
+/****************************************************************
+ * 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.james.jspf.executor;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.james.jspf.core.SPFSession;
+import org.apache.james.jspf.core.exceptions.SPFErrorConstants;
+import org.junit.Test;
+
+public class FutureSPFResultTest {
+
+    @Test(timeout = 10000)
+    public void getResultShouldGiveTempErrorWhenTheResultIsNotSetInTime() {
+        FutureSPFResult result = new FutureSPFResult();
+
+        assertEquals(SPFErrorConstants.TEMP_ERROR_CONV, result.getResult(50, 
TimeUnit.MILLISECONDS));
+    }
+
+    @Test(timeout = 10000)
+    public void getResultShouldGiveTheResultOnceSet() {
+        FutureSPFResult result = new FutureSPFResult();
+        SPFSession session = new SPFSession("[email protected]", 
"example.com", "1.2.3.4");
+        session.setCurrentResultExpanded(SPFErrorConstants.PASS_CONV);
+        result.setSPFResult(session);
+
+        assertEquals(SPFErrorConstants.PASS_CONV, result.getResult(50, 
TimeUnit.MILLISECONDS));
+    }
+}


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

Reply via email to