Module: Lotus::Action::CSRFProtection

Defined in:
lib/lotus/action/csrf_protection.rb

Overview

CSRF Protection

This security mechanism is enabled automatically if sessions are turned on.

It stores a “challenge” token in session. For each “state changing request” (eg. POST, PATCH etc..), we should send a special param: _csrf_token.

If the param matches with the challenge token, the flow can continue. Otherwise the application detects an attack attempt, it reset the session and Lotus::Action::InvalidCSRFTokenError is raised.

We can specify a custom handling strategy, by overriding #handle_invalid_csrf_token.

Form helper (#form_for) automatically sets a hidden field with the correct token. A special view method (#csrf_token) is available in case the form markup is manually crafted.

We can disable this check on action basis, by overriding #verify_csrf_token?.

Examples:

Custom Handling

module Web::Controllers::Books
  class Create
    include Web::Action

    def call(params)
      # ...
    end

    private

    def handle_invalid_csrf_token
      Web::Logger.warn "CSRF attack: expected #{ session[:_csrf_token] }, was #{ params[:_csrf_token] }"
      # manual handling
    end
  end
end

Bypass Security Check

module Web::Controllers::Books
  class Create
    include Web::Action

    def call(params)
      # ...
    end

    private

    def verify_csrf_token?
      false
    end
  end
end

See Also:

Since:

  • 0.4.0

Constant Summary collapse

CSRF_TOKEN =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Session and params key for CSRF token.

This key is shared with lotus-controller and lotus-helpers

Since:

  • 0.4.0

:_csrf_token
IDEMPOTENT_HTTP_METHODS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Idempotent HTTP methods

By default, the check isn’t performed if the request method is included in this list.

Since:

  • 0.4.0

Hash[
  'GET'     => true,
  'HEAD'    => true,
  'TRACE'   => true,
  'OPTIONS' => true
].freeze

Class Method Summary collapse

Class Method Details

.included(action) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 0.4.0



95
96
97
98
99
# File 'lib/lotus/action/csrf_protection.rb', line 95

def self.included(action)
  action.class_eval do
    before :set_csrf_token, :verify_csrf_token
  end unless Lotus.env?(:test)
end