Browse Source

Fixes #4567 - Unable to process email with invalid "Date" header

Mantas 1 year ago
parent
commit
a77e589d57

+ 37 - 0
lib/core_ext/mail/fields/common_date_field.rb

@@ -0,0 +1,37 @@
+# rubocop:disable all
+# Ruby 3.0 brought 128 characters limit to DateTime#parse
+# to avoid performance issues if a very long string is given.
+# This breaks Mail gem if email date header is malformed.
+#
+# There is a PR to fix this issue in Mail gem.
+# However, it is not merged for months
+# and it's not clear when next release may come out.
+# https://github.com/mikel/mail/pull/1469
+#
+# This monkeypatch shall be removed once above PR is merged
+# and Mail gem is updated.
+
+module Mail
+  class CommonDateField < NamedStructuredField #:nodoc:
+    def self.normalize_datetime(string)
+      if Utilities.blank?(string)
+        datetime = ::DateTime.now
+      else
+        stripped = string.to_s.gsub(/\(.*?\)/, '').squeeze(' ')
+          .slice(0, 128) # this is the custom addition in this monkeypatch
+        begin
+          datetime = ::DateTime.parse(stripped)
+        rescue ArgumentError => e
+          raise unless 'invalid date' == e.message
+        end
+      end
+
+      if datetime
+        datetime.strftime('%a, %d %b %Y %H:%M:%S %z')
+      else
+        string
+      end
+    end
+  end
+end
+# rubocop:enable all

+ 1 - 1
spec/models/channel/email_parser_spec.rb

@@ -37,7 +37,7 @@ RSpec.describe Channel::EmailParser, type: :model do
       end
 
       it 'ensures tests were dynamically generated' do
-        expect(tests.count).to eq(106)
+        expect(tests.count).to eq(107)
       end
     end
 

+ 8 - 0
test/data/mail/mail107.box

@@ -0,0 +1,8 @@
+From: me@example.com
+To: you@example.com
+Date: Fri, 07 Apr 2023 17:30:44 +0200Received: from m241-41.example.com (m241-41.example.com [1.1.1.1])
+	by in45.mail.example.com (Postfix) with ESMTPS id 4PgzCH5GFlz279jM6
+	for <service@example.com>; Tue, 21 Mar 2023 17:30:35 +0000 (UTC)
+Subject: test
+
+some text

+ 11 - 0
test/data/mail/mail107.yml

@@ -0,0 +1,11 @@
+--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
+from: me@example.com
+from_email: me@example.com
+from_display_name: ''
+to: you@example.com
+subject: test
+body: 'some text
+
+  '
+content_type: text/plain
+attachments: []