From 73fe2b00519a43aeebdb501247222b3a04b45700 Mon Sep 17 00:00:00 2001
From: Glyph <code@glyph.im>
Date: Fri, 14 Aug 2026 18:46:34 -0700
Subject: [PATCH 1/7] add a type annotation since we're about to make changes

---
 src/twisted/mail/imap4.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

Index: twisted-24.10.0/src/twisted/mail/imap4.py
===================================================================
--- twisted-24.10.0.orig/src/twisted/mail/imap4.py
+++ twisted-24.10.0/src/twisted/mail/imap4.py
@@ -4592,13 +4592,35 @@ def Not(query):
     return f"(NOT {query})"
 
 
-def wildcardToRegexp(wildcard, delim=None):
-    wildcard = wildcard.replace("*", "(?:.*?)")
-    if delim is None:
-        wildcard = wildcard.replace("%", "(?:.*?)")
-    else:
-        wildcard = wildcard.replace("%", "(?:(?:[^%s])*?)" % re.escape(delim))
-    return re.compile(wildcard, re.I)
+def wildcardToRegexp(wildcard: str, delim: str | None = None) -> re.Pattern[str]:
+    """
+    Convert what the IMAP describes as a "mailbox name with possible wildcards"
+    into a regular expression that will match a full mailbox name.
+
+    @param wildcard: the mailbox name matching expression which may contain
+        IMAP wildcards, e.g. C{*} and C{%}.  Note that this is I{not} treated
+        as a regular expression itself, and any regex syntax will be matched
+        literally.
+
+    @param delim: the delimiter between IMAP path elements, if any.  Note that
+        this is always C{"/"} when used by Twisted's IMAP server.
+
+    @return: a L{re.Pattern} that will match IMAP mailbox names with the given
+        wildcards.
+    """
+    parts = re.split(r"([*%])", wildcard)
+    result = []
+    for p in parts:
+        if p == "*":
+            result.append("(?:.*?)")
+        elif p == "%":
+            if delim is None:
+                result.append("(?:.*?)")
+            else:
+                result.append(f"(?:(?:[^{re.escape(delim)}])*?)")
+        else:
+            result.append(re.escape(p))
+    return re.compile("".join(result), re.I)
 
 
 def splitQuoted(s):
Index: twisted-24.10.0/src/twisted/mail/newsfragments/12787.bugfix
===================================================================
--- /dev/null
+++ twisted-24.10.0/src/twisted/mail/newsfragments/12787.bugfix
@@ -0,0 +1 @@
+twisted.mail.imap4 no longer allows clients to specify arbitrary regexes.
Index: twisted-24.10.0/src/twisted/mail/test/test_imap.py
===================================================================
--- twisted-24.10.0.orig/src/twisted/mail/test/test_imap.py
+++ twisted-24.10.0/src/twisted/mail/test/test_imap.py
@@ -6,6 +6,7 @@
 """
 Test case for twisted.mail.imap4
 """
+
 from __future__ import annotations
 
 import base64
@@ -17,7 +18,7 @@ import uuid
 from collections import OrderedDict
 from io import BytesIO
 from itertools import chain
-from typing import Optional, Type
+from typing import Any, Optional, Type
 from unittest import skipIf
 
 from zope.interface import implementer
@@ -2529,7 +2530,7 @@ class IMAP4ServerTests(IMAP4HelperMixin,
         )
         return d
 
-    def _listSetup(self, f):
+    def _listSetup(self, f: object) -> Deferred[Any]:
         SimpleServer.theAccount.addMailbox("root/subthing")
         SimpleServer.theAccount.addMailbox("root/another-thing")
         SimpleServer.theAccount.addMailbox("non-root/subthing")
@@ -2596,6 +2597,39 @@ class IMAP4ServerTests(IMAP4HelperMixin,
         d.addCallback(self.assertEqual, [(SimpleMailbox.flags, "/", "ROOT/SUBTHING")])
         return d
 
+    def test_LSubNoRegex(self) -> Deferred[None]:
+        """
+        LSUB commands should use IMAP wildcards, and not be treated as Python
+        regexes.
+        """
+        # Subscribe to existing mailbox.
+        SimpleServer.theAccount.subscribe("ROOT/SUBTHING")
+
+        for newMailbox in [
+            # Verify that dot is treated literally.
+            "ROOT/.SUBMATCH",
+            # And can match nested things, since we're testing *.
+            "ROOT/.DEEP/MATCH",
+            # But only at the start of the match.
+            "ROOT/DEEP/.MATCH",
+        ]:
+            SimpleServer.theAccount.addMailbox(newMailbox)
+            SimpleServer.theAccount.subscribe(newMailbox)
+
+        def lsub():
+            return self.client.lsub("root", "root/.*")
+
+        d = self._listSetup(lsub)
+        d.addCallback(self.assertListDelimiterAndMailboxAreStrings)
+        d.addCallback(
+            self.assertEqual,
+            [
+                (SimpleMailbox.flags, "/", "ROOT/.SUBMATCH"),
+                (SimpleMailbox.flags, "/", "ROOT/.DEEP/MATCH"),
+            ],
+        )
+        return d
+
     def testStatus(self):
         SimpleServer.theAccount.addMailbox("root/subthing")
 
@@ -7100,7 +7134,7 @@ class CopyWorkerTests(TestCase):
         return d.addCallback(cbCopy)
 
 
-@skipIf(not ClientTLSContext, "OpenSSL not present")
+@skipIf(not ClientTLSContext, "OpenSSL not present") # type: ignore[truthy-function]
 @skipIf(not interfaces.IReactorSSL(reactor, None), "Reactor doesn't support SSL")
 class TLSTests(IMAP4HelperMixin, TestCase):
     serverCTX = None
