Class: RuboCop::Cop::DevDoc::Route::ResourcesRequireOnly

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dev_doc/route/resources_require_only.rb

Overview

Always use ‘only:` (or `except:`) for `resources` / `resource` in routes.rb.

## Rationale When defining routes in routes.rb, it is important to explicitly specify the desired actions using the ‘only` option. This helps prevent accidentally exposing actions that should not be accessible — leaving the default opens the full RESTful set, which often exposes routes the application has no controller action for, or routes that probably should be locked down.

✔️
resources :job_applications, only: [:index, :new, :create]

In this example, only three actions are exposed for ‘job_applications`: index, new, and create. This is safer because only the needed actions are declared and accessible.

‘except:` is also acceptable, but `only:` is preferred because it is more explicit about what is being exposed.

Examples:

# bad
resources :users
resource :profile

# good
resources :users, only: %i[index show]
resource :profile, only: %i[show edit update]
resources :users, except: [:destroy]

Constant Summary collapse

MSG =
'Specify `only:` or `except:` for `%<method>s :%<name>s` to avoid exposing unintended actions.'.freeze
RESTRICT_ON_SEND =
%i[resources resource].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



38
39
40
41
42
43
# File 'lib/rubocop/cop/dev_doc/route/resources_require_only.rb', line 38

def on_send(node)
  return if only_or_except?(node)

  name = node.first_argument&.value || '?'
  add_offense(node.loc.selector, message: format(MSG, method: node.method_name, name: name))
end