2

After requiring open-uri, one can conveniently download and use files from the web via Kernel#open. However, trying to do this with https results in a root cert error, because ruby doesn't have all the root certs.

This can be solved like this, but that's for using a Net::HTTP object with a block.

Is there an elegant way to set use_ssl and ca_file for the Net::HTTP library globally, so that it will apply to my whole app, and commands like Kernel#open?

John Bachir
  • 22,495
  • 29
  • 154
  • 227

2 Answers2

3

Alright, after a couple hours I came up with this:

require 'open-uri'
require 'net/https'

module Net
  class HTTP
    alias_method :original_use_ssl=, :use_ssl=
    def use_ssl=(flag)
      self.ca_file = "/path/to/ca-bundle.crt"
      self.original_use_ssl = flag
    end
  end
end

Described more here: https://gist.github.com/996510

John Bachir
  • 22,495
  • 29
  • 154
  • 227
  • I'd like to add that this worked as a solution for me to get CarrierWave's remote_url function(where you can add attachment via remote url over https) Thanks! https://groups.google.com/forum/?fromgroups=#!topic/carrierwave/HQxayNjVAs4 – Peter P. Feb 19 '13 at 20:12
1

This might not be an answer to exactly what you asked, but I ended up here while looking for a way to specify ca_file with open-uri. After digging around in the open-uri source code, I found that there are various options you can pass to open, including one called ssl_ca_cert. So to specify CA certificate(s) you can simply use something like:

URI.open('https://example.com/', ssl_ca_cert: '/path/to/ca-bundle.crt')

# or using older hash syntax:
URI.open('https://example.com/', :ssl_ca_cert => '/path/to/ca-bundle.crt')
kwc
  • 307
  • 2
  • 8