Skip to content

Instantly share code, notes, and snippets.

@rbarazi
Forked from Papierkorb/ssl_hack.rb
Created June 15, 2016 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbarazi/36b0d94819f51fcfb9a94bb71c426bde to your computer and use it in GitHub Desktop.
Save rbarazi/36b0d94819f51fcfb9a94bb71c426bde to your computer and use it in GitHub Desktop.
SSL with Capybara and Selenium
# Hack for Capybara to use SSL connections using selenium.
#
### Usage:
# Require this from rails_helper.rb
#
### Steps to generate a SSL certificate on a Linux box:
# 0. Starting from 'Rails.root'
# 1. Generate private key. Type in some password.
# $ openssl genrsa -des3 -out private.key 4096
# 2. Generate certificate sign request
# $ openssl req -new -key private.key -out server.csr
# 3. Store decrypted private key in test/. Type in your password from before.
# Then, get rid of the original private key file.
# $ openssl rsa -in private.key -out test/private.key
# $ shred private.key && rm private.key
# 4. Self-sign your new server certificate
# $ openssl x509 -req -days 3650 -in server.csr -signkey test/private.key -out test/certificate.pem
##### - DONE!
# Monkey patched responsive? for SSL. Taken from:
# https://github.com/jnicklas/capybara/issues/1121
module Capybara
class Server
def responsive?
return false if @server_thread && @server_thread.join(0)
http = Net::HTTP.new(host, @port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = http.get('/__identify__')
if res.is_a?(Net::HTTPSuccess) or res.is_a?(Net::HTTPRedirection)
return res.body == @app.object_id.to_s
end
rescue SystemCallError
return false
end
end
end
# Helper class to start a WEBrick server with SSL
class SslServer
TEST_CERTIFICATE = Rails.root.join('test', 'certificate.pem').to_s
TEST_PRIVATE_KEY = Rails.root.join('test', 'private.key').to_s
require 'rack/handler/webrick'
require 'webrick/https'
def initialize
@certificate = OpenSSL::X509::Certificate.new File.read TEST_CERTIFICATE
@key = OpenSSL::PKey::RSA.new File.read TEST_PRIVATE_KEY
end
def run(app, port)
options = {
Port: port,
AccessLog: [],
Logger: WEBrick::Log::new(nil, 0),
SSLEnable: true,
SSLCertificate: @certificate,
SSLPrivateKey: @key
}
Rack::Handler::WEBrick.run app, options
end
end
# Configure Capybara for SSL.
RSpec.configure do |config|
Capybara.register_driver :selenium_ssl do |app|
profile = Selenium::WebDriver::Firefox::Profile.new
profile.secure_ssl = false
profile.assume_untrusted_certificate_issuer = false
Capybara::Selenium::Driver.new app, browser: :firefox, profile: profile
end
Capybara.javascript_driver = :selenium_ssl
Capybara.app_host = "https://#{Capybara.server_host}:#{Capybara.server_port}"
Capybara.server do |app, port|
server = SslServer.new
server.run app, port
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment