Skip to content

Instantly share code, notes, and snippets.

@Katee
Last active June 8, 2016 16:15
Show Gist options
  • Save Katee/d73f9bf6c077a20b237ebd7de9bb3dd4 to your computer and use it in GitHub Desktop.
Save Katee/d73f9bf6c077a20b237ebd7de9bb3dd4 to your computer and use it in GitHub Desktop.
require 'uri'
require "minitest/autorun"
# Use a module as a shared example
module RedirectTest
def test_with_reasonable_path
assert_equal "/reasonable-path", redirect_path("/reasonable-path")
end
def test_with_reasonable_path_with_query
assert_equal "/reasonable-path?params=true", redirect_path("/reasonable-path?params=true")
end
def test_when_domain_starts_with_at_symbol
assert_equal "/", redirect_path("@kate.io/open-redirect")
end
def test_when_domain_starts_with_dot
assert_equal "/", redirect_path(".kate.io")
end
def test_when_domain_starts_with_dash
assert_equal "/", redirect_path("-.kate.io/open-redirect")
end
def test_when_domain_starts_with_quad_slashes
assert_equal "/", redirect_path("////kate.io/open-redirect")
end
end
def owasp_redirect_path(url)
# taken almost directly from https://www.owasp.org/index.php/Ruby_on_Rails_Cheatsheet#Redirects_and_Forwards
begin
if path = URI.parse(url).path
return path
end
rescue URI::InvalidURIError
return '/'
end
end
class TestOwaspRedirect < Minitest::Test
alias_method :redirect_path, :owasp_redirect_path
include RedirectTest
end
def safe_redirect_path(url, default_path = '/')
uri = URI.parse(url)
path = uri.path
path = "#{uri.path}"
path += "?#{uri.query}" if uri.query
raise URI::InvalidURIError unless path.start_with?("/")
raise URI::InvalidURIError if path.start_with?("//")
path
rescue URI::InvalidURIError
default_path
end
class TestSafeRedirect < Minitest::Test
alias_method :redirect_path, :safe_redirect_path
include RedirectTest
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment