From 985f1923fa62806ff676e41de67c3b4552131ab9 Mon Sep 17 00:00:00 2001
From: John Hawthorn <john@hawthorn.email>
Date: Fri, 11 Oct 2024 00:34:14 -0700
Subject: [PATCH] Avoid backtracking in ActionMailer block_format

[CVE-2024-47889]

Thanks to yuki_osaki and scyoon for reporting this vulnerability
---
 lib/action_mailer/mail_helper.rb | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/lib/action_mailer/mail_helper.rb b/lib/action_mailer/mail_helper.rb
index e7bed41..f527d5a 100644
--- a/lib/action_mailer/mail_helper.rb
+++ b/lib/action_mailer/mail_helper.rb
@@ -23,10 +23,18 @@ module ActionMailer
       }.join("\n\n")
 
       # Make list points stand on their own line
-      formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { "  #{$1} #{$2.strip}\n" }
-      formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { "  #{$1} #{$2.strip}\n" }
+      output = +""
+      splits = formatted.split(/(\*+|\#+)/)
+      while line = splits.shift
+        if line.start_with?("*", "#") && splits[0].start_with?(" ")
+          output.chomp!(" ") while output.end_with?(" ")
+          output << "  #{line} #{splits.shift.strip}\n"
+        else
+          output << line
+        end
+      end
 
-      formatted
+      output
     end
 
     # Access the mailer instance.
-- 
2.33.0

