Module: OpenURI

Defined in:
lib/omnibus/core_extensions/open_uri.rb

Defined Under Namespace

Classes: Buffer

Class Method Summary collapse

Class Method Details

.default_redirectable?(uri1, uri2) ⇒ Boolean Also known as: redirectable?

The is a bug in Ruby’s implementation of OpenURI that prevents redirects from HTTP -> HTTPS. That should totally be a valid redirect, so we override that method here and call it a day.

Note: this does NOT permit HTTPS -> HTTP redirects, as that would be a major security hole in the fabric of space-time!

Returns:

  • (Boolean)


13
14
15
16
17
# File 'lib/omnibus/core_extensions/open_uri.rb', line 13

def default_redirectable?(uri1, uri2)
  a, b = uri1.scheme.downcase, uri2.scheme.downcase

  a == b || (a == "http" && b == "https")
end

.open_uri(name, *rest, &block) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/omnibus/core_extensions/open_uri.rb', line 42

def open_uri(name, *rest, &block)
  options = rest.find { |arg| arg.is_a?(Hash) } || {}

  if options.delete(:allow_unsafe_redirects)
    class << self
      alias_method :redirectable?, :unsafe_redirectable?
    end
  end

  original_open_uri(name, *rest, &block)
ensure
  class << self
    alias_method :redirectable?, :default_redirectable?
  end
end

.original_open_uriObject

Override the default open_uri method to search for our custom option to permit unsafe redirects.

Examples:

open('http://example.com', allow_unsafe_redirects: true)


41
# File 'lib/omnibus/core_extensions/open_uri.rb', line 41

alias_method :original_open_uri, :open_uri

.unsafe_redirectable?(uri1, uri2) ⇒ true

Permit all redirects.

Note: this DOES permit HTTP -> HTTP redirects, and that is a major security hole!

Returns:

  • (true)


28
29
30
31
32
# File 'lib/omnibus/core_extensions/open_uri.rb', line 28

def unsafe_redirectable?(uri1, uri2)
  a, b = uri1.scheme.downcase, uri2.scheme.downcase

  a == b || (a == "http" && b == "https") || (a == "https" && b == "http")
end