Skip to content

Instantly share code, notes, and snippets.

@dkam
Last active June 10, 2024 01:43
Show Gist options
  • Save dkam/76a0507f76eab9d5070cb993ddf9598c to your computer and use it in GitHub Desktop.
Save dkam/76a0507f76eab9d5070cb993ddf9598c to your computer and use it in GitHub Desktop.
Make PumaDev work with Ruby HTTP Libraries

Puma Dev creates it's own SSL certificate to provide the https://hostname.localhost feature and adds it to your system certificates - but Ruby clients doen't use that. So you need manually add the PumaDev cert to the certs Ruby uses.

For Rails, add a file like config/initializers/puma_dev_client_ssl.rb - but we don't want this in production. Depending on your setup, you may need it in test also.

if Rails.env.development?

  unless File.exist?("/tmp/cert.pem")
    # Create a new cert file including both Puma Dev ssl certificate and Ruby's default certs

    ssl_files = [OpenSSL::X509::DEFAULT_CERT_FILE, "#{Dir.home}/Library/Application Support/io.puma.dev/cert.pem"]
    File.write("/tmp/cert.pem", ssl_files.map { |file| File.read(file) }.join)
  end

  # Tell the Net::HTTP client to use the merged certificate
  module Net
    class HTTP
      alias_method :original_use_ssl=, :use_ssl=
      def use_ssl=(flag)
        self.ca_file = "/tmp/cert.pem"
        self.verify_mode = OpenSSL::SSL::VERIFY_PEER
        self.original_use_ssl = flag
      end
    end
  end
end

From GitHub

You must specify where to find CA certs for ruby to use them.

Create /tmp/cert.pem containing puma-dev CA and all default CAs:

cat $(ruby -e "require 'net/http'; puts OpenSSL::X509::DEFAULT_CERT_FILE") "${HOME}/Library/Application Support/io.puma.dev/cert.pem"  > /tmp/cert.pem

Configure Net::HTTP to use the CA bundle including puma-dev's CA:

module Net
  class HTTP
    alias_method :original_use_ssl=, :use_ssl=
    def use_ssl=(flag)
      self.ca_file = "/tmp/cert.pem"
      self.verify_mode = OpenSSL::SSL::VERIFY_PEER
      self.original_use_ssl = flag
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment