Commit Graph

14697 Commits

Author SHA1 Message Date
Steven Petryk 5f0d089f5e Clarify passing an array as a cookie's domain
When working through an issue, I found myself a little confused stumbling upon some code like this:

```rb
cookies[...] = {
  # ...
  domain: %w(.site.io .site.com)
}
```

In my mind I was thinking "is this some weird part of the cookie spec? or is this Rails?" and the docs didn't offer much insight into how it works. Going back into the commit where that line was added, the folks who added it were confused to until someone linked to the source.

I figured that clarifying this in the docs would be useful. Of course, people should know how cookies work before fiddling with them (unlike me), but since cookies are so sensitive, I think the docs should opt for being explicit about this.

Co-Authored-By: Norm Provost <norman.provost@intercom.io>
2020-02-06 16:49:17 -08:00
Ryuta Kamizono 051e349041 Prefer faster `str.start_with?` over `str.first ==`
```ruby
str = "abc"

Benchmark.ips do |x|
  x.report("start_with?") { str.start_with?("a") }
  x.report("first ==")    { str.first == "a" }
end
```

```
Warming up --------------------------------------
         start_with?   282.381k i/100ms
            first ==   207.305k i/100ms
Calculating -------------------------------------
         start_with?     10.239M (± 2.2%) i/s -     51.393M in   5.022151s
            first ==      4.593M (± 4.5%) i/s -     23.011M in   5.021434s
```
2020-02-05 19:15:33 +09:00
Ryuta Kamizono b803ed012c Make `localize` helper takes keyword arguments the same with `I18n.localize` 2020-02-05 18:49:44 +09:00
Ryuta Kamizono 6c02fee08f Make `translate` helper takes keyword arguments the same with `I18n.translate` 2020-02-05 18:04:27 +09:00
Ryuta Kamizono a33dbb17b0 Follow up fa986ae0ca 2020-02-05 14:31:11 +09:00
Ryuta Kamizono 1dac170c23 Use string eval instead of `define_method` for integration session method delegation
This is an alternative of b7e591a and a43de73.

Handling `if options.any?` is not preferable solution for kwargs.
2020-02-05 10:20:29 +09:00
Ryuta Kamizono 9b797b93f4 `delegate` allows multiple method names are passed 2020-02-05 09:55:28 +09:00
Ryuta Kamizono df81f2e5f5 Use `transform_values` to avoid extra Array allocation 2020-01-27 11:03:35 +09:00
Xavier Noria cb3b37b379 Deletes the private method add_template_helper
The method add_template_helper is private and used only in one place.
I guess its purpose was to remove the noise of module_eval at the cost
of an indirection.

However, Module#include is public since Ruby 2.1, and the indirection
is no longer justified for my taste. The loop in the caller is more
straightforward now.
2020-01-26 14:28:40 +01:00
Bibek Shrestha 0ac0afc3d0 Use path instead of fullpath on validating authenticity token
PR #38211 introduced a bug where URLs with query_params
will fail to validate authenticity token.

This PR changes changes fullpath to path to fix the bug.
I've also added a test with query_params
2020-01-23 13:08:36 -05:00
Adam Hess 85f95b2f58 prevent helper_method from calling to_hash
`helper_method` was taking `**kwargs` on all definitions by default.
ruby will assume that this means you want keyword args and call
`to_hash` on what you pass if the object responds to `to_hash`. Instead
we should only take keyword args if the helper method defined intends
to pass keyword args.

This also fixes a warning when you pass a hash to your helper method,

```
warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
```

Also, this would be a good candidate for using `...`, but since `send`
requires the method as the first argument, we can't use it here.
2020-01-14 15:33:33 -08:00
Kevin Deisz e4c035a8fb
Fix warning on arg forwarding in integration tests
Kwargs need to be forwarded for this method_missing to avoid warnings in Ruby 2.7.
2020-01-13 11:19:31 -05:00
Ryuta Kamizono a6a4222384 rack 2.1.0 changed expires date format from rfc2822 to httpdate
See https://github.com/rack/rack/pull/1144.
2020-01-11 15:09:50 +09:00
Aaron Patterson c2d7bdc6cc
Merge pull request #38211 from rails/do-not-reparse-path-info
Do not re-parse PATH_INFO when validating authenticity token
2020-01-10 12:38:01 -08:00
Aaron Patterson 08e4a71d02
Do not re-parse PATH_INFO when validating authenticity token
PATH_INFO will never contain query parameters (that is the contract with
the webserver), so there is no reason to call URI.parse on it.  In
addition, clients can send garbage paths that raise an exception when
being parsed rather than just failing the auth token check.
2020-01-10 11:16:57 -08:00
abcang b9fac5c3d6 Fix ActionController::TestSession#id to return Rack::Session::SessionId instance (#38063)
* Fix ActionController::TestSession#id to return Rack::Session::SessionId instance

* test SessionId#public_id

* test session["session_id"]

Co-authored-by: Benjamin Quorning <22333+bquorning@users.noreply.github.com>
2020-01-10 13:48:42 -05:00
George Claghorn de853a296f Address Ruby 2.7 kwargs warning in ActionDispatch::SystemTesting::Driver 2020-01-09 12:01:14 -05:00
Rafael França 031763ab5c
Merge pull request #38169 from gsamokovarov/rails-middleware-move-before-after
Delayed middleware delete does not allow move operations
2020-01-08 12:17:26 -03:00
Genadi Samokovarov 40fc1651ad Delayed middleware delete does not allow move operations
While trying to fix #16433, we made the middleware deletions always
happen at the end. While this works for the case of deleting the
Rack::Runtime middleware, it makes operations like the following
misbehave.

```ruby
gem "bundler", "< 1.16"

begin
  require "bundler/inline"
rescue LoadError => e
  $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
  raise e
end

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "rails", github: "rails/rails"
end

require "action_controller/railtie"

class TestApp < Rails::Application
  config.root = __dir__
  secrets.secret_key_base = "secret_key_base"

  config.logger = Logger.new($stdout)
  Rails.logger  = config.logger

  middleware.insert_after ActionDispatch::Session::CookieStore, ::Rails::Rack::Logger, config.log_tags
  middleware.delete ::Rails::Rack::Logger
end

require "minitest/autorun"
require "rack/test"

class BugTest < Minitest::Test
  include Rack::Test::Methods

  def test_returns_success
    get "/"
    assert last_response.ok?
  end

  private
    def app
      Rails.application
    end
end
```

In the case ☝️  the ::Rails::Rack::Logger would be deleted instead of
moved, because the order of middleware stack building execution will be:

```ruby
[:insert, ActionDispatch::Session::CookieStore, [::Rails::Rack::Logger]]
[:delete, ::Rails::Rack::Logger, [config.log_tags]]
```

This is pretty surprising and hard to reason about behaviour, unless you
go spelunking into the Rails configuration code.

I have a few solutions in mind and all of them have their drawbacks.

1. Introduce a `Rails::Configuration::MiddlewareStackProxy#delete!` that
delays the deleted operations. This will make `#delete` to be executed
in order. The drawback here is backwards incompatible behavior and a new
public method.

2. Just revert to the old operations. This won't allow people to delete
the `Rack::Runtime` middleware.

3. Legitimize the middleware moving with the new `#move_after` and
`#move_before` methods. This does not breaks any backwards
compatibility, but includes 2 new methods to the middleware stack.

I have implemented `3.` in this pull request.

Happy holidays! 🎄
2020-01-08 11:30:02 +02:00
Adam Hegyi e0eff2c3dd Memoize regex when checking missing route keys
When the route definition has parameters, we can supply a regex for
validation purposes:

    get "/a/:b" => "test#index", constraints: { b: /abc/ }, as: test

This regex is going to be used to check the supplied values during
link generation:

    test_path("abc") # check "abc" against /abc/ regex

The link generation code checks each parameter. To properly validate the
parameter, it creates a new regex with start and end of string modifiers:

    /\A#{original_regex}\Z/

This means for each link generation the code stringifies the existing
regex and creates a new one. When a new regex is created, it needs to be
compiled, for large regexes this can take quite a bit of time.

This change memoizes the generated regex for each route when constrains
are given. It also removes the RegexCaseComparator class since it is not
in use anymore.
2020-01-08 08:36:29 +01:00
IWASE 8e9c48b580 Add AC::TestSession#dig method like AD::Request::Session 2020-01-08 15:18:59 +09:00
Eileen M. Uchitelle ee2ec97372
Merge pull request #37955 from Manfred/named-routes-metal-integration
Prevent NoMethodError on named route in integration test
2020-01-07 12:15:27 -05:00
Rodrigo Ramírez Norambuena 9b92b1fb6d Add match 302 http code for log in redirect_to 2020-01-04 22:29:45 -03:00
Rafael Mendonça França 7b29bc2179
Merge pull request #38150 from kbrock/all_trusted_ips
When all IPs are trusted, use the furthest away
2020-01-03 19:00:23 -03:00
Keenan Brock b17aaae811 trusted IP changelog 2020-01-03 13:32:44 -05:00
Matthew Draper d160a8d637 When all IPs are trusted, use the furthest away
Scenario: we have a REMOTE_ADDR of `127.0.0.1`, and X-Forwarded-For is
`A, B, C`.

Without any relevant trust, the `remote_ip` is `C`.

If `C` is trusted, then the `remote_ip` is `B`.

If `B` and `C` are trusted, then the `remote_ip` is `A`.

If all of `A`, `B`, and `C` are trusted, then the `remote_ip` should
still be `A`: if our trust was sufficient to get that far out before,
trusting something else should not have us fall back to `127.0.0.1`.

It is this last situation that we're correcting here:

We trust `A` to give us accurate X-Forwarded-For information, yet it has
chosen to leave it unset. Therefore, `A` is telling us that it is itself
the client.
2020-01-03 09:03:23 -05:00
Rafael França 56d72c2caf
Merge pull request #38139 from roramirez/log-for-no-exten
Add to the log format "*/*" if using a not found format:
2020-01-02 20:22:00 -03:00
Rodrigo Ramírez Norambuena 11b7943723 Add to the log format "*/*" if using a not found format:
The rendering template is processing as */* but in the log is
  "Processing by Controller#action as "

This change add the */* for the log and showing as
  "Processing by Controller#action as */*"
when there not founds for the extension of format.
2020-01-02 16:45:47 -03:00
Edouard CHIN 91b6253ade Mime::Mimes#symbols should return a always up to date reference:
- Original issue was reported in https://github.com/rails/rails/issues/38094
  and a fix attempted in https://github.com/rails/rails/pull/38126 but
  it's not the proper fix I think.

  TL;DR Is that `ActionView::Base.default_formats` holds a copy of
  mime symbols at the time ActionView::Base is loaded.
  So if you try to register mime types after ActionView Base is loaded
  then it won't work.

  ```ruby
    ActionView::Base.default_formats ||= Mime::SET.symbols # Note that this is automatically done when ActionView get loaded 22483b86a6/actionpack/lib/action_dispatch.rb (L117)

   Mime::Type.register_alias "application/xhtml+xml", :foobar
   puts ActionView::base.defaults_formats.include?(:foobar) # => false
  ```

  Same issue if you try to unregister a mime after ActionView is loaded.
  That's what was happening in the flaky test:

  ```
   Mime::Type.register_alias "application/xhtml+xml", :foobar
   ActionView::Base.default_formats ||= Mime::SET.symbols

   puts ActionView::base.defaults_formats.include?(:foobar) # => true

   Mime::Type.unregister(:foobar)
   puts ActionView::base.defaults_formats.include?(:foobar) # => true
  ```

  ### Solution

  Return a refence to `@symbols` which is updated each time a new mime is
  registered/unregistered.
2020-01-02 18:05:33 +01:00
Ryuta Kamizono 785427b88c Merge pull request #38132
Closes #38132
2020-01-02 17:29:00 +09:00
Yasuo Honda c667a725f1 Remove `ENV['TRAVIS']`
Rather than replace `ENV['TRAVIS']` with `ENV['CI']`, I think we can
remove this condition because `ENV['TRAVIS']` is not valid at Buildkite
then Rails CI has been running with `PROCESS_COUNT` about 9 month
since this e485c14a3e
2020-01-02 09:23:06 +09:00
Abhay Nikam d8beb77252 Bump license years from 2019 to 2020 [ci skip] 2020-01-01 15:10:31 +05:30
Yasuo Honda b0714b5f28 Address StarStarMimeControllerTest#test_javascript_with_no_format_only_star_star failure
Fix #38094

* Steps to reproduce:

```ruby
% cd actionpack
% MT_CPU=0 bundle exec ruby -w -Itest test/controller/mime/accept_format_test.rb -n "/^(?:MimeControllerLayoutsTest#(?:test_missing_layout_renders_properly)|StarStarMimeControllerTest#(?:test_javascript_with_no_format_only_star_star))$/" --verbose --seed 15759
```

* Actual result without this commit:

```ruby
% cd actionpack
% MT_CPU=0 bundle exec ruby -w -Itest test/controller/mime/accept_format_test.rb -n "/^(?:MimeControllerLayoutsTest#(?:test_missing_layout_renders_properly)|StarStarMimeControllerTest#(?:test_javascript_with_no_format_only_star_star))$/" --verbose --seed 15759
Run options: -n "/^(?:MimeControllerLayoutsTest#(?:test_missing_layout_renders_properly)|StarStarMimeControllerTest#(?:test_javascript_with_no_format_only_star_star))$/" --verbose --seed 15759

MimeControllerLayoutsTest#test_missing_layout_renders_properly = 0.18 s = .
StarStarMimeControllerTest#test_javascript_with_no_format_only_star_star = 0.00 s = E

Error:
StarStarMimeControllerTest#test_javascript_with_no_format_only_star_star:
ArgumentError: Invalid formats: :iphone
    /Users/yahonda/src/github.com/yahonda/rails/actionview/lib/action_view/lookup_context.rb:287:in `formats='
    /Users/yahonda/src/github.com/yahonda/rails/actionview/lib/action_view/view_paths.rb:11:in `formats='
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/metal/rendering.rb:29:in `process_action'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/abstract_controller/callbacks.rb:42:in `block in process_action'
    /Users/yahonda/src/github.com/yahonda/rails/activesupport/lib/active_support/callbacks.rb:98:in `run_callbacks'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/abstract_controller/callbacks.rb:41:in `process_action'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/metal/rescue.rb:22:in `process_action'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/metal/instrumentation.rb:34:in `block in process_action'
    /Users/yahonda/src/github.com/yahonda/rails/activesupport/lib/active_support/notifications.rb:203:in `block in instrument'
    /Users/yahonda/src/github.com/yahonda/rails/activesupport/lib/active_support/notifications/instrumenter.rb:24:in `instrument'
    /Users/yahonda/src/github.com/yahonda/rails/activesupport/lib/active_support/notifications.rb:203:in `instrument'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/metal/instrumentation.rb:33:in `process_action'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/abstract_controller/base.rb:136:in `process'
    /Users/yahonda/src/github.com/yahonda/rails/actionview/lib/action_view/rendering.rb:39:in `process'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/metal.rb:190:in `dispatch'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/test_case.rb:512:in `process'
    /Users/yahonda/src/github.com/yahonda/rails/actionpack/lib/action_controller/test_case.rb:390:in `get'
    test/controller/mime/accept_format_test.rb:28:in `test_javascript_with_no_format_only_star_star'

rails test test/controller/mime/accept_format_test.rb:26

Finished in 0.180610s, 11.0736 runs/s, 11.0736 assertions/s.
2 runs, 2 assertions, 0 failures, 1 errors, 0 skips
%
```

* How to diagnose this error:

At first Restore `require "action_view/base"` to `actionpack/lib/action_dispatch/middleware/debug_exceptions.rb` addresses this error,
then isolated which lines are required then found this line is required.

22483b86a6/actionpack/lib/action_dispatch.rb (L117)

```ruby
  ActionView::Base.default_formats ||= Mime::SET.symbols
```
2019-12-31 13:47:49 +09:00
Ryuta Kamizono 51908b641f Remove passing a block which is unneeded
I misunderstood the effect of `ruby2_keywords`, the effect is not
local scope, the effect still alive even where you delegate.
2019-12-28 18:20:15 +09:00
Yasuo Honda 1a41a741cf Address `DEPRECATED: use MT_CPU instead of N for parallel test runs`
* Steps to reproduce

```ruby
% cd actionpack
% N=0 bundle exec ruby -w -Itest test/controller/mime/accept_format_test.rb
DEPRECATED: use MT_CPU instead of N for parallel test runs
... snip ...
%
```

* minitest 5.12.0 deprecates ENV["N"] to specify number of parallel test
runners:

https://github.com/seattlerb/minitest/blob/master/History.rdoc#5120--2019-09-22
4103a10eb4

* No other code uses `ENV["N"]`
```
% git grep 'ENV\["N"\]'
actionpack/test/abstract_unit.rb:  PROCESS_COUNT = (ENV["N"] || 4).to_i
%
```

* Rails guide suggests using `PARALLEL_WORKERS` to specify the number of workers, not `N`
https://guides.rubyonrails.org/testing.html#parallel-testing
https://guides.rubyonrails.org/testing.html#parallel-testing

```ruby
PARALLEL_WORKERS=15 rails test
```
2019-12-28 13:01:09 +09:00
Rafael França 4fbb393b25
Merge pull request #35023 from hahmed/deprecate-global-rails-command-docs
Remove reference to global rails command in the docs
2019-12-27 16:39:55 -03:00
Haroon Ahmed db1ae8cbb4 remove reference to global rails command and replace with bin/rails 2019-12-27 19:32:37 +00:00
Rafael Mendonça França f64f0a3471
Fix test with new capybara 2019-12-27 15:30:45 -03:00
Jared Fine 1ead658616 Switch to standardized argument name 2019-12-27 12:35:21 -05:00
Ryuta Kamizono 3eb1f1dd10 Cannot parse `def self.use(...)` in Ruby 2.6 2019-12-26 18:30:11 +09:00
Ryuta Kamizono 04f94394b3 Fix Ruby 2.7 warnings for `ActionController::Metal.use` 2019-12-26 17:59:13 +09:00
Ryuta Kamizono 2e9d4f531c Fix method signature for `ActionController::MiddlewareStack#build_middleware` 2019-12-26 04:14:26 +09:00
Ryuta Kamizono 2253cce3d6 Extract duplicated `&build_block` part into `build_middleware` 2019-12-26 03:33:27 +09:00
Ryuta Kamizono fedde239dc Fix Ruby 2.7 warnings on `MiddlewareStackProxy`
Especially this is caused on `config.app_middleware.insert_after` in our
code base:

2b9edb777b/activerecord/lib/active_record/railtie.rb (L88-L90)
2b9edb777b/activerecord/lib/active_record/migration.rb (L556-L557)
2019-12-25 17:13:09 +09:00
Ryuta Kamizono 9e16af0997 Fix keyward arguments warning in `MiddlewareStack#build`
This is an alternative of 6b633a2823.

`ActionDispatch::Static` middleware requires to be passed `**kwargs`.

0b3c710d35/railties/lib/rails/application/default_middleware_stack.rb (L27)
0b3c710d35/actionpack/lib/action_dispatch/middleware/static.rb (L112-L116)

But `ActionDispatch::Session::CookieStore` middleware requires to be
passed actual `session_options` to `options.merge!(cookie_only: true)`
destructively.

(Ideally passed args should not be mutated, but for now the middleware
intentionally murate the args and testing that.)

0b3c710d35/railties/lib/rails/application/default_middleware_stack.rb (L65)
0b3c710d35/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb (L59-L61)
0b3c710d35/railties/test/application/configuration_test.rb (L1557-L1563)
0b3c710d35/railties/test/application/middleware/session_test.rb (L337-L341)

To address both case, we need to evaluate args for building app in the
`use` method context (that method args in the context have last args
whether kwargs or hash).
2019-12-23 23:37:11 +09:00
Kasper Timm Hansen 6047301063
Merge pull request #38059 from eugeneius/source_extract_encode_template
Encode template source before extracting lines
2019-12-22 08:56:29 +01:00
John Hawthorn 866bedcd29 Fix failing isolated tests due to Array#second
These tests were failing because Array#second from core_ext wasn't
loaded. In one place we now load it, in another we use arr[1] instead.
2019-12-21 03:38:38 -08:00
Eugene Kenny d7b015a167 Encode template source before extracting lines
Before 2169bd3d2a, a template's source was
encoded in place when it was compiled, and the `source_extract` method
could rely on `Template#source` to return a properly encoded string.

Now that `Template#source` always returns a new copy of the template
source with no encoding, `source_extract` should call `encode!` itself.
2019-12-21 07:30:52 +00:00
John Hawthorn 8ceb72f0c4 Revert "Fix keyward arguments warning in `MiddlewareStack#build`"
This reverts commit 6b633a2823.
2019-12-20 16:34:32 -08:00
Ryuta Kamizono 6b633a2823 Fix keyward arguments warning in `MiddlewareStack#build` 2019-12-21 05:17:25 +09:00