8

I'm looking for a simple way to enable SSL in a standalone Sinatra application running via Thin without having to pass the --ssl, --ssl-key-file and --ssl-cert-file parameters in via the Thin command line.

Is it possible to define them directly within the Sinatra app or via a config.ru file?

I've spent several hours looking for an answer to this question, but so far have not found anything that works.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user1513388
  • 7,165
  • 14
  • 69
  • 111

3 Answers3

10

I just spent a few hours trying to figure this one out myself.

It turns out that Thin::Server.initialize discards ssl options during its initialization method (it delegates to its instance of Backend, which immediately sets its ssl to nil, ignoring any ssl options you've passed into Thin::Server.new. This means you have to to set ssl options after you've instantiated a server.)

Here's how to do it:

class App < Sinatra::Base

  # ...

  def self.run!
    rack_handler_config = {}

    ssl_options = {
      :private_key_file => '/path/to/foo.key',
      :cert_chain_file => '/path/to/bar.crt',
      :verify_peer => false,
    }

    Rack::Handler::Thin.run(self, rack_handler_config) do |server|
      server.ssl = true
      server.ssl_options = ssl_options
    end
  end
end

App.run!
pje
  • 21,801
  • 10
  • 54
  • 70
9

These days (sinatra 1.4.1) run! accepts a block that yields server. So you can do this:

MyApp.run! do |server|
  ssl_options = {
    :cert_chain_file => '/path/to/bar.crt',
    :private_key_file => '/path/to/foo.key',
    :verify_peer => false
  }
  server.ssl = true
  server.ssl_options = ssl_options
end
artemave
  • 6,786
  • 7
  • 47
  • 71
  • 1
    Very Cool! Where are these options documented? - I can't seem to find anything other than your post! – user1513388 Apr 13 '13 at 15:59
  • 1
    http://rdoc.info/github/eventmachine/eventmachine/EventMachine/Connection:start_tls is apparently what's happening here. – Swizzlr Dec 16 '13 at 17:05
1

I'm running Sinatra and Thin (on Heroku) with SSL using the Rack::SslEnforcer, doing this:

if production?
    require 'rack/ssl-enforcer'
    use Rack::SslEnforcer
end

This should be before you enable :sessions in your file.

Frank
  • 143
  • 1
  • 9