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 d05b6becdc837556ebaec26094421320abc8e71d
Author: Benoit TELLIER <[email protected]>
AuthorDate: Thu Nov 19 06:08:35 2026 +0100

    [PERF] DKIMVerifier: share the placeholder record and the cap failure
    
    A failure without a parsed record, which is the case of every field
    past the maxSignatures cap and of every unparsable record, got a new
    placeholder SignatureRecordTemplate: a tag-value parse of a constant
    string per field. Each field past the cap also got its own
    PermFailException, with the same message and a new stack trace. On a
    forged mail with 1000 fields these made most of the verification cost
    and about 8 MB of garbage, for fields that are not verified.
    
    PlaceholderSignatureRecord is a single shared record whose getters
    return the former placeholder values and whose setters throw. The
    fields past the cap share one PermFailException per verification.
    There is still one Result per field, with the same type and message.
---
 .../java/org/apache/james/jdkim/DKIMVerifier.java  |  17 ++-
 .../james/jdkim/PlaceholderSignatureRecord.java    | 131 +++++++++++++++++++++
 .../org/apache/james/jdkim/DKIMVerifierTest.java   |  22 ++++
 3 files changed, 161 insertions(+), 9 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 284f7bc..49be446 100644
--- a/main/src/main/java/org/apache/james/jdkim/DKIMVerifier.java
+++ b/main/src/main/java/org/apache/james/jdkim/DKIMVerifier.java
@@ -41,7 +41,6 @@ import org.apache.james.jdkim.impl.CompoundBodyHasher;
 import org.apache.james.jdkim.impl.Message;
 import org.apache.james.jdkim.tagvalue.PublicKeyRecordImpl;
 import org.apache.james.jdkim.tagvalue.SignatureRecordImpl;
-import org.apache.james.jdkim.tagvalue.SignatureRecordTemplate;
 
 import java.io.IOException;
 import java.io.InputStream;
@@ -270,14 +269,19 @@ public class DKIMVerifier {
         // One job per field, even for byte-identical fields: each one gets 
its own result.
         List<CompoundBodyHasher.Job> jobs = new ArrayList<>();
         int processedSignatures = 0;
+        // the fields past the cap all get this one exception: its message and 
stack are the same for each
+        PermFailException tooManySignatures = null;
         for (int signatureIndex = 0; signatureIndex < fields.size(); 
signatureIndex++) {
             String signatureField = fields.get(signatureIndex);
             CompoundBodyHasher.Job job = new 
CompoundBodyHasher.Job(signatureField);
             jobs.add(job);
             // RFC 6376 section 6.1: verifiers MAY limit the number of 
signatures they try to verify.
             if (processedSignatures >= options.getMaxSignatures()) {
-                job.setFailure(new PermFailException("Too many DKIM-Signature 
fields: only the first "
-                        + options.getMaxSignatures() + " are verified"));
+                if (tooManySignatures == null) {
+                    tooManySignatures = new PermFailException("Too many 
DKIM-Signature fields: only the first "
+                            + options.getMaxSignatures() + " are verified");
+                }
+                job.setFailure(tooManySignatures);
                 continue;
             }
             processedSignatures++;
@@ -579,12 +583,7 @@ public class DKIMVerifier {
     private Result resultFromException(String signatureField, FailException e) 
{
         SignatureRecord rec = e.getRelatedRecord();
         if (rec == null) {
-            rec = new SignatureRecordTemplate("v=1; d=invalid; h=from; 
s=invalid; b=invalidsig") {
-                @Override
-                public void validate() {
-                    // placeholder for a failure without a parsed signature, 
not a record to check
-                }
-            };
+            rec = PlaceholderSignatureRecord.INSTANCE;
         }
 
         Result.Type resultType = Result.Type.NONE;
diff --git 
a/main/src/main/java/org/apache/james/jdkim/PlaceholderSignatureRecord.java 
b/main/src/main/java/org/apache/james/jdkim/PlaceholderSignatureRecord.java
new file mode 100644
index 0000000..b74ba1d
--- /dev/null
+++ b/main/src/main/java/org/apache/james/jdkim/PlaceholderSignatureRecord.java
@@ -0,0 +1,131 @@
+/******************************************************************************
+ * 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.jdkim;
+
+import java.util.List;
+
+import org.apache.james.jdkim.api.SignatureRecord;
+import org.apache.james.jdkim.tagvalue.SignatureRecordTemplate;
+
+/**
+ * The record of a result whose failure has no parsed signature (unparsable 
record, field past the
+ * maxSignatures cap...). One instance is shared: its setters throw, and its 
getters return values that
+ * cannot be changed through them.
+ */
+final class PlaceholderSignatureRecord implements SignatureRecord {
+
+    static final SignatureRecord INSTANCE = new PlaceholderSignatureRecord();
+
+    private final SignatureRecord placeholder = new SignatureRecordTemplate(
+            "v=1; d=invalid; h=from; s=invalid; b=invalidsig") {
+        @Override
+        public void validate() {
+            // placeholder for a failure without a parsed signature, not a 
record to check
+        }
+    };
+
+    private PlaceholderSignatureRecord() {
+        // computes the string representation now, so that the shared instance 
is never written to again
+        placeholder.toString();
+    }
+
+    public List<CharSequence> getHeaders() {
+        return placeholder.getHeaders();
+    }
+
+    public CharSequence getIdentityLocalPart() {
+        return placeholder.getIdentityLocalPart();
+    }
+
+    public CharSequence getIdentity() {
+        return placeholder.getIdentity();
+    }
+
+    public CharSequence getHashKeyType() {
+        return placeholder.getHashKeyType();
+    }
+
+    public CharSequence getHashMethod() {
+        return placeholder.getHashMethod();
+    }
+
+    public CharSequence getHashAlgo() {
+        return placeholder.getHashAlgo();
+    }
+
+    public CharSequence getSelector() {
+        return placeholder.getSelector();
+    }
+
+    public CharSequence getDToken() {
+        return placeholder.getDToken();
+    }
+
+    public byte[] getBodyHash() {
+        return placeholder.getBodyHash();
+    }
+
+    public int getBodyHashLimit() {
+        return placeholder.getBodyHashLimit();
+    }
+
+    public String getHeaderCanonicalisationMethod() {
+        return placeholder.getHeaderCanonicalisationMethod();
+    }
+
+    public String getBodyCanonicalisationMethod() {
+        return placeholder.getBodyCanonicalisationMethod();
+    }
+
+    public List<CharSequence> getRecordLookupMethods() {
+        return placeholder.getRecordLookupMethods();
+    }
+
+    public void validate() {
+    }
+
+    public byte[] getSignature() {
+        return placeholder.getSignature();
+    }
+
+    public CharSequence getRawSignature() {
+        return placeholder.getRawSignature();
+    }
+
+    public void setSignature(byte[] newSignature) {
+        throw new UnsupportedOperationException("placeholder record");
+    }
+
+    public void setBodyHash(byte[] newBodyHash) {
+        throw new UnsupportedOperationException("placeholder record");
+    }
+
+    public String toUnsignedString() {
+        return placeholder.toUnsignedString();
+    }
+
+    public Long getSignatureTimestamp() {
+        return placeholder.getSignatureTimestamp();
+    }
+
+    public String toString() {
+        return placeholder.toString();
+    }
+}
diff --git a/main/src/test/java/org/apache/james/jdkim/DKIMVerifierTest.java 
b/main/src/test/java/org/apache/james/jdkim/DKIMVerifierTest.java
index a8a73d6..31ca25e 100644
--- a/main/src/test/java/org/apache/james/jdkim/DKIMVerifierTest.java
+++ b/main/src/test/java/org/apache/james/jdkim/DKIMVerifierTest.java
@@ -157,6 +157,28 @@ public class DKIMVerifierTest {
         assertThat(verifier.getResults().stream().filter(r -> 
r.getErrorMessage().startsWith("Too many DKIM-Signature fields"))).hasSize(190);
     }
 
+    @Test
+    public void resultsWithoutARecordShouldShareAnUnmodifiablePlaceholder() {
+        StringBuilder mail = new StringBuilder();
+        for (int i = 0; i < 3; i++) {
+            mail.append("DKIM-Signature: v=1; a=rsa-sha256; d=example.com; 
s=s").append(i).append("; h=from; bh=AAAA; b=AAAA\r\n");
+        }
+        mail.append("From: [email protected]\r\n\r\nbody\r\n");
+        DKIMVerifier verifier = new DKIMVerifier(new VerifierOptions.Builder()
+                .withPublicKeyRecordRetriever((method, selector, token) -> {
+                    throw new PermFailException("no key");
+                }).withMaxSignatures(1).build());
+
+        assertThatThrownBy(() -> verifier.verify(new 
ByteArrayInputStream(mail.toString().getBytes(StandardCharsets.US_ASCII))))
+                .isInstanceOf(FailException.class);
+        Result pastTheCap = verifier.getResults().get(2);
+        
assertThat(pastTheCap.getRecord()).isSameAs(verifier.getResults().get(1).getRecord());
+        assertThat(pastTheCap.getRecord().getDToken()).hasToString("invalid");
+        assertThat(pastTheCap.getHeaderText()).contains("permerror");
+        assertThatThrownBy(() -> pastTheCap.getRecord().setSignature(new 
byte[0]))
+                .isInstanceOf(UnsupportedOperationException.class);
+    }
+
     @Test
     public void verifyShouldFailWithPermFailOnUndecodableBodyHash() throws 
Exception {
         String tags = " b=; v=1; a=rsa-sha256; d=example.com; s=sel; h=from; 
bh=ab=c";


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

Reply via email to