~singpolyma/jmp-pay

b17a9ecc37d0d6ad6ae7bd6907d03390e0a1918c — Stephen Paul Weber 10 months ago c2bab9c
Handle multiple DKIM headers
2 files changed, 79 insertions(+), 4 deletions(-)

M lib/interac_email.rb
A test/test_interac_email.rb
M lib/interac_email.rb => lib/interac_email.rb +4 -4
@@ 119,17 119,17 @@ class InteracEmail
		end

		def authentication_header
			@m["Authentication-Results"]&.value
			Array(@m["Authentication-Results"]).map(&:value)
		end

		HEADER_REGEX = /\sheader.d=payments.interac.ca\s/.freeze

		def ensure_authentication_header
			auth = authentication_header

			auth = authentication_header.find { |a|
				a =~ HEADER_REGEX
			}
			raise Error::NoAuth, @m unless auth
			raise Error::BadAuth, @m unless auth =~ /\sdkim=pass\s/
			raise Error::BadDomain, @m unless auth =~ HEADER_REGEX
		end

		def dkim_header

A test/test_interac_email.rb => test/test_interac_email.rb +75 -0
@@ 0,0 1,75 @@
# frozen_string_literal: true

require "interac_email"
require "mail"
require "test_helper"

class InteracEmailTest < Minitest::Test
	def test_authentication_header
		@m = Mail.new(<<~MAIL)
			Authentication-Results: hai
			To: someone@example.com
			From: interac@example.com

			body
		MAIL
		@validator = InteracEmail::Validator.new(@m)
		assert_equal ["hai"], @validator.authentication_header
	end

	def test_authentication_headers
		@m = Mail.new(<<~MAIL)
			Authentication-Results: hai
			Authentication-Results: hai2
			To: someone@example.com
			From: interac@example.com

			body
		MAIL
		@validator = InteracEmail::Validator.new(@m)
		assert_equal ["hai", "hai2"], @validator.authentication_header
	end

	def test_ensure_authentication_header
		@m = Mail.new(<<~MAIL)
			Authentication-Results: stuff header.d=payments.interac.ca dkim=pass and
			Authentication-Results: and
			To: someone@example.com
			From: interac@example.com

			body
		MAIL
		@validator = InteracEmail::Validator.new(@m)
		@validator.ensure_authentication_header
	end

	def test_ensure_authentication_header_fail
		@m = Mail.new(<<~MAIL)
			Authentication-Results: stuff header.d=payments.interac.ca dkim=fail and
			Authentication-Results: and
			To: someone@example.com
			From: interac@example.com

			body
		MAIL
		@validator = InteracEmail::Validator.new(@m)
		assert_raises(InteracEmail::Error::BadAuth) do
			@validator.ensure_authentication_header
		end
	end

	def test_ensure_authentication_header_no_interac
		@m = Mail.new(<<~MAIL)
			Authentication-Results: stuff header.d=fakey.fake dkim=pass and
			Authentication-Results: and dkim=pass stuff
			To: someone@example.com
			From: interac@example.com

			body
		MAIL
		@validator = InteracEmail::Validator.new(@m)
		assert_raises(InteracEmail::Error::NoAuth) do
			@validator.ensure_authentication_header
		end
	end
end