Commit Graph

3311 Commits

Author SHA1 Message Date
Nikita Vasilevsky
28eb8b4818 Add assert_redirected_to test with custom message 2022-09-26 15:30:02 +00:00
Jon Dufresne
021113927a Allow specifying the HTTP status code in assert_redirected_to
Previously, the method always asserts the status is `:redirect` which
allows for any kind of 3XX response. However, sometimes it is worthwhile
to precise the status code of the redirect. For example, a Rails
application may want to verify the redirect is a 301 (Moved Permanently)
and not the default 302 (Found). The new method argument makes this
convenient to do in one assertion.
2022-09-19 13:51:14 -04:00
John Bampton
2f699c51ce Fix word case. html -> HTML 2022-09-18 04:21:22 +10:00
Yasuo Honda
349a66ebed Drop Rubinius code
Rubinius has not been maintained since May 2020 and based on the
discussion at https://github.com/rails/rails/pull/44984 ,
I think we can remove Rubinius specific code from Rails.
2022-09-15 23:43:51 +09:00
Rafael Mendonça França
8e65c22e40
Merge pull request #40051 from fsateler/feature/redirect-referer
Add HTTP_REFERER when following redirects on integration tests
2022-09-09 17:03:13 -04:00
Ian Neubert
ca29fca4c8 Add exclude? method to ActionController::Parameters 2022-08-25 13:44:12 -04:00
Jean Boussier
fc0db35fb1 Add OutputBuffer#raw and #capture to reduce the need to swap the buffer
Right now many helpers have to deal with two modes of operation to
capture view output.

The main one is to swap the `@output_buffer` variable with a new buffer.
But since some view implementations such as `builder` keep a reference
on the buffer they were initialized with, this doesn't always work.

So additionally, the various capturing helpers also record the buffer
length prior to executing the block, and then `slice!` the buffer back
to its original size.

This is wasteful and make the code rather unclear.

Now that `OutputBuffer` is a delegator, I'd like to refactor all this
so that:

  - @output_buffer is no longer re-assigned
  - A single OutputBuffer instance is used for the entire response rendering
  - Instead capturing is done through `OutputBuffer#capture`

Once the above is achieved, it should allow us to enabled Erubi's
`:chain_appends` option and get some reduced template size and some
performance.

Not re-assigning `@output_buffer` will also allow template to access
the local variable instead of an instance variable, which is cheaper.

But more importantly, that should make the code easier to understand
and easier to be compatible with `StreamingBuffer`.
2022-08-03 12:56:34 +02:00
Aaron Patterson
07be723bc1 Ensure Rails is green with Rack-Test main branch
This commit just ensures we're green with the main branch of rack test.
The changes are things we should have done anyway, and are backwards
compatible with older versions of rack test
2022-07-06 14:54:01 +02:00
Santiago Bartesaghi
708bb9d314 Fix vulnerability on open redirects 2022-06-28 18:31:58 -03:00
eileencodes
9766eb4a83
Fix tests for minitest 5.16
In minitest/minitest@6e06ac9 minitest changed such that it now accepts
`kwargs` instead of requiring kwargs to be shoved into the args array.
This is a good change but required some updates to our test code to get
the new version of minitest passing.

Changes are as follows:

1) Lock minitest to 5.15 for Ruby 2.7. We don't love this change but
it's pretty difficult to get 2.7 and 3.0 to play nicely together with
the new kwargs changes. Dropping 2.7 support isn't an option right
now for Rails. This is safe because all of the code changes here are
internal methods to Rails like assert_called_with. Applications
shouldn't be consuming them as they are no-doc'd.
2) Update the `assert_called_with` method to take any kwargs but also
the returns kwarg.
3) Update callers of `assert_called_with` to move the kwargs outside the
args array.
4) Update the message from marshaled exceptions. In 5.16 the exception
message is "result not reported" instead of "Wrapped undumpable
exception".

Co-authored-by: Matthew Draper <matthew@trebex.net>
2022-06-23 08:32:11 -04:00
eileencodes
935120fdfd
Fix did you mean tests for ruby-trunk (3.2)
In
f075be3dcb
did_you_mean and error_highlight now use `detailed_message` over
`message` to display errors.

For cases where we are testing `message`, in 3.2 and above we need to
test against `detailed_message` instead.

As far as I can tell in a Rails console when these errors are raised the
`detailed_message` is used so we shouldn't need to make other changes to
Rails. The only case where this isn't true is in the Railties changes -
we are explicitly formatting the did you mean message so we need to be
sure to call `detailed_message` here.

This fixes most of the failing tests for ruby-trunk.
2022-06-10 13:06:42 -04:00
John Hawthorn
c7adce2d8e Fix eql? of AC::Parameters to match hash
Previously, as of 80aaa111884247e6aa17b7bbab268c7719847521,
ActionController::Parameters has defined hash as:

    [@parameters.hash, @permitted].hash

Defining hash means that eql? must be defined, and eql? must be at
least as strict as the hash value generated. That is, for any two
objects which return a different hash value, `a.eql?(b)` should return
false. Otherwise, because hash values have a random seed added, and in
some cases have only some of their bits compared, their behaviour in a
hash becomes undefined. Previously we were breaking this expectation by
allowing a deprecated comparison between Parameters and a plain hash.

This commit fixes eql? to match hash, only returning true when the class
matches as well as the permitted? and parameters values (ie. eql? never
allows the deprecated relaxed equality branch).

This also adds the class to the hash and eql? check, which previously
wasn't there, which isn't strictly necessary to fix this but I think is
a best practice.
2022-06-01 16:21:00 -07:00
John Hawthorn
89caf058e1 Extract AC::Parameters equality tests to own file 2022-06-01 16:13:53 -07:00
Eugene Kenny
1a146bfa7a Don't call controller's headers method internally
Since 5745a3c0928ee5604ce80af19348efb42189f1d6, if a controller defines
a `headers` method it will be called by this line, and the return value
will be mutated. This was also preventing the "Vary" header from being
sent to the client.

Co-authored-by: Oleksandr Bezruchenko <alex.bezruchenko@intercom.io>
Co-authored-by: Iliana Hadzhiatanasova <iliana.hadzhiatanasova@intercom.io>
2022-05-20 08:42:17 -07:00
Alex Ghiculescu
203032dd76 Fix incorrect line number if a helper_method errors
Currently if you use `helper_method` to define a method, and inside that method you get an error, the backtrace is off by one line.

This PR fixes that so that the backtrace now points to the line where you called `helper_method`.
2022-05-17 15:41:28 -05:00
Seva Stefkin
743ab43686
Make behaviour of has_value?/value? more consistent 2022-05-06 15:52:22 +02:00
Seva Stefkin
86980d1a9d
Only allow String and Symbol keys in ActionController::Parameters 2022-04-06 21:24:40 +02:00
Ryuta Kamizono
f6f59be028 Remove deprecated comparing AC::Parameters with a hash assertion
https://buildkite.com/rails/rails/builds/85809#83bae90f-f7ca-4a23-aab9-c9b71d5b823f/1167-1177
2022-04-06 16:18:36 +09:00
Andrew Kowpak
f2c66ce392
Allow CSRF tokens to be stored outside of session 2022-04-04 14:17:44 -04:00
Seva Stefkin
67762c2407
Add a flag to disable deprecated AC::Parameters comparison 2022-04-04 10:08:05 +02:00
Gannon McGibbon
20b77321ef Fix deprecation warning in ActionController::Parameters enumerator test 2022-03-31 18:59:04 -04:00
Gannon McGibbon
aba6008850 Don't delegate ActionController::Parameters#values to hash
Instead, cast any nested hashes into ActionController::Parameters.
2022-03-31 18:59:03 -04:00
Aaron Patterson
8af86c997c
Really deprecate comparing AC::Parameters with a hash
PR #23733 was supposed to deprecate and remove the ability to compare
Hash objects with AC::Parameters objects.  Unfortunately it seems that
we still accidentally support that.

This PR adds a deprecation warning so that we can remove it in the
future.
2022-03-31 13:31:38 -07:00
John Bampton
3b7f55c179 Change yaml to YAML 2022-03-29 15:19:22 +10:00
Bob Farrell
0e1188b563 Receive a block to ActionController::Parameters.to_h
Allow `ActionController::Parameters.to_h` to receive a block to provide
parity with `Hash#to_h`. The provided block recieves `key, value` and
yields a two-element array/keypair which can be transformed in the
resulting Hash.

https://ruby-doc.org/core-2.7.5/Hash.html#method-i-to_h
2022-03-23 20:35:49 +00:00
Hartley McGuire
535113e7e9 fix serializing Parameters as yaml
This has been broken since the logging context was added in
6be9c498bccd8dbc99b4b451841fcf73c7061d48

Also added a higher level test to ensure that this isn't broken again in
the future.
2022-03-22 23:43:46 -04:00
Tom Hughes
24ebaa4e83 Allow relative redirects when raise_on_open_redirects is enabled 2022-03-10 00:41:49 +00:00
Felipe Sateler
c247eaeeba Add HTTP_REFERER when following redirects on integration tests
This makes a closer simulation of what happens in a real browser session
2022-03-06 20:24:46 -03:00
Jean Boussier
9ebfb149ed Better handle basic authentication without a password
https://github.com/rails/rails/pull/43209 immediately rejects
the request if no password is passed, but there are legitimate
uses for accepting authentication without a password.
2022-03-04 14:40:04 +01:00
Brad Trick
880a1bedb9 Allow skip_forgery_protection if no protection set
Calling `skip_forgery_protection` without first calling
`protect_from_forgery`--either manually or through default
settings--raises an `ArgumentError` because `verify_authenticity_token`
has not been defined as a callback.

Since Rails 7.0 adds `skip_forgery_protection` to the
`Rails::WelcomeController` (PR #42864), this behavior means that setting
`default_protect_from_forgery` to false and visiting the Rails Welcome
page (`/`) raises an error.

This behavior also created an issue for `ActionMailbox` that was
previously fixed in the Mailbox controller by running
`skip_forgery_protection` only if `default_protect_from_forgery` was
true (PR #35935).

This PR addresses the underlying issue by setting the `raise` option for
`skip_before_action` to default to false inside
`skip_forgery_protection`.

The fix is implemented in `request_forgery_protection.rb`. The change to
`ActionMailbox`'s `base_controller.rb` removes the now-unnecessary
check of `default_protect_from_forgery`.

The tests added in `request_forgery_protection_test.rb` and
`routing_test.rb` both raise an error when run against the current
codebase and pass with the changes noted above.
2022-02-27 21:58:42 -05:00
Jon Dufresne
c2e756a944 Remove body content from redirect responses
Modern browsers don't render this HTML so it goes unused in practice.
The delivered bytes are therefore a small waste (although very small)
and unnecessary and could be optimized away.

Additionally, the HTML fails validation. Using the W3C v.Nu, we see the
following errors:

    Warning: Consider adding a lang attribute to the html start tag to declare the language of this document.

    Error: Start tag seen without seeing a doctype first. Expected <!DOCTYPE html>.

    Error: Element head is missing a required instance of child element title.

These errors may surface in site-wide compliance tests (either internal
tests or external contractual tests). Avoid the false positives by
removing the HTML.

While these warnings and errors could be resolved, it would be simpler
on future maintenance to remove the body altogether (especially as it
isn't rendered by the browser). As the same string is copied around a
few places, this removes multiple touch points to resolve the current
validation errors as well as new ones.

Many other frameworks and web servers don't include an HTML body on
redirect, so there isn't a reason for Rails to do so. By removing the
custom Rails HTML, there are fewing "fingerprints" that a malicious bot
could use to identify the backend technologies.

Application controllers that wish to add a response body after calling
redirect_to can continue to do so.
2022-02-25 13:31:54 -04:00
Jean Boussier
d32767884d Copy over the IsolatedExecutionState in AC::Live
Fix: https://github.com/rails/rails/issues/44496

It's really unfortunate, but since thread locals were copied
since a decade and we moved most of them into IsolatedExecutionState
we now need to copy it too to keep backward compatibility.

However I think it's one more sign that AC::Live should be
rethought.
2022-02-21 11:40:52 +01:00
John Hawthorn
139ef8a0bc
Merge pull request #44174 from jguecaimburu/add_lowdash_support_to_path_parser_locale_regex
Add support to locales with lowdash in Resolver::PathParser
2022-02-17 08:27:34 -08:00
Petrik
c9cb1aa198 Silence uninitialized instance var warning in tests
Running the Action Pack tests outputs a warning:

    ./actionpack/test/controller/test_case_test.rb:1007: warning: instance variable @counter not initialized

Surrounding the line with silence_warnings cleans up the output.
2022-02-10 16:31:02 +01:00
Jean Boussier
4f12bcd7f1 Remove the deprecated urlsafe_csrf_tokens configuration
Ref: https://github.com/rails/rails/pull/43817

Normally we remove deprecated code much later, but in this case
it's in the way of https://github.com/rails/rails/pull/44283
so I think it would make sense to remove it now.
2022-02-01 10:35:43 +01:00
Juan Guecaimburu
bd0753b396 Add support to locales with lowdash in Resolver::PathParser
In previous versions of Rails, a dynamic regex was built to find templates.
After that, PathParser started to be used to both match and sort templates.
With the dynamic regex, templates with lowdash locales (es_AR) were
found properly. But the PathParser regex does not match locales with this
format, only allowing dash (es-AR) or no dash (es). Templates with lowdash
locales have a wrong virtual path and get filtered.

In this commit the PathParser regex is extended to support the lowdash.
2022-01-14 15:11:58 -03:00
Yutaka Kamei
0b7f37fbed
Initialize ActionController::Parameters with @logging_context
`params` contains `@logging_context` in its instance to notify
unpermitted parameters including the context through Rails
Instrumentation API. However, the logging context disappeared when
`params` is updated with some methods, such as `require`, `slice`,
`merge`, etc, so the subscriber of `unpermitted_parameters` could not
get the information.

This patch tries to initialize `Parameters` with `@logging_context`
where it makes sense to pass the information. The following methods will
be affected with this patch:

* `require`
* `deep_dup`
* `slice`
* `except`
* `extract!`
* `transform_values`
* `transform_keys`
* `deep_transform_keys`
* `select`
* `reject`
* `compact`
* `merge`
* `reverse_merge`
2021-12-16 23:11:49 +09:00
Aaron Patterson
8159996ea0
Dup arrays that get "converted"
We don't want to expose these cache keys to users because users can
mutate the key causing the cache to behave inconsistently.

Fixes: #43681
2021-12-15 14:30:27 -08:00
Rafael Mendonça França
ab754e95d8
Merge pull request #43817 from etiennebarrie/deprecate-non-url-safe-csrf-tokens
Deprecate non-URL-safe CSRF tokens
2021-12-15 01:48:51 +00:00
Alex Ghiculescu
054fa96bac ActionController::TestCase: reset instance variables after each request
`ActionController::TestCase` keeps a `@controller` instance variable, which represents the controller being tested. At the end of each request inside a test, its [params and format](https://github.com/rails/rails/blob/main/actionpack/lib/action_controller/metal/testing.rb) are reset. But any other instance variables set in the test aren't reset. This creates a problem if you do something like this:

```ruby
class UserController
  def show
    @user ||= User.find(params[:id])
    render plain: @user.name
  end
end
```

```ruby

test "gets the user" do
  get :show, params: { id: users(:one).id }
  assert "one", response.body

  get :show, params: { id: users(:two).id }
  assert "two", response.body
end
```

The second assertion will fail, because `@user` won't be re-assigned in the second test (due to `||=`). This example is a bit contrived, but it shows how instance variables persisting between requests can lead to surprising outcomes.

This PR fixes this by clearing all instance variables that were created on the controller while a request was processed.

It explicitly excludes instance variables that were created *before* any requests were run. And it leaves the instance variable around until the *next* request in the test. This means that you can still do this:

```ruby

test "gets the user" do
  @controller.user = users(:one) # assuming `Controller#user` users an ivar internally, you can set the ivar here...

  get :show_current
  assert "one", response.body

  assert_equal users(:one), @controller.user # and you can read the ivar here
end
```
2021-12-09 16:22:54 -06:00
Rafael Mendonça França
7160f46a9e
Merge pull request #43368 from FestaLab/render-hash-syntax
Replaces the hash rocket operator in favor of the newer Ruby syntax on render
2021-12-08 18:13:44 -05:00
Rafael Mendonça França
481343ed91
Merge PR #41769 2021-11-25 19:27:09 +00:00
Rafael Mendonça França
1f4a541421
Remove deprecated support to passing a path to fixture_file_upload relative to fixture_path 2021-11-17 21:51:15 +00:00
Nikita Vasilevsky
2a00c89a7d
Enable Lint/DuplicateMethods rubocop rule 2021-11-15 13:51:28 -05:00
Kasper Timm Hansen
c3758a71af Raise ActionController::Redirecting::UnsafeRedirectError for unsafe redirect_to redirects.
This allows `rescue_from` to be used to add a default fallback route:

```ruby
rescue_from ActionController::Redirecting::UnsafeRedirectError do
  redirect_to root_url
end
```

Co-Authored-By: Chris Oliver <excid3@gmail.com>
2021-11-05 03:23:12 +01:00
danmcge
a2b3e3d523 Add url_from to verify a URL is internal and safe to redirect to
Closes https://github.com/rails/rails/pull/43327

Co-Authored-By: Kasper Timm Hansen <kaspth@gmail.com>
2021-11-05 01:56:37 +01:00
Kasper Timm Hansen
922729eb48 Extract open redirect protection to separate method
Let's us separate what's location generation and what's protection: fewer
arguments, avoids overloading safe, and polluting response_options.

The exception message has been clarified a bit too.
2021-11-04 03:28:02 +01:00
Rafael Mendonça França
20ced4757e
Merge pull request #43444 from sabulikia/support-custom-csrf-strategy
Add support for custom CSRF strategies.
2021-10-14 12:33:52 -04:00
ignacio-chiazzo
4df32bc139 Allow multiline to be passed in routes when using wildcards.
Fixed a bug in action_dispatch where routes with newlines weren't detected when using wildcard segments
2021-10-13 19:14:20 -04:00
Jack McCracken
f40405c138 Add support for custom CSRF strategies. 2021-10-13 14:15:17 -04:00