Skip to content

Instantly share code, notes, and snippets.

@dasibre
Forked from speedmax/ssl_requirement_spec.rb
Last active July 21, 2020 11:30
Show Gist options
  • Save dasibre/c95c710c9187652a108ea8ffb4ccb52e to your computer and use it in GitHub Desktop.
Save dasibre/c95c710c9187652a108ea8ffb4ccb52e to your computer and use it in GitHub Desktop.
How to test rack middleware example
require 'spec_helper'
# Based on https://github.com/rails/ssl_requirement/blob/master/lib/ssl_requirement.rb
class SslRequirement
def initialize(app, options= {})
@app = app
@allowed = options[:allowed]
@required = options[:required]
end
def call(env)
@env = env
redirect_to = url_with_proper_protocol
if redirect_to.is_a?(String)
return [ 301, {"Location" => redirect_to}, [] ]
end
@app.call @env
end
def ssl_required?
@required && host_and_path =~ @required
end
def ssl_allowed?
@allowed && host_and_path =~ @allowed
end
private
def request
Rack::Request.new @env
end
def host_and_path
request.host + request.fullpath
end
def url_with_proper_protocol
return true if ssl_allowed?
return_to = nil
if ssl_required? && request.port != 443
return_to = "https://" + host_and_path
elsif request.port == 443 && !ssl_required?
return_to = "http://" + host_and_path
end
return_to
end
end
describe SslRequirement do
let(:app) { ->(env) { [200, env, "app"] } }
let :middleware do
SslRequirement.new(app, required: /^admin.example.com/ )
end
it "redirects to secure protocol" do
code, env = middleware.call env_for('http://admin.example.com')
code.should == 301
env['Location'].should == 'https://admin.example.com/'
end
it "shouldn't redirect for non matching ssl requirement" do
code, env = middleware.call env_for('http://help.example.com')
code.should == 200
end
it "redirects to non-secure site for non matching ssl requirement'" do
code, env = middleware.call env_for('https://content.example.com')
code.should == 301
env["Location"].should == "http://content.example.com/"
end
it "allows certain url with secured protocol" do
middleware = SslRequirement.new(app, allowed: /^help.example.com/ )
code, env = middleware.call env_for('https://help.example.com')
code.should == 200
env["Location"].should == nil
end
def env_for url, opts={}
Rack::MockRequest.env_for(url, opts)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment