Ссылка бренда Sendgrid с прокси nginx - PullRequest
0 голосов
/ 28 августа 2018

Мы пытаемся установить ссылку на бренд с пользовательским ssl с этим документом https://sendgrid.com/docs/ui/account-and-settings/custom-ssl-configurations/.

Мы следуем ему, и теперь у нас есть прокси-сервер с сертификатом, который перенаправляется на sendgrid.net.

Служба поддержки сообщает нам, что их тест говорит: «СБОЙ: Мы не получили ответ 200 от тестовой ссылки« https »». И скажите нам также, что сертифицированный шаблон на прокси не поддерживается.

Я не понимаю причину подстановочного знака, и прокси отправляет не 200, потому что sendgrid.net отправляет 404

Так что я не понимаю, что делать.

Мы используем nginx и этот пример для реализации нашего прокси: https://gist.github.com/jjhiew/cbbd26da313fc550467e303a6c6f8177

1 Ответ

0 голосов
/ 31 мая 2019

Спасибо за напоминание. У нас это работает, но я забыл опубликовать это здесь. Общая идея состоит в том, чтобы отправлять запросы на клики под брендом на наш собственный сервер, имеющий сертификат TLS. То есть link.mysite.com идет на наш собственный сервер вместо SendGrid. Наш сервер принимает эти запросы, делает идентичные запрос к SendGrid. Все, что SendGrid отвечает на наш сервер, мы отправляем обратно в браузер.

Я не уверен, но я думаю, что люди из службы поддержки SendGrid должны были переключить переключатель. Но это может быть неправильно. Я помню, я говорил с ними, и я помню, что они не понимали эту ситуацию с прокси. Я наконец нашел кого-то, кто сделал, или я заставил это работать без них, я не уверен.

Ниже приведен код, который мы используем для этого (Ruby on Rails):

# Allow SendGrid Click Tracking to use HTTPS
#
# SendGrid click tracking uses the host 'link.example.com' but HSTS requires that host
# respond to HTTPS. However SendGrid does not have our certificate. So instead point
# link.example.com to this proxy, and we make the same request to sendgrid.
#
# see: https://sendgrid.com/docs/ui/account-and-settings/custom-ssl-configurations/
#
# Configuring SendGrid, Heroku, and DNSimple for Click Tracking and unsubscribes
# ------------------------------------------------------------------------------
#   Sendgrid > Sender Authentication > Link Branding
#     Create branded link for example.com
#     Advanced Settings > Custom link subdomain: link
#
#   DNS > make the CNAME records they mention
#   Sendgrid >
#     verify branded links so they are activated.
#     Make link the default.
#
#   Heroku > configure subdomain for link.example.com
#   DNS > change CNAME record so link.example.com points to Heroku, e.g. blah.blah.herokudns.com
#
#   Test:
#       Unsubscribe links that start with link.example.com/___ should work now.
#
#   Sendgrid > Tracking > Click Tracking > ON
#
#   Test:
#     Send a test Frisky Friday.
#     Follow link to article--it should start with link.example.com
#     SendGrid increments the Click Tracking counter
class SendgridLinkProxyController < ActionController::Base
  SENDGRID_CLICK_TRACKING_URL = 'https://sendgrid.net'.freeze

  def index
    # Make matching request to SendGrid
    sendgrid_url = URI.parse("#{SENDGRID_CLICK_TRACKING_URL}#{request.env['ORIGINAL_FULLPATH']}").to_s
    sendgrid_headers = { 'Host' => CFG.SENDGRID_PROXY_HOSTNAME }

    Rails.logger.info("sendgrid_link_proxy_controller.rb: fetching #{sendgrid_url}, headers: #{sendgrid_headers}")
    sendgrid_response = HTTParty.get(sendgrid_url, headers: sendgrid_headers, follow_redirects: false) # , debug_output: STDOUT)

    # Make matching response to browser
    user_response_status = sendgrid_response.code
    response.set_header('location', sendgrid_response.headers['location'])
    Rails.logger.info("sendgrid_link_proxy_controller.rb: responding status_code: #{user_response_status}, location header: #{response.header['location']}")
    render html: sendgrid_response.body.html_safe, # We are trusting SendGrid. Winston think's that's OK. [Winston Dec 2018]
           status: user_response_status
  end
end

И вот файл RSpec для этого:

require 'spec_helper'

describe SendgridLinkProxyController do

  describe '#index' do
    before do
      @sendgrid_response = {
        headers: {},
        body: '<html>SENDGRID BODY</html>',
        code: 200
      }
      request.env['ORIGINAL_FULLPATH'] = '/wf/click?upn=BLAH'
      CFG.SENDGRID_PROXY_HOSTNAME = 'link.example.com'
    end

    subject do
      allow(HTTParty)
        .to receive(:get)
        .and_return(double('Mock Sendgrid Response', @sendgrid_response))
      get :index, params: {a: 'click'}
    end

    it 'requests page from sendgrid with same path and with Host header' do
      expect(HTTParty).to receive(:get)
        .with('https://sendgrid.net/wf/click?upn=BLAH',
              headers: { 'Host' => 'link.example.com' },
              follow_redirects: false
             )

      subject
    end

    context 'when receiving a click-tracking redirect link' do
      before do
        @sendgrid_response[:code] = 302
        @sendgrid_response[:headers]['location'] = 'https://example.com/TARGET'
      end

      it 'redirects browser to target link' do
        subject

        expect(response.status).to eq(302)
        expect(response.headers['location']).to eq('https://example.com/TARGET')
      end
    end

    context 'when receiving an unsubcribe link' do
      before do
        request.env['ORIGINAL_FULLPATH'] = '/wf/unsubscribe?upn=BLAH'
      end

      it 'renders sendgrid\'s unsubscribe page' do
        subject

        expect(response.body).to eq('<html>SENDGRID BODY</html>')
      end
    end
  end
end
...