From acfb6588265cfc811be5d054455ed84eb558c991 Mon Sep 17 00:00:00 2001 From: Aditya <152765789+adityawrk@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:23:28 +0530 Subject: [PATCH] Percent-encode unsafe characters in a mailto address MailTo.build copied the address into the URI unchanged, so a reserved character such as ? or # made the address fail to parse. Those octets are now percent-encoded. A plus sign is left as-is, because RFC 6068 uses it for subaddresses. --- lib/uri/mailto.rb | 13 +++++++++++-- test/uri/test_mailto.rb | 10 ++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/uri/mailto.rb b/lib/uri/mailto.rb index cb8024f3..e36fe090 100644 --- a/lib/uri/mailto.rb +++ b/lib/uri/mailto.rb @@ -87,9 +87,9 @@ def self.build(args) case tmp[:to] when Array - tmp[:opaque] = tmp[:to].join(',') + tmp[:opaque] = tmp[:to].map { |addr| encode_to_addrs(addr) }.join(',') when String - tmp[:opaque] = tmp[:to].dup + tmp[:opaque] = encode_to_addrs(tmp[:to]) else tmp[:opaque] = '' end @@ -120,6 +120,15 @@ def self.build(args) super(tmp) end + # Percent-encode octets that cannot appear raw in a mailto addr-spec. + # '+' is left as-is: RFC 6068 allows it for subaddresses. + def self.encode_to_addrs(str) + str.to_s.b.gsub(/%(?!\h\h)|[^!$&-.0-;=@-Z_a-z~%]/n) { |char| + '%%%02X' % char.ord + } + end + private_class_method :encode_to_addrs + # # == Description # diff --git a/test/uri/test_mailto.rb b/test/uri/test_mailto.rb index 6cd33529..25746b2e 100644 --- a/test/uri/test_mailto.rb +++ b/test/uri/test_mailto.rb @@ -131,6 +131,16 @@ def test_build assert_equal(ok_all, ok.flatten.join("\0")) end + def test_build_percent_encodes_unsafe_address_characters + address = "#!$%&'*+-/=?^_`{}|@example.org" + uri = URI::MailTo.build(:to => address) + assert_equal( + "mailto:%23!$%25&'*+-%2F=%3F%5E_%60%7B%7D%7C@example.org", + uri.to_s + ) + assert_equal(address, uri.to.gsub(/%\h\h/) { |esc| [esc[1, 2]].pack('H2') }) + end + def test_initializer assert_raise(URI::InvalidComponentError) do URI::MailTo.new('mailto', 'sdmitry:bla', 'localhost', '2000', nil,