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

pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git


The following commit(s) were added to refs/heads/trunk by this push:
     new 83d5e63bfb Avoid quadratic regex backtracking in 
HeaderFooter.stripFields, OOXMLSignatureFacet and XSLFComment (#1439)
83d5e63bfb is described below

commit 83d5e63bfb30a3014dc15635ba6b33c15479444c
Author: PJ Fanning <[email protected]>
AuthorDate: Sun Oct 18 10:57:07 2026 +0100

    Avoid quadratic regex backtracking in HeaderFooter.stripFields, 
OOXMLSignatureFacet and XSLFComment (#1439)
    
    * Avoid quadratic regex backtracking in HeaderFooter.stripFields, 
OOXMLSignatureFacet and XSLFComment
    
    - HeaderFooter.stripFields: replace the &".*?,.*?" replaceAll with an
      equivalent linear scan
    - OOXMLSignatureFacet: anchor the .*/relationships/ and (.*)/_rels/.*
      replaceFirst patterns to line starts with (?<!.), which is where the
      leftmost match starts anyway
    - XSLFComment.setAuthor: anchor the initials pattern to the start of a
      whitespace run with (?<!\s)
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    * Use unicode escapes for line terminator characters in HeaderFooter
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../crypt/dsig/facets/OOXMLSignatureFacet.java     |  8 +++--
 .../org/apache/poi/xslf/usermodel/XSLFComment.java |  4 ++-
 .../poi/poifs/crypt/dsig/TestSignatureInfo.java    | 22 ++++++++++++
 .../poi/xslf/usermodel/TestXMLSlideShow.java       | 16 +++++++++
 .../apache/poi/hssf/usermodel/HeaderFooter.java    | 42 +++++++++++++++++++++-
 .../poi/hssf/usermodel/TestHSSFHeaderFooter.java   | 21 +++++++++++
 6 files changed, 109 insertions(+), 4 deletions(-)

diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java
 
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java
index a8092053dc..1e0fc30155 100644
--- 
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java
+++ 
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java
@@ -131,7 +131,9 @@ public class OOXMLSignatureFacet implements SignatureFacet {
 
         Set<String> digestedPartNames = new HashSet<>();
         for (PackagePart pp : relsEntryNames) {
-            final String baseUri = 
pp.getPartName().getName().replaceFirst("(.*)/_rels/.*", "$1");
+            // (?<!.) only lets a match start at the beginning of a line, 
which is where the leftmost match
+            // starts anyway - it avoids quadratic backtracking on long part 
names without "/_rels/"
+            final String baseUri = 
pp.getPartName().getName().replaceFirst("(?<!.)(.*)/_rels/.*", "$1");
 
             PackageRelationshipCollection prc;
             try {
@@ -347,7 +349,9 @@ public class OOXMLSignatureFacet implements SignatureFacet {
 
     protected static boolean isSignedRelationship(String relationshipType) {
         LOG.atDebug().log("relationship type: {}", relationshipType);
-        String rt = relationshipType.replaceFirst(".*/relationships/", "");
+        // (?<!.) only lets a match start at the beginning of a line, which is 
where the leftmost match
+        // starts anyway - it avoids quadratic backtracking on long types 
without "/relationships/"
+        String rt = relationshipType.replaceFirst("(?<!.).*/relationships/", 
"");
         return (signed.contains(rt) || rt.endsWith("customXml"));
     }
 
diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java 
b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java
index 84457894d0..84cdb9d784 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java
@@ -68,7 +68,9 @@ public class XSLFComment implements Comment {
         final CTCommentAuthor newAuthor = list.addNewCmAuthor();
         newAuthor.setName(author);
         newAuthor.setId(maxId+1);
-        newAuthor.setInitials(author.replaceAll(    "\\s*(\\w)\\S*", 
"$1").toUpperCase(LocaleUtil.getUserLocale()));
+        // (?<!\s) only lets a match start at the beginning of a whitespace 
run, which is where the
+        // leftmost match starts anyway - it avoids quadratic backtracking on 
long runs of whitespace
+        newAuthor.setInitials(author.replaceAll("(?<!\\s)\\s*(\\w)\\S*", 
"$1").toUpperCase(LocaleUtil.getUserLocale()));
         comment.setAuthorId(maxId+1);
     }
 
diff --git 
a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
 
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
index c0e42866b9..5596f99541 100644
--- 
a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
+++ 
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
@@ -27,6 +27,7 @@ import static 
org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assumptions.assumeFalse;
 import static org.junit.jupiter.api.Assumptions.assumeTrue;
@@ -48,6 +49,7 @@ import java.security.GeneralSecurityException;
 import java.security.KeyStoreException;
 import java.security.cert.X509CRL;
 import java.security.cert.X509Certificate;
+import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Calendar;
@@ -157,6 +159,26 @@ class TestSignatureInfo {
         // System.setProperty("line.separator", "\n");
     }
 
+    @Test
+    void isSignedRelationship() {
+        
assertTrue(RelationshipTypeFacet.isSigned("http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";));
+        
assertTrue(RelationshipTypeFacet.isSigned("a/relationships/b/relationships/styles"));
+        
assertFalse(RelationshipTypeFacet.isSigned("http://schemas.openxmlformats.org/officeDocument/2006/relationships/unknown";));
+        // '.' does not match line terminators, so only the first line's 
prefix is removed
+        
assertFalse(RelationshipTypeFacet.isSigned("x/relationships/a\nb/relationships/styles"));
+        
assertTrue(RelationshipTypeFacet.isSigned("x\nb/relationships/customXml"));
+
+        // the old ".*/relationships/" regex backtracked quadratically on 
types without "/relationships/"
+        String longType = "a".repeat(50_000);
+        assertFalse(assertTimeoutPreemptively(Duration.ofSeconds(10), () -> 
RelationshipTypeFacet.isSigned(longType)));
+    }
+
+    private static class RelationshipTypeFacet extends OOXMLSignatureFacet {
+        static boolean isSigned(String relationshipType) {
+            return isSignedRelationship(relationshipType);
+        }
+    }
+
     @Disabled("This test is very sensitive, it breaks with every little change 
to the produced XML")
     @Test
     void bug61182() throws Exception {
diff --git 
a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java 
b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java
index 7d0dbd567f..8b66ac8a55 100644
--- 
a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java
+++ 
b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java
@@ -22,10 +22,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.IOException;
 import java.io.InputStream;
+import java.time.Duration;
 
 import org.apache.poi.POIDataSamples;
 import org.apache.poi.ooxml.TrackingInputStream;
@@ -183,6 +185,20 @@ class TestXMLSlideShow extends 
BaseTestSlideShow<XSLFShape, XSLFTextParagraph> {
         }
     }
 
+    @Test
+    void testCommentAuthorInitials() throws Exception {
+        try (XMLSlideShow xmlComments = 
openSampleDocument("45545_Comment.pptx")) {
+            XSLFComment comment = 
xmlComments.getSlides().get(0).getComments().get(0);
+            comment.setAuthor("Apache  POI-team !x");
+            assertEquals("AP !X", comment.getAuthorInitials());
+
+            // the old "\\s*(\\w)\\S*" regex backtracked quadratically on 
whitespace not followed by a word character
+            String spaces = " ".repeat(50_000);
+            assertTimeoutPreemptively(Duration.ofSeconds(10), () -> 
comment.setAuthor("Apache" + spaces + "!"));
+            assertEquals("A" + spaces + "!", comment.getAuthorInitials());
+        }
+    }
+
     @Test
     void testInputStreamClosed() throws Exception {
         try (TrackingInputStream stream = new TrackingInputStream(
diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java 
b/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java
index 3884462587..5a18b65065 100644
--- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java
+++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java
@@ -299,7 +299,7 @@ public abstract class HeaderFooter implements 
org.apache.poi.ss.usermodel.Header
         // Now do the tricky, dynamic ones
         // These are things like font sizes, font names and colours
         text = text.replaceAll("&\\d+", "");
-        text = text.replaceAll("&\".*?,.*?\"", "");
+        text = stripFontNames(text);
         text = text.replaceAll("&K[\\dA-F]{6}", "");
         text = text.replaceAll("&K[\\d]{2}[+][\\d]{3}", "");
 
@@ -310,6 +310,46 @@ public abstract class HeaderFooter implements 
org.apache.poi.ss.usermodel.Header
         return text;
     }
 
+    /**
+     * Removes font name fields, giving the same result as
+     * {@code text.replaceAll("&\".*?,.*?\"", "")} but in linear time:
+     * that regex backtracks quadratically on, e.g., {@code &"} followed by 
many commas.
+     */
+    private static String stripFontNames(String text) {
+        int start = text.indexOf("&\"");
+        if (start < 0) {
+            return text;
+        }
+        final int len = text.length();
+        StringBuilder sb = new StringBuilder(len);
+        int copied = 0;
+        while (start >= 0) {
+            // like '.' in the regex, the comma and the closing quote must be 
on the same line
+            int i = start + 2;
+            while (i < len && text.charAt(i) != ',' && 
!isLineTerminator(text.charAt(i))) {
+                i++;
+            }
+            if (i < len && text.charAt(i) == ',') {
+                i++;
+                while (i < len && text.charAt(i) != '"' && 
!isLineTerminator(text.charAt(i))) {
+                    i++;
+                }
+                if (i < len && text.charAt(i) == '"') {
+                    sb.append(text, copied, start);
+                    copied = ++i;
+                }
+            }
+            // on a failed match, i is at the end of the line, and no later 
match can start before then
+            start = text.indexOf("&\"", i);
+        }
+        return sb.append(text, copied, len).toString();
+    }
+
+    /** the characters that '.' does not match in a regex */
+    private static boolean isLineTerminator(char c) {
+        return c == '\n' || c == '\r' || c == '\u0085' || c == '\u2028' || c 
== '\u2029';
+    }
+
     private enum MarkupTag {
         SHEET_NAME_FIELD ("&A", false),
         DATE_FIELD       ("&D", false),
diff --git 
a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java 
b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java
index c8a5265a63..bee8db55f8 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java
@@ -19,8 +19,10 @@ package org.apache.poi.hssf.usermodel;
 
 import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
 
 import java.io.IOException;
+import java.time.Duration;
 
 import org.apache.poi.hssf.HSSFTestDataSamples;
 import org.junit.jupiter.api.Test;
@@ -56,6 +58,25 @@ final class TestHSSFHeaderFooter {
         assertEquals("&\"Arial,bold\"", HSSFFooter.font("Arial", "bold"));
     }
 
+    @Test
+    void testStripFieldsFontNames() {
+        assertEquals("ab", HSSFHeader.stripFields("a&\"Arial,Bold\"b"));
+        assertEquals("a,\"b", HSSFHeader.stripFields("a&\"x&\"y,z\",\"b"));
+        // the comma and the closing quote have to be on the same line as the 
opening &"
+        assertEquals("a&\"Arial\n,Bold\"b", 
HSSFHeader.stripFields("a&\"Arial\n,Bold\"b"));
+        assertEquals("a&\"Arial,\nBold\"b", 
HSSFHeader.stripFields("a&\"Arial,\nBold\"b"));
+        assertEquals("a&\"Arial,\nc", 
HSSFHeader.stripFields("a&\"Arial,\n&\"x,y\"c"));
+    }
+
+    @Test
+    void testStripFieldsUnclosedFontName() {
+        // the old "&\".*?,.*?\"" regex backtracked quadratically on an 
unclosed font name
+        String commas = "&\"" + ",".repeat(50_000);
+        assertEquals(commas, assertTimeoutPreemptively(Duration.ofSeconds(10), 
() -> HSSFHeader.stripFields(commas)));
+        String quotes = "&\"".repeat(50_000);
+        assertEquals(quotes, assertTimeoutPreemptively(Duration.ofSeconds(10), 
() -> HSSFHeader.stripFields(quotes)));
+    }
+
     @Test
     void testStripFields() throws IOException {
         String simple = "I am a test header";


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

Reply via email to