How can I password-protect my /sidekiq route (i.e. require authentication for the Sidekiq::Web tool)?

前端 未结 8 1409
太阳男子
太阳男子 2021-02-01 00:52

I am using sidekiq in my rails application. By Default, Sidekiq can be accessed by anybody by appending \"/sidekiq\" after the url. I want to password protect / authenticate onl

8条回答
  •  天命终不由人
    2021-02-01 01:31

    The accepted answer is good, but I think that it can be implemented more securely, as Sidekiq documentation mentions (it got edited to demonstrate the right solution after I posted).

    To protect your app against timing attacks, use ActiveSupport::SecurityUtils.secure_compare.

    • See https://codahale.com/a-lesson-in-timing-attacks/
    • See https://thisdata.com/blog/timing-attacks-against-string-comparison/

    Also, use & (do not use &&) so that it doesn't short circuit.

    And finally, use digests to stop length information leaking (default of secure_compare in Active Support 5).

    So, in an initializer file, typically in config/initializers/sidekiq.rb in Rails projects, depending of your version of Active Support/Rails, write the following.

    Active Support 5+: Thanks to Rails PR #24510, parameters passed to secure_compare are going through Digest::SHA256.hexdigest by default.

    require 'active_support/security_utils'
    require 'sidekiq'
    require 'sidekiq/web'
    
    Sidekiq::Web.use(Rack::Auth::Basic) do |user, password|
      # Protect against timing attacks:
      # - See https://codahale.com/a-lesson-in-timing-attacks/
      # - See https://thisdata.com/blog/timing-attacks-against-string-comparison/
      # - Use & (do not use &&) so that it doesn't short circuit.
      # - Use digests to stop length information leaking
      ActiveSupport::SecurityUtils.secure_compare(user, ENV["SIDEKIQ_ADMIN_USER"]) &
        ActiveSupport::SecurityUtils.secure_compare(password, ENV["SIDEKIQ_ADMIN_PASSWORD"])
    end
    

    Active Support 4:

    require 'active_support/security_utils'
    require 'sidekiq'
    require 'sidekiq/web'
    
    Sidekiq::Web.use(Rack::Auth::Basic) do |user, password|
      # Protect against timing attacks:
      # - See https://codahale.com/a-lesson-in-timing-attacks/
      # - See https://thisdata.com/blog/timing-attacks-against-string-comparison/
      # - Use & (do not use &&) so that it doesn't short circuit.
      # - Use digests to stop length information leaking
      ActiveSupport::SecurityUtils.secure_compare(
        ::Digest::SHA256.hexdigest(user),
        ::Digest::SHA256.hexdigest(ENV["SIDEKIQ_ADMIN_USER"])
      ) &
        ActiveSupport::SecurityUtils.secure_compare(
          ::Digest::SHA256.hexdigest(password),
          ::Digest::SHA256.hexdigest(ENV["SIDEKIQ_ADMIN_PASSWORD"])
        )
    end
    

提交回复
热议问题