10

I'm trying to work out what the best way to secure my staging environment would be. Currently I'm running both staging and production on the same server.

The two options I can think of would be to:

Use rails digest authentication

I could put something like this in the application_controller.rb

# Password protection for staging environment
if RAILS_ENV == 'staging'
  before_filter :authenticate_for_staging
end

def authenticate_for_staging
  success = authenticate_or_request_with_http_digest("Staging") do |username|
    if username == "staging"
      "staging_password"
    end
  end
  unless success
    request_http_digest_authentication("Admin", "Authentication failed")
  end
end

This was ripped from Ryan Daigle's blog. I'm running on the latest Rails 2.3 so I should be free from the security problem they had with this.

Use web server authentication

I could also achieve this using .htaccess or apache permissions, however it makes my server provisioning slightly more complex (I'm using Chef, and would require different apache configs for staging/production).


For now I have the first one implemented and working, do you see ay problems with it? Have I missed something obvious? Thanks in advance!

jonnii
  • 28,019
  • 8
  • 80
  • 108

3 Answers3

25

bumping this to help others, like myself as I read this before settling on an similar, but cleaner solution.

# config/environments/staging.rb

MyApp::Application.configure do
  config.middleware.insert_after(::Rack::Lock, "::Rack::Auth::Basic", "Staging") do |u, p|
    [u, p] == ['username', 'password']
  end

 #... other config
end

I wrote a short blog post about it.

oma
  • 38,642
  • 11
  • 71
  • 99
  • There's also this option, which was added recently: https://github.com/rails/rails/commit/e2b07ee000439d0bd41f725ff9f7ad53e52a7e9b, I like your solution though, I think it's the way to go. – jonnii Apr 06 '11 at 15:02
8

If you are deploying with multi-staging environments and so you have production environment and staging environment, you only need to add these lines to config/environments/staging.rb

MyApp::Application.configure do
  # RESTRICTING ACCESS TO THE STAGE ENVIRONMENT
  config.middleware.insert_before(::Rack::Runtime, "::Rack::Auth::Basic", "Staging") do |u, p|
    u == 'tester' && p == 'secret'
  end

  ...

end

By doing so, you don't need to configure Apache.

I am using Ruby 2 with Rails 4 and it works like a charm!

Diego D
  • 1,706
  • 19
  • 23
1

I would go with the http basic authentication, I see no inherent problems with it.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261