Skip to content

Commit

Permalink
Validate request before attempting redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerhunt committed Mar 15, 2024
1 parent 4c23f0b commit 12708fd
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
15 changes: 9 additions & 6 deletions lib/rack/canonical_host.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'rack'
require 'rack/canonical_host/redirect'
require 'rack/canonical_host/request'
require 'rack/canonical_host/version'

module Rack
Expand All @@ -12,16 +13,18 @@ def initialize(app, host=nil, options={}, &block)
end

def call(env)
request = Request.new(env)

return request.bad_request_response unless request.valid?

host = evaluate_host(env)
redirect = Redirect.new(env, host, options)

begin
return redirect.response unless redirect.canonical?
rescue Addressable::URI::InvalidURIError
return [400, { Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => "0" }, []]
if redirect.canonical?
app.call(env)
else
redirect.response
end

app.call(env)
end

protected
Expand Down
37 changes: 37 additions & 0 deletions lib/rack/canonical_host/request.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
require 'addressable/uri'
require 'rack'

module Rack
class CanonicalHost
class Request
BAD_REQUEST = <<-HTML.gsub(/^\s+/, '')
<!DOCTYPE html>
<html lang="en-US">
<head><title>400 Bad Request</title></head>
<body>
<h1>Bad Request</h1>
</body>
</html>
HTML

def initialize(env)
self.env = env
end

def valid?
Addressable::URI.parse(Rack::Request.new(env).url)
true
rescue Addressable::URI::InvalidURIError
false
end

def bad_request_response
[400, { 'content-type' => 'text/html' }, [BAD_REQUEST]]
end

protected

attr_accessor :env
end
end
end

0 comments on commit 12708fd

Please sign in to comment.