aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/action_mailbox/ingresses/mailgun/inbound_emails_controller.rb
blob: 4d194a3e0042c12fbb568eea22b5288bf4ba6334 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class ActionMailbox::Ingresses::Mailgun::InboundEmailsController < ActionMailbox::BaseController
  before_action :ensure_authenticated

  def create
    ActionMailbox::InboundEmail.create_and_extract_message_id! raw_email
    head :ok
  end

  private
    def raw_email
      StringIO.new params.require("body-mime")
    end


    def ensure_authenticated
      head :unauthorized unless authenticated?
    end

    def authenticated?
      Authenticator.new(authentication_params).authenticated?
    rescue ArgumentError
      false
    end

    def authentication_params
      params.permit(:timestamp, :token, :signature).to_h.symbolize_keys
    end


    class Authenticator
      cattr_accessor :key

      attr_reader :timestamp, :token, :signature

      def initialize(timestamp:, token:, signature:)
        @timestamp, @token, @signature = timestamp, token, signature
      end

      def authenticated?
        signed? && recent?
      end

      private
        def signed?
          ActiveSupport::SecurityUtils.secure_compare signature, expected_signature
        end

        # Allow for 10 minutes of drift between Mailgun time and local server time.
        def recent?
          time >= 10.minutes.ago
        end

        def expected_signature
          OpenSSL::HMAC.hexdigest OpenSSL::Digest::SHA256.new, key, "#{timestamp}#{token}"
        end

        def time
          Time.at Integer(timestamp)
        end
    end
end