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-jdkim.git

commit e09f53e088233ba96483ca4c6d8336d42b0640b7
Author: Benoit TELLIER <[email protected]>
AuthorDate: Thu Nov 26 18:13:02 2026 +0100

    [FIX] DKIMVerifier: keep the results of the last call only, per thread
    
    Each verify call appended its results to a list held by the instance and
    never cleared but by resetResults: a verifier reused for every mail, as
    James does, grew without bound, and concurrent calls raced on the list.
    
    Each call now builds its own list and keeps it, unmodifiable, in a
    ThreadLocal: getResults, hasAnyValidSignature and resetResults keep their
    signatures and report the last call of the calling thread.
---
 .../java/org/apache/james/jdkim/DKIMVerifier.java  | 43 +++++++---
 .../test/java/org/apache/james/jdkim/DKIMTest.java | 92 ++++++++++++++++++++++
 2 files changed, 123 insertions(+), 12 deletions(-)

diff --git a/main/src/main/java/org/apache/james/jdkim/DKIMVerifier.java 
b/main/src/main/java/org/apache/james/jdkim/DKIMVerifier.java
index 1fa457d..c12cb52 100644
--- a/main/src/main/java/org/apache/james/jdkim/DKIMVerifier.java
+++ b/main/src/main/java/org/apache/james/jdkim/DKIMVerifier.java
@@ -54,6 +54,7 @@ import java.time.Duration;
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
@@ -63,12 +64,20 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
 
+/**
+ * Verifies the DKIM signatures of messages. An instance holds no per-message 
state: it can be shared and
+ * reused for any number of messages, from any number of threads.
+ */
 public class DKIMVerifier {
     /**
      * Allows e = 65537 and any exponent up to 2^32 + 1.
      */
     private static final int MAX_RSA_PUBLIC_EXPONENT_BITS = 33;
-    private final List<Result> result = new ArrayList<>();
+    /**
+     * The results of the last verification made by each thread: a call 
replaces them, so they do not grow
+     * with the number of verified messages, and concurrent calls do not see 
each other's.
+     */
+    private final ThreadLocal<List<Result>> lastResults = 
ThreadLocal.withInitial(Collections::emptyList);
     private final VerifierOptions options;
 
     public DKIMVerifier() {
@@ -237,6 +246,7 @@ public class DKIMVerifier {
      */
     public List<SignatureRecord> verify(InputStream is) throws IOException,
             FailException {
+        lastResults.remove();
         Message message;
         try {
             try {
@@ -453,6 +463,7 @@ public class DKIMVerifier {
      */
     public List<SignatureRecord> verify(Headers messageHeaders,
                                         InputStream bodyInputStream) throws 
IOException, FailException {
+        lastResults.remove();
 
         BodyHasher bh = newBodyHasher(messageHeaders);
 
@@ -476,6 +487,7 @@ public class DKIMVerifier {
      * @throws FailException if no valid signature is found
      */
     public List<SignatureRecord> verify(BodyHasher bh) throws FailException {
+        lastResults.remove();
         if (bh == null) return null;
         CompoundBodyHasher cbh = validateBodyHasher(bh);
 
@@ -512,6 +524,7 @@ public class DKIMVerifier {
             throws FailException {
         List<SignatureRecord> verifiedSignatures = new LinkedList<>();
         List<FailException> failures = new ArrayList<>();
+        List<Result> result = new ArrayList<>();
         for (CompoundBodyHasher.Job job : compoundBodyHasher.getJobs()) {
             BodyHasherImpl bhj = job.getBodyHasher();
             if (bhj != null) {
@@ -540,6 +553,7 @@ public class DKIMVerifier {
             failures.add(job.getFailure());
             result.add(resultFromException(job.getSignatureField(), 
job.getFailure()));
         }
+        lastResults.set(Collections.unmodifiableList(result));
 
         if (verifiedSignatures.isEmpty()) {
             throw prepareException(failures);
@@ -549,20 +563,24 @@ public class DKIMVerifier {
     }
 
     /**
-     * Returns the results of all signature checks, success and fail.
-     * If a message doesn't have a DKIM-Signature header the result list will
-     * be empty. Use {@link Result#getResultType} or {@link Result#isSuccess}
-     * to get verification result of each DKIM-Signature check. Call {@link 
#resetResults}
-     * if the same instance of {@code DKIMVerifier} is reused for a new {@code 
verify} call.
+     * Returns the results of all signature checks, success and fail, of the 
last {@code verify} call
+     * made by the current thread on this instance. If that message doesn't 
have a DKIM-Signature header,
+     * or no {@code verify} call was made, the result list is empty. Use 
{@link Result#getResultType} or
+     * {@link Result#isSuccess} to get verification result of each 
DKIM-Signature check.
+     * <p>
+     * Each {@code verify} call replaces the results of the previous one: an 
instance can be reused for
+     * many messages and shared between threads. The results are bound to the 
calling thread: read them
+     * from the thread that called {@code verify}, before it verifies another 
message.
      *
-     * @return List of {@link Result} object.
+     * @return unmodifiable List of {@link Result} object.
      */
     public List<Result> getResults() {
-        return result;
+        return lastResults.get();
     }
 
     /**
-     * Returns {@code true} if at least one signature is successfully verified.
+     * Returns {@code true} if at least one signature is successfully verified 
by the last
+     * {@code verify} call made by the current thread, see {@link #getResults}.
      * A message pass the DKIM check when at least one signature is valid.
      * This method is DMARC compliant, and should be called after {@code 
DKIMVerifier.verify}.
      * Use {@link #getResults} to get result details.
@@ -572,14 +590,15 @@ public class DKIMVerifier {
      * @see #getResults
      */
     public boolean hasAnyValidSignature() {
-        return result.stream().anyMatch(Result::isSuccess);
+        return getResults().stream().anyMatch(Result::isSuccess);
     }
 
     /**
-     * Clears results list for the DKIMVerifier instance
+     * Clears the results of the last {@code verify} call made by the current 
thread. Not needed
+     * between two calls, each one replaces the results of the previous one.
      */
     public void resetResults() {
-        result.clear();
+        lastResults.remove();
     }
 
     private Result resultFromException(String signatureField, FailException e) 
{
diff --git a/main/src/test/java/org/apache/james/jdkim/DKIMTest.java 
b/main/src/test/java/org/apache/james/jdkim/DKIMTest.java
index 318fd43..3bd3e81 100644
--- a/main/src/test/java/org/apache/james/jdkim/DKIMTest.java
+++ b/main/src/test/java/org/apache/james/jdkim/DKIMTest.java
@@ -42,7 +42,14 @@ import java.security.Signature;
 import java.util.Arrays;
 import java.util.Base64;
 import java.util.Collections;
+import java.util.ArrayList;
 import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.james.jdkim.MockPublicKeyRecordRetriever.Record;
@@ -859,4 +866,89 @@ public class DKIMTest {
         }
     }
 
+    private byte[] signedMail(int index, boolean valid) throws Exception {
+        byte[] mail = ("From: [email protected]\r\nSubject: mail " + index + 
"\r\n\r\nbody " + index + "\r\n")
+                .getBytes(StandardCharsets.US_ASCII);
+        String field = dkimSigner.sign(new ByteArrayInputStream(mail));
+        if (!valid) {
+            field = field.replace("bh=", "bh=AAAA");
+        }
+        ByteArrayOutputStream signed = new ByteArrayOutputStream();
+        signed.write((field + "\r\n").getBytes(StandardCharsets.US_ASCII));
+        signed.write(mail);
+        return signed.toByteArray();
+    }
+
+    @Test
+    public void reusedVerifierShouldNotAccumulateResults() throws Exception {
+        for (int i = 0; i < 100; i++) {
+            boolean valid = i % 2 == 0;
+            try {
+                verifier.verify(new ByteArrayInputStream(signedMail(i, 
valid)));
+            } catch (FailException e) {
+                assertThat(valid).isFalse();
+            }
+
+            assertThat(verifier.getResults()).singleElement()
+                    .extracting(Result::isSuccess).isEqualTo(valid);
+            assertThat(verifier.hasAnyValidSignature()).isEqualTo(valid);
+        }
+    }
+
+    @Test
+    public void unsignedMailShouldClearThePreviousResults() throws Exception {
+        verifier.verify(new ByteArrayInputStream(signedMail(0, true)));
+
+        assertThat(verifier.verify(new ByteArrayInputStream(
+                "From: 
[email protected]\r\n\r\nbody\r\n".getBytes(StandardCharsets.US_ASCII)))).isNull();
+
+        assertThat(verifier.getResults()).isEmpty();
+        assertThat(verifier.hasAnyValidSignature()).isFalse();
+    }
+
+    @Test
+    public void resetResultsShouldClearTheResults() throws Exception {
+        verifier.verify(new ByteArrayInputStream(signedMail(0, true)));
+
+        verifier.resetResults();
+
+        assertThat(verifier.getResults()).isEmpty();
+    }
+
+    @Test
+    public void concurrentVerificationsShouldNotSeeEachOtherResults() throws 
Exception {
+        int threads = 8;
+        int mailsPerThread = 50;
+        ExecutorService executor = Executors.newFixedThreadPool(threads);
+        try {
+            CountDownLatch start = new CountDownLatch(1);
+            List<Future<Void>> futures = new ArrayList<>();
+            for (int t = 0; t < threads; t++) {
+                boolean valid = t % 2 == 0;
+                int thread = t;
+                Callable<Void> task = () -> {
+                    start.await();
+                    for (int i = 0; i < mailsPerThread; i++) {
+                        try {
+                            verifier.verify(new 
ByteArrayInputStream(signedMail(thread * mailsPerThread + i, valid)));
+                        } catch (FailException e) {
+                            assertThat(valid).isFalse();
+                        }
+                        assertThat(verifier.getResults()).singleElement()
+                                
.extracting(Result::isSuccess).isEqualTo(valid);
+                        
assertThat(verifier.hasAnyValidSignature()).isEqualTo(valid);
+                    }
+                    return null;
+                };
+                futures.add(executor.submit(task));
+            }
+            start.countDown();
+            for (Future<Void> future : futures) {
+                future.get(60, TimeUnit.SECONDS);
+            }
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
 }


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

Reply via email to