Commit Graph

15803 Commits

Author SHA1 Message Date
zzak
f6f52c363b Add Passenger docs for ActionController::Streaming
Originally added in #20811

Co-authored-by: Aditya Kapoor <adityakapoor.mait@gmail.com>
2023-01-28 18:28:57 +09:00
Sean Doyle
ad79ed0e6b ActionDispatch::Testing::TestResponse#parsed_body parse HTML with Nokogiri
Prior to this commit, the only out-of-the-box parsing that
`ActionDispatch::Testing::TestResponse#parsed_body` supported was for
`application/json` requests. This meant that `response.body ==
response.parsed_body` for HTML requests.

```ruby
get "/posts"
response.content_type         # => "text/html; charset=utf-8"
response.parsed_body.class    # => Nokogiri::HTML5::Document
response.parsed_body.to_html  # => "<!DOCTYPE html>\n<html>\n..."
```

Using `parsed_body` for JSON requests supports `Hash#fetch`, `Hash#dig`,
and Ruby 3.2 destructuring assignment and pattern matching.

The introduction of [Nokogiri support for pattern
matching][nokogiri-pattern-matching] poses an opportunity to make assertions
about the structure of the HTML response.

On top of that, there is ongoing work to [introduce pattern matching
support in MiniTest][minitest-pattern-matching].

[nokogiri-pattern-matching]: https://github.com/sparklemotion/nokogiri/pull/2523
[minitest-pattern-matching]: https://github.com/minitest/minitest/pull/936
2023-01-27 23:52:21 -05:00
Michael Hadley
c22e20e79c Fix typo in assume_ssl configuration guide 2023-01-27 19:09:38 -08:00
Steven Harman
af1019cecd
Fix typo: missing end brackets 2023-01-27 12:53:57 -05:00
Samuel Williams
a3caa2b551
Normalize usage of "Headers". 2023-01-26 12:06:24 +13:00
Rafael Mendonça França
2cf8740e15
Merge pull request #47091 from ioquatix/rack-3-case-insensitive-headers
Use Rack's own headers classes where appropriate.
2023-01-25 17:22:47 -05:00
Joel Hawksley
2fc46f95a5
Tag HTTP::Request with route URI pattern (#47129)
In the GitHub RoR monolith, we output the route URI pattern
in an HTML meta tag in our application layout for analysis
purposes. However, our current implementation is quite manual.

This change adds an attribute to requests with the URI pattern
of the matched route.

Co-authored-by: Rafael Mendonça França <rafael@rubyonrails.org>
Co-authored-by: Kate Higa <khiga8@github.com>
2023-01-25 16:43:12 -05:00
Rafael Mendonça França
e572f23150
Merge pull request #47094 from zzak/rack-3-files-continued
Replace deprecated Rack::File with Rack::Files
2023-01-25 16:41:12 -05:00
David Heinemeier Hansson
8b8ac378a9 Trailing whitespace 2023-01-25 21:27:16 +01:00
Rafael Mendonça França
1b44989521
Merge PR #46594 2023-01-25 20:13:18 +00:00
David Heinemeier Hansson
1da6f8c68e
Allow use of SSL-terminating reserve proxy that doesn't set headers (#47139)
* Allow use of SSL-terminating reserve proxy that doesn't set headers

NGINX and other SSL-terminating reverse proxies can use HTTP headers to include forwarding information. If your stack includes SSL-termination through a network load balancer, that won't happen. You can use config.assume_ssl to address that.

* I hate these warts

* Document the new setting

* Add autoload for AssumeSSL

* Add CHANGELOG notice
2023-01-25 21:02:02 +01:00
Rafael Mendonça França
859b526c5b
Remove upper bound of rack
Allow users to install any version and try to see if Rails is compatible.
2023-01-25 15:25:49 +00:00
zzak
896c7faedf Use Gemfile to manage Rack version for dev 2023-01-25 12:24:19 +09:00
John Hawthorn
f6e36c90aa
Merge pull request #47087 from jhawthorn/cookie_domain
Fix cookie domain for `domain: all` on two letter single level TLD
2023-01-24 13:56:38 -08:00
John Hawthorn
941e0cd212 Fix cookie domain calculation for two letter tld 2023-01-23 16:37:16 -08:00
Ron Shinall
189e4108c5 Address Selenium :capabilities deprecation warning 2023-01-23 21:40:01 +00:00
zzak
12de399ef9 Replace deprecated Rack::File with Rack::Files
Follow up to #47075
2023-01-21 09:34:21 +09:00
Samuel Williams
89df368e4d
Update ActionDispatch::Response to support streaming bodies.
Rack 3 introduces streaming bodies, which don't respond to `#each` and
MUST respond to `#call`. Ensure that the methods are correctly delegated.

`#to_ary` must also work correctly for enumerable bodies, and is used by
middleware like `Rack::ETag` to buffer enumerable bodies correctly.
2023-01-21 13:12:24 +13:00
Samuel Williams
0b4b4c6b96
Use Rack's own headers classes where appropriate.
Rack 3 response headers must be a mutable hash with lower-case keys. Rack
provides `Rack::Headers` as a compatibility layer for existing systems
which don't conform to this requirement. Prefer `Rack::Utils::HeaderHash`
on Rack 2, and `Rack::Headers` on Rack 3.


Remove some of the response test cases which test `nil` header keys as
these are considered invalid, and will fail with `Rack::Headers`.
2023-01-21 12:55:06 +13:00
Rafael Mendonça França
72642bd74b
Merge pull request #47081 from ioquatix/rack-3-query-parser-utf8
Don't assume that invalid UTF-8 will raise an error.
2023-01-20 15:20:42 -05:00
Rafael Mendonça França
3adec8df0a
Merge pull request #47083 from ioquatix/rack-3-ssl_test-headers
Don't assume the existance of `Rack::Utils::HeaderHash`.
2023-01-20 15:14:19 -05:00
Rafael Mendonça França
4c7c69d1fe
Merge pull request #47082 from ioquatix/rack-3-env-fields
Don't assume these fields will be present in a rack env.
2023-01-20 15:03:52 -05:00
Rafael Mendonça França
8c11ae0440
Avoid redefining the response=.
In `6d5e0d2de2a8836e858962981c34aff2f76ffe3d` we added a `response=` method
that was redefining the already existed method generated by `attr_internal`.
2023-01-20 19:31:37 +00:00
Rafael Mendonça França
006d68eb8c
Merge pull request #47079 from ioquatix/actiondispatch-request-inspect
Fix `#inspect` failures when dealing with requests with `method=nil`.
2023-01-20 14:16:36 -05:00
Rafael Mendonça França
f43a088b78
Merge pull request #47077 from ioquatix/rack-3-rewindability
Don't assume Rack input supports rewindability.
2023-01-20 14:10:54 -05:00
Rafael Mendonça França
0e615275a6
Merge pull request #47085 from ioquatix/rack-3-compatible-cookies
Don't assume the existance of `add_cookie_to_header` and related methods.
2023-01-20 14:09:12 -05:00
Aaron Patterson
db2463f277
Merge pull request #47075 from ioquatix/rack-3-files
Rack deprecated `Rack::File` and replaced it with `Rack::Files`.
2023-01-20 09:49:41 -08:00
Samuel Williams
4c58755862
Add rack-session and rackup gems.
Rack 2 includes this code, but in Rack 3 it was extracted into gems. These
gems include a v1 release compatible with Rack 2, and a v2 release
compatible with Rack v3+.
2023-01-21 06:03:41 +13:00
Samuel Williams
706fb10ad5
Don't assume the existance of add_cookie_to_header and related methods.
Rack 3 deprecates some of these clunky methods, and the only compatible
methods between Rack 2 and Rack 3 is to use `Rack::Response` which
includes `set_cookie` and `delete_cookie`.
2023-01-21 05:59:22 +13:00
Samuel Williams
fc0ec10272
Don't assume the existance of Rack::Utils::HeaderHash.
In Rack 3, this was deprecated and replaced with `Rack::Headers`. Using a
hash instance here appars to be sufficient.
2023-01-21 05:56:15 +13:00
Samuel Williams
7981dce06c
Don't assume these fields will be present in a rack env.
Rack 3 drops several of these fields as mandatory.
2023-01-21 05:53:20 +13:00
Samuel Williams
fd48e72518
Don't assume that invalid UTF-8 will raise an error.
Rack 3 parses the query part of a URL as ASCII-8BIT and does not fail on
invalid UTF-8 code sequences. Limit the tests to Rack 2.
2023-01-21 05:51:29 +13:00
Samuel Williams
cc3f50702f
Fix #inspect failures when dealing with requests with method=nil.
When I was debugging `ActionDispatch::Request` instances in some tests, I
noticed IRB complaining that the object did not support `#inspect`, as
it was trying to print out the `method` which calls `check_method(nil)`
which fails. Don't try to validate `nil` method as it will always fail
and appears to be a valid state (when constructing an empty request as in
some tests).
2023-01-21 05:44:43 +13:00
Samuel Williams
911556fd81
Don't assume Rack input supports rewindability.
Rack 3 drops the requirement for a Rack input body to be rewindable. Limit
the related tests to run only on Rack < 3.
2023-01-21 05:38:54 +13:00
Samuel Williams
d4bf3ff6d1
Rack deprecated Rack::File and replaced it with Rack::Files. 2023-01-21 05:31:41 +13:00
Samuel Williams
08510b5437
Improve matching of headers assertions.
The current implementation makes assumptions about the case and format of
headers. Introduce methods to handle headers in a case insensitive manner
and reduce churn when comparing with multi-value headers.
2023-01-21 05:26:22 +13:00
Samuel Williams
f63a5e7d16
Improve matching of cookie assertions.
The current implementation makes assumptions about the order and case
sensitivity of cookie attributes. Introduce methods to parse those fields
and compare them semantically. Update the existing tests to take advantage
of these new assertions.
2023-01-20 14:53:18 +13:00
Rafael Mendonça França
7c38258f70
Merge pull request #46327 from elliotcm/elliotcm/fix-stream-content-type
Fix content-type header with `send_stream`
2023-01-18 15:32:48 -05:00
Jean Boussier
66227e01e7 Improve Rails' Shape friendliness (third pass)
Followup: https://github.com/rails/rails/pull/47023

```
Shape Edges Report
-----------------------------------
snip...
       130  @_config
snip...
        99  @_url_options
```
2023-01-18 15:44:08 +01:00
Rafael Mendonça França
9ecc8785ef
Fix rubocop violations 2023-01-17 19:51:40 +00:00
John Hawthorn
13016ce16e Avoid regex backtracking on If-None-Match header
[CVE-2023-22795]
2023-01-17 11:38:11 -08:00
sabulikia
fbc24520a3 Use string#split instead of regex for domain parts
[CVE-2023-22792]
2023-01-17 11:38:11 -08:00
wonda-tea-coffee
f6cdce50d4 Fix sec issue with _url_host_allowed?
Disallow certain strings from `_url_host_allowed?` to avoid a redirect
to malicious sites.

[CVE-2023-22797]
2023-01-17 11:38:11 -08:00
Petrik de Heus
c975051746
Merge pull request #47029 from hahmed/ha/fix-routing-wording-in-doc [ci-skip]
Update docs in actionpack to use bin/rails
2023-01-17 16:34:50 +01:00
Jean Boussier
aa7d78d9b1 Improve Rails' Shape friendliness (second pass)
Followup: https://github.com/rails/rails/pull/47023

```
Shape Edges Report
-----------------------------------
snip...
       238  @errors
snip...
       219  @options
snip...
       129  @_request
       128  @type
       125  @virtual_path
       124  @_assigns
       123  @_config
       123  @_controller
       123  @output_buffer
       123  @view_flow
       122  @_default_form_builder
snip...
        89  @_already_called
        75  @validation_context
snip...
        65  @_new_record_before_last_commit
snip...
        58  @_url_options
snip...
```
2023-01-17 13:55:49 +01:00
Haroon Ahmed
2303628189 Update doc to use bin/rails which is the correct convention for invoking rails commands 2023-01-17 09:42:38 +00:00
Rafael Mendonça França
03a1da9c34
Merge pull request #46915 from joshuay03/update-action-pack-render-template-tests
Update `ActionPack` render template with locals tests
2023-01-16 18:40:27 -05:00
Jean Boussier
fc950324bd Improve Rails' Shape friendliness
Ruby 3.2 significantly changed how instance variables are store.
It now use shapes, and in short, it's important for performance
to define instance variables in a consistent order to limit the
amount of shapes.

Otherwise, the number of shapes will increase past a point where
MRI won't be able to cache instance variable access. The impact
is even more important when YJIT is enabled.

This PR is data driven. I dump the list of Shapes from Shopify's
monolith production environment, and Rails is very present among
the top offenders:

```
Shape Edges Report
-----------------------------------
       770  @default_graphql_name
       697  @own_fields
       661  @to_non_null_type
       555  @own_interface_type_memberships
       472  @description
       389  @errors
       348  @oseid
       316  @_view_runtime
       310  @_db_runtime
       292  @visibility
       286  @shop
       271  @attribute_method_patterns_cache
       264  @namespace_for_serializer
       254  @locking_column
       254  @primary_key
       253  @validation_context
       244  @quoted_primary_key
       238  @access_controls
       234  @_trigger_destroy_callback
       226  @_trigger_update_callback
       224  @finder_needs_type_condition
       215  @_committed_already_called
       214  @api_type
       203  @mutations_before_last_save
       202  @access_controls_overrides
       201  @options
       198  @mutations_from_database
       190  @_already_called
       183  @name
       179  @_request
       176  @own_arguments
       175  @_assigns
       175  @virtual_path
       174  @context
       173  @_controller
       173  @output_buffer
       173  @view_flow
       172  @_default_form_builder
       169  @cache
       159  @_touch_record
       151  @attribute_names
       151  @default_attributes
       150  @columns_hash
       149  @attribute_types
       148  @columns
       147  @marked_for_same_origin_verification
       146  @schema_loaded
       143  @_config
       143  @type
       141  @column_names
```

All the changes are of similar nature, the goal is to preset the instance
variable to nil when objects are allocated, or when classes are created.

For classes I leverage the `inherited` hook. If the patern becomes common enough
it might make sense to add a helper for this in `ActiveSupport::Concern`.
2023-01-16 12:31:37 +01:00
eileencodes
d9dd1c59d0
Implement spot and don't use keep_script_lines in Ruby 3.2
We want to use error highlight with eval'd code, specifically ERB
templates.

Previously we could only get the information we needed by setting
`keep_script_lines` to true. In Ruby 3.2 and error_highlight we added
the ability to get this information without setting `keep_script_lines`.

This change implements that new behavior for Rails.

I removed the script line changes to support this in 3.1 because it is
not in any released version.

Ruby change: https://github.com/ruby/ruby/pull/6593
Erorr highlight change: https://github.com/ruby/error_highlight/pull/26

Co-authored-by: Aaron Patterson <tenderlove@ruby-lang.org>
2023-01-13 16:20:09 -05:00
Lachlan Sylvester
0a77b32042 discard marshal dumped values when reading a signed cookie 2023-01-13 10:47:01 +11:00
Fabian Mersch
e768fc8ab8 Scope generated route helpers to an instance of RoutesProxy 2023-01-12 15:03:57 +01:00
Roman Sokhan
b7d7376df1 Fix rare conflict of default_render with Minitest::Mock 2023-01-11 18:24:15 +02:00
Samuel Williams
28c8e2229f
Be more explicit when wrapping in an enumerable body. 2023-01-09 13:26:53 +13:00
Samuel Williams
36e2cb9abb
Test body proc detection. 2023-01-09 13:26:53 +13:00
Samuel Williams
5af76309ef
Close previous response if any. 2023-01-09 13:26:53 +13:00
Samuel Williams
dc9c0859c0
Allow assigning streaming response body. 2023-01-09 13:26:53 +13:00
Samuel Williams
8e8695ea57
Fix comment. 2023-01-09 13:26:53 +13:00
Samuel Williams
6d5e0d2de2
Limit changes to new interface, response=. 2023-01-09 13:26:53 +13:00
Samuel Williams
d8256ff62f
Fix test name. 2023-01-09 13:26:53 +13:00
Samuel Williams
c239d6d79c
Spaces inside brackets. 2023-01-09 13:26:53 +13:00
Samuel Williams
ec3830d54a
Add some tests. 2023-01-09 13:26:52 +13:00
Samuel Williams
49053fe8c0
Direct support for assigning to self.response. 2023-01-09 13:26:52 +13:00
Jonathan Hefner
aaf7bed003 Document ActionController::Rendering#render [ci-skip]
In #33418, documentation from `ActionView::Helpers::RenderingHelper#render`
was copied to `ActionController::Renderer#render` with the intention of
documenting `ActionController::Rendering#render`.  Since then, further
documentation has been added to `ActionController::Renderer#render`, and
`ActionController::Renderer#render` has been mistaken for
`ActionController::Rendering#render` (for example, in #46045).

This commit adds documentation to `ActionController::Rendering#render`
(which was previously `:nodoc:` because it is a simple override of
`AbstractController::Rendering#render`), and updates related
documentation to point to `ActionController::Rendering#render`.
2023-01-08 15:47:31 -06:00
Jonathan Hefner
6969cdc969 Revise ConditionalGet#expires_in doc [ci-skip] 2023-01-08 15:47:31 -06:00
Jonathan Hefner
2cb419f220 Clean up ConditionalGet#stale? doc [ci-skip] 2023-01-08 15:47:31 -06:00
Jonathan Hefner
657f214f25 Clean up ConditionalGet#fresh_when doc [ci-skip] 2023-01-08 15:47:31 -06:00
Jonathan Hefner
9a82d9585c Replace RFC 2616 links [ci-skip]
The w3.org RFC 2616 page displays an obtrusive "This document has been
superseded" overlay.  In regard to the `Cache-Control` header, RFC 2616
has been superseded by RFC 7234, which, in turn, has been superseded by
RFC 9111.

Therefore, this commit replaces links to RFC 2616 with links to either
MDN or RFC 9111.
2023-01-08 15:47:31 -06:00
Jonathan Hefner
ce23110829 Coordinate FilterParameters and ParameterFilter docs [ci-skip]
This clarifies the `ActiveSupport::ParameterFilter` documentation, and
tweaks the example code to be more friendly to the syntax highlighter
(similar to the tweaks made for `ActionDispatch::Http::FilterParameters`
in 782bed5d450363b302e0e6aa28b7ea0aef306d9f).

This also trims the `ActionDispatch::Http::FilterParameters`
documentation, and links it to `ActiveSupport::ParameterFilter`, since
`ActiveSupport::ParameterFilter` is responsible for filter behavior.
2023-01-08 15:47:20 -06:00
Jonathan Hefner
1aba8f64bf Document AD::Request::RFC* constants individually [ci-skip]
Prior to this commit, the list of RFCs and URLs was jumbled in a single
paragraph (with no delimiters) that was associated with the `RFC2616`
constant.

This commit splits up the list, associating each RFC with its respective
constant, and incorporating each URL into a link.
2023-01-08 15:47:20 -06:00
Jonathan Hefner
cfe300ceb1 Format inline code [ci-skip] 2023-01-08 15:47:20 -06:00
Jonathan Hefner
3eadf057db Fix typos in API docs [ci-skip] 2023-01-08 15:47:20 -06:00
Jonathan Hefner
33557c5dca Indent private methods in code examples [ci-skip]
This matches the indentation used in generated code, such as code from
`railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb.tt`.
2023-01-08 15:47:20 -06:00
Jean Boussier
481c169aa5
Merge pull request #46910 from skipkayhil/more-string-include
Fix Performance/StringInclude that RuboCop can't
2023-01-07 14:32:49 +01:00
Joshua Young
7e351255c0 [Closes #46724] Update ActionPack render template with locals tests 2023-01-07 12:04:37 +10:00
Akira Matsuda
e0936d99a3
Revert "One less String allocation for event.allocations"
This reverts commit ae569eaef86fb5f74e1d6150cb6945ec700d26a9.

Seems like this broke Action View CI
2023-01-07 06:00:21 +09:00
Hartley McGuire
583ce94c22
Fix Performance/StringInclude that RuboCop can't
This replaces two instances of /html/.match?(<string>) with the more
performant <string>.include?("html").

Performance/StringInclude was enabled in 3158bbb, however RuboCop does
not flag these two because it is unable to determine that the variable
passed to #match? is a string. In both these cases we know that the
variable must be a string (Mime::Type must be initialized with a string,
and Content-Type must be a string if present per Rack SPEC)

These were found by `rg '/\[\w ]+/\.match\?'`, and while this search
returns other entries they are either comments or in test files.
2023-01-06 15:52:32 -05:00
Akira Matsuda
ae569eaef8
One less String allocation for event.allocations 2023-01-07 04:54:32 +09:00
Jean Boussier
dcb4f4d557
Merge pull request #46862 from skipkayhil/lint-ad-integration
Fix IntegrationTest not following Rack SPEC
2023-01-06 16:36:32 +01:00
Hartley McGuire
eef4e755e0
Changelog for 0019dea
As this is a user facing change, it should have a changelog entry
2023-01-05 17:43:15 -05:00
Junichi Sato
6f1f2d74e6
Tweak doc to show helper methods need not be public [ci-skip] 2023-01-05 16:19:36 +09:00
Akira Matsuda
bfb0a6c211
require active_support/test_case instead of minitest
because this file references AS::TestCase which already loads minitest.
2023-01-05 02:15:10 +09:00
eileencodes
04e1a0d2e1
Add documentation for #43487
In #43487 we missed adding a changelog so that's been added here. In
addition, since this isn't a new framework default unless you are
creating a new application (and only in dev and test environments by
default) it can be easy to miss this new option. I've updated the
message to mention the option following DHH's suggestion on the original
PR.
2023-01-03 13:40:28 -05:00
Ghouse Mohamed
e0559d2c1c Change 2022 -> 2023 2023-01-03 13:22:00 +05:30
Hartley McGuire
060887d4c5
Fix IntegrationTest not following Rack SPEC
Previously, ActionDispatch::IntegrationTest would always set
CONTENT_TYPE on the request whether or not the value being set was a
string or nil. However, Rack SPEC requires that if CONTENT_TYPE is set,
it must be a string.

Since the request_encoder can return nil for #content_type (and the
IdentityEncoder always will), IntegrationTest must check before it sets
the CONTENT_TYPE value.

A Rack::Lint test has been added to prevent regressions. Additionally,
it will make changes needed for Rack 3 more obvious when the time comes.
2022-12-30 16:19:25 -05:00
Matthew Draper
0f0ec9908e
Merge pull request #46792 from codeminator/fix-flaky-tests
Increase `socket_timeout` for Memcached inside memcached tests
2022-12-27 17:45:33 +10:30
Yasuo Honda
15576ddedb
Merge pull request #46800 from the-spectator/prefer_local_env
Prefer using new Rails.env.local?
2022-12-24 08:40:42 +09:00
Akira Matsuda
a790203408
Use Kernel#Array to avoid an extra Array allocation when nil was given 2022-12-23 23:34:34 +09:00
Akshay Birajdar
c312bb7e04 Prefer using new shorthand helper Rails.env.local? 2022-12-23 19:04:33 +05:30
RobL
83da2e9383 Allow proc for per-request cookie domain
Per-request cookie domain set through proc
2022-12-22 19:49:22 +00:00
Ahmed Shahin
c2f6be12a5 increase for more tests 2022-12-22 15:04:05 +02:00
Akira Matsuda
15ab7223c7
Avoid creating an extra Hash object when no options were given 2022-12-22 18:26:27 +09:00
Akira Matsuda
055f71cece
Reduce a String object allocation 2022-12-22 17:31:12 +09:00
Akira Matsuda
41c2c26dc6
Reuse the Array object passed from parent middleware
This patch reduces Array object allocations from some Rack middleware per each
request by reusing the Array object that wraps status, headers, and body
objects. This is a Rails version of the same improvements that has already been
pushed to Rack 3.0. https://github.com/rack/rack/pull/1887
2022-12-19 23:04:04 +09:00
Akira Matsuda
8b617e224b
Reduce Array allocations in MimeNegotiation 2022-12-18 12:11:34 +09:00
Akira Matsuda
01001028df
Revert "Reduce more Array object creations"
This reverts commit cac0e0431375073f4bebc5df8598bf79e863c086.

Reason: web-console gem expects the existence of `filter_proxy` and overrides this method
https://github.com/rails/web-console/blob/v4.2.0/lib/web_console/request.rb#L31-L36
2022-12-17 19:00:57 +09:00
Akira Matsuda
4fbc4bbe43
Revert "👮"
This reverts commit 59728911e445da8183f5083b3ad9fb1b60bfdf00.
2022-12-17 18:57:10 +09:00
Akira Matsuda
56333f3c69
Avoid returning "" which is not a valid MIME type 2022-12-17 16:35:25 +09:00
Akira Matsuda
26f51f36fa
No need to reset_body where setting the body soon afterwards 2022-12-17 15:52:18 +09:00
Akira Matsuda
bc3251f1be
Reduce formats call which creates extra Array objects per each call 2022-12-17 15:52:18 +09:00
Akira Matsuda
78599ba1e8
'string'[0, index] is faster and more eco-friendly than 'string'.split.first 2022-12-17 15:48:00 +09:00
Jonathan Hefner
40b1c60872
Merge pull request #46752 from swanson/forgery-docs-update
Update RequestForgeryProtection docs to encourage wrapper method for skipping [ci-skip]
2022-12-16 11:21:48 -06:00
matt swanson
a7bbbc1589 Update docs to encourage use of wrapper method
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
2022-12-16 12:10:57 -05:00
Akira Matsuda
59728911e4
👮 2022-12-16 22:20:58 +09:00
Akira Matsuda
b368c68c6a
Reduce Array object allocation 2022-12-16 20:22:07 +09:00
Akira Matsuda
4e7620b110
Unused default value that creates an Array object per each invocation 2022-12-16 20:21:22 +09:00
Akira Matsuda
9a8d2de95b
Avoid duplicating HWIA and reduce object allocations 2022-12-16 20:20:03 +09:00
Akira Matsuda
351e726be5
Reduce Hash allocations 2022-12-16 20:20:03 +09:00
Akira Matsuda
cac0e04313
Reduce more Array object creations 2022-12-16 20:20:03 +09:00
Akira Matsuda
b9fe288d6d
Reduce Array object allocations 2022-12-16 20:20:03 +09:00
Jonathan Hefner
93038baad7 Use routes.default_url_options in AC::Renderer env
When a host is not specified for an `ActionController::Renderer`'s env,
the host and related options will now be derived from the routes'
`default_url_options` and `ActionDispatch::Http::URL.secure_protocol`.

For example, with:

  ```ruby
  Rails.application.default_url_options = { host: "rubyonrails.org" }
  Rails.application.config.force_ssl = true
  ```

Before:

  ```ruby
  ApplicationController.renderer.render inline: "<%= blog_url %>"
  # => "http://example.org/blog"
  ```

After:

  ```ruby
  ApplicationController.renderer.render inline: "<%= blog_url %>"
  # => "https://rubyonrails.org/blog"
  ```

As a consequence, Action Text attachment URLs rendered in a background
job (a la Turbo Streams) will now use `Rails.application.default_url_options`.

Fixes #41795.
Fixes hotwired/turbo-rails#54.
Fixes hotwired/turbo-rails#155.
2022-12-15 16:22:07 -06:00
Akira Matsuda
c0f16c16a3
Defer creation of Request object until the object is in need 2022-12-15 11:55:03 +09:00
Akira Matsuda
41b3e61735
Defer creating Request object until the object is in need in the exceptional case 2022-12-15 11:55:03 +09:00
Alex Ghiculescu
090d1acfe4 Query Logs: namespaced_controller tag should match controller format
Currently if you do this:

```ruby
config.active_record.query_log_tags = [:namespaced_controller]
```

A request that's processed by the `NameSpaced::UsersController` will log as `namespaced_controller='NameSpaced%3A%3AUsersController'`.

By contrast if you set the tag to `:controller` it would log as `controller='user'`, much nicer.

This PR makes the `:namespaced_controller` formatting more similar to `:controller` - it will now log as `namespaced_controller='name_spaced/users'`.
2022-12-12 10:31:00 -06:00
Jean Boussier
51e9fa9bf9
Merge pull request #46614 from Cofense/action_dispatch-response-buffer-write-alias
Add `#<<` alias for `#write` to ActionDispatch::Response::Buffer
2022-12-08 11:18:09 +01:00
Alex Ghiculescu
03394484a6 Fix more double logging in ActiveRecord::QueryLogs
ref: https://github.com/rails/rails/pull/46279

That PR missed the case where if you set `config.active_record.query_log_tags = [:namespaced_controller]`, it would log the controller twice:

```
/*namespaced_controller:Foo::BarController,controller:bar*
```

So this PR just fixes that bug, and tweaks the changelog entry rather than adding another one for the same bug.
2022-12-04 20:57:34 -06:00
Jonathan Hefner
3658dc8af8 Preallocate default Rack env for AC::Renderer
This preallocates a `DEFAULT_ENV` Rack env for `Renderer` instances to
use, and avoids `dup`ing the `DEFAULTS` Hash unless the user intends to
modify it.  This reduces retained allocations per controller class.

**Benchmark**

  ```ruby
  # frozen_string_literal: true
  require "benchmark/memory"

  $controllers = []

  Benchmark.memory do |x|
    Class.new(ActionController::Base) # warmup

    x.report("1 controller") do
      $controllers << Class.new(ActionController::Base)
    end

    x.report("100 controllers") do
      100.times { $controllers << Class.new(ActionController::Base) }
    end
  end
  ```

**Before**

  ```
  Calculating -------------------------------------
          1 controller    16.070k memsize (     9.683k retained)
                         133.000  objects (    40.000  retained)
                          50.000  strings (    14.000  retained)
       100 controllers     1.607M memsize (   875.044k retained)
                          13.300k objects (     3.308k retained)
                          50.000  strings (    50.000  retained)
  ```

**After**

  ```
  Calculating -------------------------------------
          1 controller    15.654k memsize (     9.347k retained)
                         129.000  objects (    38.000  retained)
                          49.000  strings (    14.000  retained)
       100 controllers     1.565M memsize (   841.284k retained)
                          12.900k objects (     3.108k retained)
                          50.000  strings (    50.000  retained)
  ```

This does add a `dup` to `render` because `request.routes = ...` mutates
the underlying env, which can now be `DEFAULT_ENV`.  But a temporary
allocation there (likely outside of a request cycle) seems like a
reasonable trade for avoiding two retained allocations per controller
class.
2022-11-30 16:48:06 -06:00
Eddie Lebow
3eb8493024
Add #<< alias for #write to ActionDispatch::Response::Buffer
This makes the stream object a closer analog of an `IO`.

on-behalf-of: @Cofense <oss@cofense.com>
2022-11-29 18:00:23 -05:00
Étienne Barrié
3d6a7b2faa Initialize deprecators before configuring them
Since engine initializers run later in the process, we need to run this
initializer earlier than the default.

This ensures they're all registered before the environments are loaded.
2022-11-28 10:47:26 +01:00
Jonathan Hefner
a2174bd260 Revise ActionController::Renderer API docs [ci-skip]
This fixes a few inaccuracies that have been present since
2db7304c2c338711b265e92a51d29121cbd702e6.  For example,
`Controller.renderer` no longer returns a class, `Renderer#env` is not
defined, and changing the value of `Renderer#defaults` has no direct
effect.  This also documents the user-friendly Rack env key variants.
2022-11-27 15:05:33 -06:00
Andy Waite
0ec8f21bb6
Add details of cookie name and size to CookieOverflow exception
My app was raising a `CookieOverflow` exception but it was difficult to pinpoint the cause, since error trackers and logging system generally filter out cookies.

This Pull Request has been created because I want the exception to provide additional information:
- The name of the cookie that overflowed
- The magnitude of how much it overflowed by

I am assuming that only the cookie value is sensitive, and not its name or size.
2022-11-24 17:18:02 -05:00
Jonathan Hefner
7bcca5b763 Use memoized dup of url_helpers for reinclusion
In the case where a controller subclasses an engine's controller that,
in turn, subclasses a controller that includes the application's
`url_helpers` (for example, in the "isolated engine routes and helpers
are isolated to that engine" test in `railties/test/railties/engine_test.rb`),
this commit avoids allocating a new module per controller:

  ```ruby
  ActionController::Base.include Rails.application.routes.url_helpers
  C1 = Class.new(ActiveStorage::DirectUploadsController)
  C2 = Class.new(ActiveStorage::DirectUploadsController)

  C1.ancestors - C2.ancestors
  # BEFORE:
  # => [C1, #<Module:0x...>]
  # AFTER:
  # => [C1]
  ```

This commit also modifies the `RouteHelperIntegrationTest` test to use
the controllers defined in `actionpack/test/abstract_unit.rb`.
Otherwise, `extend AbstractController::Railties::RoutesHelpers.with(...)`
happens twice -- once for `ActionController::Base` and once for
`FakeACBase` -- which causes `FooController` to include an extra module
as it flip-flops its `_routes` definition.  Previously, the extra module
only defined a `_routes` method; now, the extra module would be the
memoized dup of `routes.url_helpers`, which would cause the "only
includes one module with route helpers" test to falsely fail.
2022-11-19 10:57:21 -06:00
Jonathan Hefner
d69501a3d6 Update ActionController::UrlFor request contract [ci-skip]
Using a `request` object that only "responds to the `host`,
`optional_port`, `protocol`, and `symbolized_path_parameter` methods"
has not been possible for a long time.  For example,
`symbolized_path_parameter` was renamed to `path_parameters` (without
deprecation) in 925bd975663df2e0e8613507a7c95a6945a277ac.  And
`request.routes` and `request.original_script_name` methods became
required in 87a75910640b83a677099198ccb3317d9850c204.  And a
`request.engine_script_name` method became required in
4080dd2f244e7c4d140f8724c2075102ea9db36e.

Therefore, this commit updates the documentation to simply require
an `ActionDispatch::Request` instance.
2022-11-15 13:57:15 -06:00
Jonathan Hefner
782bed5d45 Tweak AD::Http::FilterParameters code example [ci-skip]
Prior to this commit, the format of the code example confused the syntax
highlighter.  This commit formats each explanation as a code comment,
and tweaks their wording for clarity.
2022-11-15 13:57:15 -06:00
Jonathan Hefner
8b216e89cf Replace ActionController::UrlFor references [ci-skip]
These references were missed when `ActionController::UrlFor` was
converted to `ActionDispatch::Routing::UrlFor` in
226dfc2681c98deaf14e4ae82e973d1d5caedd68.
2022-11-15 13:57:15 -06:00
Jonathan Hefner
ee8d9497dd Auto-link code references [ci-skip] 2022-11-15 13:57:15 -06:00
Jonathan Hefner
9588f780dc Format inline code [ci-skip] 2022-11-15 13:57:15 -06:00
Jonathan Hefner
cb34c92a2b Fix typos [ci-skip] 2022-11-15 13:57:15 -06:00
takayamaki / fusagiko
ee389f56ef refactor ParameterEncodingTest and add test for param_encoding
- rename testcases
- reduce redundant parameters
- rename tested action methods
- move skip_parameter_encoding near by definiton of action
- add test for param_encoding
2022-11-14 17:58:18 +00:00
Niklas Haeusele
ba16325c96 Improve the MissingExactTemplate errorpage
Passthrough the controller and action name to the error page.
2022-11-10 22:39:09 +01:00
sampatbadhe
61ceeacf0c Correct missing template error page
- Correct controller path "app/controller/books_controller.rb" to "app/controllers/books_controller.rb"
- Add space after "NOTE:"

Ref - https://github.com/rails/rails/pull/46342
2022-11-05 08:26:14 +05:30
Jonathan Hefner
de304819ae
Merge pull request #46425 from bdewater/fix-error-highlight-dark-mode
Make error highlight readable on dark mode
2022-11-04 17:19:24 -05:00
Bart de Water
8cb96a3e04 Make error highlight readable on dark mode 2022-11-04 17:57:46 -04:00
hmbreaux
914a732c21
Add API documentation for Routing#draw
Adding documentation to the API doc for `ActionDispatch::Routing::Mapper::Resources#draw` method,
inspired by the Rails Guide routing section. Also removed extra colon in title.
2022-10-31 21:17:42 -07:00
Jonathan Hefner
7a6bcc6285
Merge pull request #46388 from jonathanhefner/action_view-deprecator
Add `ActionView.deprecator`
2022-10-31 17:04:04 -05:00
Jean Boussier
cfa9c9f891 Fix a typo in missing_exact_template.html.erb 2022-10-31 12:11:20 +01:00
Jonathan Hefner
b5248aca16 Add ActionView.deprecator
This commit adds `ActionView.deprecator` and replaces all usages of
`ActiveSupport::Deprecation.warn` in `actionview/lib` with
`ActionView.deprecator`.  This commit also replaces a call to Ruby's
`Module#deprecate_constant` with Rails' `DeprecatedConstantProxy`, so
that its deprecation behavior can be configured using
`ActionView.deprecator`.

Additionally, this commit adds `ActionView.deprecator` to
`Rails.application.deprecators` so that it can be configured via
settings such as `config.active_support.report_deprecations`.

This commit also removes a few defunct `assert_deprecated` calls that
were not failing because they were nested in `assert_raises`, and the
raised error prevented checking the deprecation.  (One was mistakenly
kept in d52d7739468153bd6cb7c629f60bd5cd7ebea3eb when converting
`test_render_file_with_errors` to `test_render_template_with_errors`;
the other two were added in dd9991bac598bb5da312278a749cf85e19b027cc but
not removed when the deprecation was completed in
85ecf6e4098601222b604f7c1cbdcb4e49a6d1f0.)
2022-10-30 16:01:39 -05:00
Jonathan Hefner
bb96ea70cb
Merge pull request #46366 from jonathanhefner/action_dispatch-deprecator
Add `ActionDispatch.deprecator`
2022-10-29 15:55:20 -05:00
Jean Boussier
b3c4ecac2b
Merge pull request #46342 from olivierlacan/docs/view-template
Improve missing template error page
2022-10-28 19:49:22 +02:00
Jonathan Hefner
48d4e6e02b Add ActionDispatch.deprecator
This commit adds `ActionDispatch.deprecator` and replaces all usages of
`ActiveSupport::Deprecation.warn` in `actionpack/lib/action_dispatch`
with `ActionDispatch.deprecator`.

Additionally, this commit adds `ActionDispatch.deprecator` to
`Rails.application.deprecators` so that it can be configured via
settings such as `config.active_support.report_deprecations`.
2022-10-27 17:11:02 -05:00
Jonathan Hefner
b287779499 Add {Abstract,Action}Controller.deprecator
This commit adds `AbstractController.deprecator` and
`ActionController.deprecator`, and replaces all usages of
`ActiveSupport::Deprecation.warn` in `actionpack/lib/action_controller`
with the latter.

Additionally, this commit adds `ActionController.deprecator` to
`Rails.application.deprecators`.  Because `AbstractController` does not
have its own railtie to do the same, `AbstractController` and
`ActionController` use the same deprecator instance.  Thus, both can be
configured via `Rails.application.deprecators[:action_controller]` or
via config settings such as `config.active_support.report_deprecations`.
2022-10-27 16:20:53 -05:00
Rafael Mendonça França
f297e6afbd
Merge pull request #46280 from rails/rm-expose-parameter_filter
Expose the request.parameter_filter
2022-10-27 16:26:47 -04:00
Olivier Lacan
9425191e63 Clarify missing template error page
Some goals here:
- Be less obtuse with word choices for folks who use English
as a second language.
- Stop referring to view templates as "templates" when the
literal directory is called `app/views` which has and will
confuse beginners (otherwise let's rename the directory).
- Stop formatting the HTML with `<br>` tags like it's 2005
and let the text flow with the viewport as appropriate.
- Give a *concrete* example of the naming relationship between
a controller and its view template, based on
[the ActionView Rails Guides][1].

I also tried to clarify the frankly confusing copy explaining
the 204 No Content rendering case, which I think should
probably mention that such endpoints shouldn't be allowed to
render HTML to avoid this error, but that might be pushing
the scope of the error feedback a bit too far.

[1]: https://guides.rubyonrails.org/layouts_and_rendering.html
2022-10-26 01:09:09 -04:00
Elliot Crosby-McCullough
044935c773
Fix content-type header with send_stream
The Rack specification[1] states that header values
must be a `String` instance (or array thereof).

When setting up the content-type header based on the
file extension, `send_stream` assigns the whole
`Mime::Type` object, instead of its `String`
representation.

This change ensures that all three ways of setting
the content-type header (implicit via extension,
implicit via a symbol, and explicit via a string)
all result in a `String` instance being assigned as
the header's value.

[1] 0a62f75eee/SPEC.rdoc (label-The+Headers)
2022-10-24 15:27:50 +01:00
Jean Boussier
971fa17502
Merge pull request #46279 from ghiculescu/query-tags-dupe 2022-10-23 01:22:41 +02:00
Alex Ghiculescu
f737b5ec13 Fix double logging in ActiveRecord::QueryLog
Fixes https://github.com/rails/rails/issues/46103

An issue exists if you set `config.active_record.query_log_tags` to an array that includes `:controller`, `:action`, or `:job`; the relevant item will get duplicated in the log line. This occured because the relevant railties would add the item to `config.active_record.query_log_tags` again during setup. This PR fixes that by only adding those items to the config if they aren't already set.

The issue proposed more documentation to work around this, but I think it's a bug and should be fixed directly.
2022-10-22 15:53:14 -05:00
Niklas Haeusele
be177e4566 Fix #46244 Remove innerHTML usage to avoid self-XSS 2022-10-21 21:18:48 +02:00
Rafael Mendonça França
365df75346
Expose the request.parameter_filter
This is useful when you want to filter your own hashes based on the
same parameter filter as the request.

Examples of this are exception notification and logging, that needs to
load headers or even custom values from the request, and want to keep
filtering those.
2022-10-19 21:31:53 +00:00
Jean Boussier
58e7fc18cb
Merge pull request #46223 from j-manu/screenshot-filename-whitelist-sanitizer 2022-10-12 16:56:15 +02:00
Aaron Patterson
2f36f0a2bb
Merge pull request #46171 from rails/refactor-errors
Add column information inside ERB templates
2022-10-11 15:10:40 -07:00
Manu J
bccf42baf8 Remove all non word characters from screenshot filenames
Screenshot filenames are derived from test names which can contain
special characters. These special characters may not be supported by
CI systems like Github Actions. Replacing all non word characters
ensures compatibility.
2022-10-11 19:13:01 +05:30
Jean Boussier
d917896f45 Enable verbose mode in test and report warnings as errors
We recently let a few very easy to avoid warnings get merged.
The root cause is that locally the test suite doesn't run in
verbose mode unless you explictly pass `-w`.

On CI warnings are enabled, but there is no reason to look at the
build output unless something is failing. And even if one wanted
to do that, that would be particularly work intensive since warnings
may be specific to a Ruby version etc.

Because of this I believe we should:

  - Always run the test suite with warnings enabled.
  - Raise an error if a warning is unexpected.

We've been using this pattern for a long time at Shopify both in private
and public repositories.
2022-10-11 09:25:18 +02:00
Guillaume CABANEL
ca11431647
Update CHANGELOG with PR #45427 changes (#46215)
* Update CHANGELOG with PR #45427 changes [ci skip]

Co-authored-by: Petrik de Heus <petrik@deheus.net>
2022-10-10 21:07:22 +02:00
Aaron Patterson
0c55a87ccf
Stop using a global for storing template info
This isn't as easy, but should eliminate any memory leaks in dev
2022-10-09 15:51:23 -07:00
Aaron Patterson
aa37b787ef
Use file path as the error lookup key
We have access to the path from the backtrace location object.  If we
use the path of the ERB as the key, then anytime the ERB changes it'll
just overwrite that template instance in the error handling hash
2022-10-09 14:55:50 -07:00
Aaron Patterson
c4c72ad0bb
remove sentinel object 2022-10-09 14:52:17 -07:00
Aaron Patterson
650e99ac5b
Map column information in to ERB templates
This commit maps the column information returned from ErrorHighlight in
to column information within the source ERB template.  ErrorHighlight
only understands the compiled Ruby code, so this commit adds a small
translation layer that converts the values from ErrorHighlight in to the
right values for the ERB source template
2022-10-09 14:52:17 -07:00
Aaron Patterson
e85edcc45d
Ask backtrace locations for their spot information
This way we can do special stuff when the exceptions come from special
locations
2022-10-09 14:52:17 -07:00
Aaron Patterson
343dba47e0
Only deal with backtrace locations in ExceptionWrapper
We should get out of the business of parsing backtraces and only use
backtrace locations.  Backtrace locations have the file and line number
information baked in, so we don't need to parse things anymore
2022-10-09 14:52:17 -07:00
Aaron Patterson
80a698d15c
Use a SyntaxError proxy object when displaying syntax error info
This commit adds a SyntaxErrorProxy object to active support and wraps
syntax error exceptions with that proxy object.  We want to enhance
syntax errors with information about the source location where they
actually happened (normally the backtrace doesn't contain such info).
Rather than mutating the original exception's backtrace, this wraps it
with a proxy object.

Eventually we will implement backtrace_locations on the proxy object so
that the exception handling middleware can be updated to _only_ deal
with backtrace_locations and never deal with raw `backtrace`
2022-10-09 14:52:17 -07:00
Aaron Patterson
c066440b92
only wrap exception once 2022-10-09 14:52:17 -07:00
Aaron Patterson
894acf9588
Wrapping the cause should do the "SyntaxError" magic 2022-10-09 14:52:16 -07:00
Aaron Patterson
bff868d56f
stop exposing the exception class 2022-10-09 14:52:16 -07:00
Aaron Patterson
7b2f9328a6
make the exceptiom method private so we can catch callers 2022-10-09 14:52:16 -07:00
Aaron Patterson
dec39e3961
Start hiding the exception object from the views
We are currently mutating exception objects and I would like to stop
doing that.  Unfortunately the views are calling many methods directly
on the exception and expecting that the mutations exist.

This patch refactors the templates so that they ask the ExceptionWrapper
class for information about the exception rather than directly asking
the exception object itself
2022-10-09 14:52:16 -07:00
Jonathan Hefner
1466b44299 Deprecate obsolete permissions policy directives
`speaker`, `vibrate`, and `vr` were [listed as policy-controlled features][1]
around the time when #33439 was first written (2018-07-25).  However,
`vibrate` was removed in w3c/webappsec-permissions-policy@b7271ac0f2,
`vr` was changed to `xr` in w3c/webappsec-permissions-policy@bec5ce6547,
and `speaker` was removed in w3c/webappsec-permissions-policy@18707d396e.
(And `xr` was later changed to `xr-spatial-tracking`, and still only has
[experimental support][2].)

Therefore, this commit deprecates these permissions policy directives.

[1]: 6d8bbbe738/features.md (policy-controlled-features)
[2]: 432a1532c9/features.md (standardized-features)
2022-10-05 12:18:55 -05:00
Jonathan Hefner
2a9f8aeb24
Merge pull request #45427 from guillaumecabanel/update-permissions-policy
Update permissions policy list
2022-10-05 12:17:15 -05:00
Jonathan Hefner
6a0ec0e54e Fix tests for selenium-webdriver v4.5.0
`selenium-webdriver` v4.5.0 adds more entries ("acceptInsecureCerts" and
"moz:debuggerAddress") to the `as_json` output for
`Selenium::WebDriver::Firefox::Options`, causing an exact comparison of
the Hash to fail.

See SeleniumHQ/selenium@58f5833ba0.
2022-09-29 11:13:06 -05:00
Aaron Patterson
08ef43ed5e
Merge pull request #46120 from rails/rescue-template-paths
Keep rescue template paths in an array
2022-09-27 15:15:06 -07:00
Nikita Vasilevsky
e7a1740114 Keep assert_redirected_to backwards compatible 2022-09-26 15:30:09 +00:00
Nikita Vasilevsky
28eb8b4818 Add assert_redirected_to test with custom message 2022-09-26 15:30:02 +00:00
Aaron Patterson
5c6e9d48e1
Keep rescue template paths in an array
Gotta be honest, this is so I can make some hacks.  Basically I would
like an engine to specify where to find rescue templates, and currently
there's no way to add search paths to the debug view lookup context.
This commit turns the template path in to an array (that I plan to
mutate, but nobody should do that besides me until we make an actual
good API).

I added the `dup` in `initialize` so in case the array is accidentally
mutated we don't leak memory.
2022-09-23 15:25:40 -07: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
John Bampton
3a32915bbc Fix word case. json -> JSON 2022-09-17 04:11:36 +10:00
Sreeram Venkitesh
9c751a1b05 Added status in API documentation for ActionController::Renderer#render 2022-09-16 18:48:14 +05:30
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
46bfabcfd4
Merge pull request #44547 from skipkayhil/fix-incorrect-assertions
fix remaining asserts that should be assert_equal
2022-09-12 20:32:42 -04:00
Josef Šimánek
b0fdca4fbc Rescue Rack::QueryParser::ParamsTooDeepError in HTTP request.
- render HTTP 400
- needs Rack 2.2.4+
2022-09-11 01:40:28 +02:00
Hartley McGuire
c62dcf54eb
fix remaining asserts that should be assert_equal
Found using Minitest/AssertWithExpectedArgument.

Also enabled the rule per feedback and fixed 29 additional violations
2022-09-09 19:22:21 -04:00
Rafael Mendonça França
977868b338
Merge PR #45956 2022-09-09 22:13:08 +00:00
Rafael Mendonça França
e3b9671e67
Copy-edit 8e65c22 2022-09-09 21:05:13 +00: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
Rafael Mendonça França
37492e2569
Merge pull request #45887 from ianneub/add-exclude-to-action_controller-parameters
Add exclude? method to ActionController::Parameters
2022-09-09 16:46:03 -04:00
Rafael Mendonça França
4f212ef212
Merge pull request #41517 from brunoarueira/fix/issue-38080-encoding-uploaded-file-headers
Encodes the uploaded file's headers
2022-09-09 16:05:41 -04:00
John Hawthorn
fc3c077f6b Round server timing to two decimal places 2022-09-08 21:23:25 -07:00
John Hawthorn
368275f157 Don't measure server timing for "!" topics
These are not intended for user consumption
2022-09-08 21:05:33 -07:00
John Hawthorn
384a479159 Fix ServerTiming in Threads, use single subscriber
Previously ActionDispatch::ServerTiming would subscribe and unsubscribe
on each request. This could cause issues with the internal stacks of
ActiveSupport::Notifications, particlularly under the previous AS::N
implementation which used thread-local stacks for every subscriber
(the new implementation has mostly mitigated this).

Additionally, the previous ServerTiming implementation did not report
metrics correctly in a multi-threaded environment.

This commit works around both of these issues by using a single global
subscription, which collects events into a per-thread Array.
2022-09-08 21:05:33 -07:00
Nathan Bardoux
e38ea1aeaa
ActionDispatch::Cookies json deserializer discards marshal dumps
Without this change if action_dispatch.cookies_serializer is set to
json and the app tries to read a marshal-serialized cookie, it will
raise a JSON::ParserError which won't clear the cookie and force app
users to manually clear the cookie in their browser.
(See #45127 for original bug discussion)
2022-09-07 13:09:07 -07:00
Ryo Nakamura
a5065d4abc Avoid using render(...) and return in example code 2022-09-02 06:33:43 +09:00
Jonathan Hefner
40dc22f715 Add :request to redirect.action_dispatch payload
Follow-up to #43755.

This adds the request object to the `redirect.action_dispatch` payload,
for parity with `redirect_to.action_controller`.
2022-08-31 13:53:48 -05:00
fatkodima
3158bbb9f6 Update rubocop-performance and enable more performance-related cops 2022-08-26 15:07:11 +03:00
Ian Neubert
ca29fca4c8 Add exclude? method to ActionController::Parameters 2022-08-25 13:44:12 -04:00
Orhan Toy
930e36f10b Extend routes --grep to also filter routes by matching against path 2022-08-25 08:33:51 +00:00
Jonathan Hefner
2045cef03b
Merge pull request #45859 from kratob/no-csp-response-for-304
Do not return CSP headers for 304 Not Modified responses
2022-08-23 15:13:09 -05:00
Yusuke Endoh
3beb2aff3b Use error_highlight gem to locate the columns where an error was raised
This change incorporates to Rails a feature called error_highlight that
has been available since Ruby 3.1. This allow Rails' error report screen
to display the fine-grained location where an error occurred (not only a
line number but also beginning and end column numbers of the code
fragment).

For ErrorHighlight, see https://bugs.ruby-lang.org/issues/17930 in
detail.

To use error_highlight, ExceptionWrapper now prefers
`Exception#backtrace_locations` (since Ruby 2.1), which returns an array
of `Thread::Backtrace::Location`s, instead of `Exception#backtrace`.
This is because error_highlight requires `Thread::Backtrace::Location`
to locate the column where an error was raised.

Co-Authored-By: John Hawthorn <john@hawthorn.email>
Co-Authored-By: Jean Boussier <jean.boussier@gmail.com>
2022-08-24 00:28:50 +09:00
Jean Boussier
2418939007
Merge pull request #45796 from Shopify/log-subscriber-silenced
Optimize AS::LogSubscriber
2022-08-22 10:43:49 +02:00
Tobias Kraze
3fadf8ac7f Do not return CSP headers for 304 Not Modified responses 2022-08-19 15:10:47 +02:00
akmhmgc
2f9c84a604
Fix trivial typo (#45855) 2022-08-19 08:29:52 -04:00
Nikita Vasilevsky
3b0d8c1ff0 Rescue EOFError error from rack on a multipart request 2022-08-15 23:51:13 +00:00
Jean Boussier
bd19d1baf1 Optimize AS::LogSubscriber
The various LogSubscriber subclasses tend to subscribe to events
but then end up doing nothing if the log level is high enough.

But even if we end up not logging, we have to go through the
entire notification path, record timing etc.

By allowing subscribers to dynamically bail out early, we can
save a lot of work if all subscribers are silenced.
2022-08-12 09:58:17 +02:00
Jean Boussier
a393e0de09
Merge pull request #43755 from djfpaagman/log_route_redirects
Log redirects from router similarly to controller redirects
2022-08-10 13:54:58 +02:00
Dennis Paagman
ee4700241e
Log redirects from router similarly to controller redirects 2022-08-10 12:00:16 +02:00
Jonathan Hefner
95fa021465
Merge pull request #45719 from bensheldon/subpath_engine_route_helpers
Allow Mounted Engine url_helpers to use config.relative_url_root
2022-08-09 14:49:39 -05:00
Ben Sheldon [he/him]
066ce1e34f
Allow Engine url_helpers to respect config.relative_url_root 2022-08-09 10:06:21 -07:00
fatkodima
b95ddd4ef5 Fix EtagWithFlash when there is no Flash middleware available
Co-authored-by: mihaic195 <colceriumi@gmail.com>
2022-08-06 18:41:10 +03:00
Jonathan Hefner
6e94889b72 Format inline code [ci-skip] 2022-08-05 21:36:18 -05:00
Jonathan Hefner
32c169d014 Linkify code references [ci-skip] 2022-08-05 21:36:18 -05:00
Jonathan Hefner
b13107fe5e Fix typos [ci-skip] 2022-08-05 21:36:18 -05:00
Gannon McGibbon
9414a8b79f
Merge pull request #45701 from gmcgibbon/unused_routes_script
Add `routes --unused` option to detect extraneous routes.
2022-08-04 21:57:09 -05: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
Gannon McGibbon
5613b1240a Add routes --unused option to detect extraneous routes.
Routes take a long time to draw. Over time, a Rails app can become slow
to boot simply because of how many routes it has. This script can be
used to detect routes that are drawn, but aren't actually valid.
Removing routes this script detects can help speed up your app and
remove dead code.

Example:

```
> bin/rails routes --unused

Found 2 unused routes:

Prefix Verb URI Pattern    Controller#Action
   one GET  /one(.:format) action#one
   two GET  /two(.:format) action#two
```
2022-08-02 20:07:45 -05:00
Jonathan Hefner
c95780d7c6 Fix default SameSite for session cookies
Follow-up to #45501.

The Rack base class that `CookieStore` inherits from [always sets
`:same_site`][1].  Thus, `options.key?(:same_site)` always returns true
for session cookies, preventing a default value from being set.

It would be possible to change Rack to conditionally set `:same_site`,
but, from Rack's perspective, it has no reason to not set `:same_site`,
because it treats a `nil` value the same as no value.

Therefore, this commit specifies a default `:same_site` in `CookieStore`,
which simply defers to `request.cookies_same_site_protection` as
`CookieJar` does.

Fixes #45681.

[1]: https://github.com/rack/rack/blob/2.2.4/lib/rack/session/abstract/id.rb#L398-L402
2022-07-28 16:19:21 -05:00
Jakub Malinowski
f075e0cf06
Prevent ActionDispatch::ServerTiming from overwriting existing header 2022-07-18 20:51:10 +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
Alex Ghiculescu
d29e755aea Allow opting out of the SameSite cookie attribute when setting a cookie.
Since 7ccaa125ba it's not been possible to not include `SameSite` on your cookies. `SameSite` is recommended, but it's not a required field, and you should be able to opt out of it.

This PR introduces that ability: you can opt out of `SameSite` by passing `same_site: false`.

```ruby
cookies[:foo] = { value: "bar", same_site: false }
```

Previously, this incorrectly set the `SameSite` attribute to the value of the `cookies_same_site_protection` setting. https://github.com/rails/rails/pull/44934 added docs saying that you could pass `nil` as a value, but that also would fall back to the default (`:lax`).
2022-07-03 10:40:51 -05:00
Alex Ghiculescu
1ee984dfe4 Anchor the Action Cable server's route
Fixes https://github.com/rails/rails/issues/45489

- Adds `anchor: true` to the Action Cable server mount, so that it only strictly matches `/cable` rather than anything that starts with that.
- Uses `reverse_merge` instead of `merge` in `Mapper#mount`, so that you can override these options if you need to.
2022-06-29 13:26:49 -05: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
Guillaume Cabanel
13b0c6330a Update permissions policy list 2022-06-22 12:43:02 +02:00
Jonathan Hefner
949a5e4c28
Merge pull request #45395 from skipkayhil/rm-ar-store-special
Remove special handling for ActiveRecordStore
2022-06-20 14:06:29 -05:00
Hartley McGuire
27285e7881
Remove special handling for ActiveRecordStore
activerecord-session_store was removed in 0ffe190, and has been
displaying a special error message when missing since Rails 4.0.

Replace the specific error message so that third party stores get nicer
error handling as well
2022-06-20 00:35:36 -04:00
Hartley McGuire
ab31e83130 Fix docs for ActionController::Metal#headers
This documentation was correct when it was written in 6e75455, however
`headers` has moved a few times since:

- added to ActionController::Http in 216309c as part of the new_base
- Http was renamed to Metal in 52798fd
- headers was changed from an independent hash to a delegation in
  51c7ac1 and 54becd1

Added docs for Metal#request, Metal#response, and Metal#headers that can
be linked to from Response. The recommendation to use Metal delegation
methods instead of methods on Response was also removed due to a number of
docs/guides demonstrating the opposite.
2022-06-18 10:51:42 -05:00
Hartley McGuire
1d5f9c3e17
Fix references to RequestHelpers methods in docs
These were extracted into the RequestHelpers module in 9bac470
2022-06-14 18:08:13 -04:00
Eileen M. Uchitelle
7c1165c8c8
Merge pull request #45322 from eileencodes/fix-ruby-trunk-did-you-mean
Fix did you mean tests for ruby-trunk (3.2)
2022-06-10 13:30:38 -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
Jean Boussier
115be62709 Wrap rails runner in executor
The main reason is to automatically report uncaught exceptions
since `rails runner` is often used for cron tasks and such.
2022-06-10 14:16:49 +02: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
Shouichi Kamiya
2bab22c78b Document ActionDispatch::TestResponse#parsed_body [skip ci]
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
2022-05-29 10:11:13 +09:00
Gannon McGibbon
3dad2919d5 Rename behaviour to behavior in documentation 2022-05-26 17:14:18 -04:00
Jean Boussier
7a15d15169
Merge pull request #45142 from jonathanhefner/action_mailer-base-no-load-action_contoller-base
Avoid loading `ActionController::Base` when loading `ActionMailer::Base`
2022-05-21 08:17:40 -07:00
Eugene Kenny
436207aa20
Merge pull request #45141 from eugeneius/dont_call_headers
Don't call controller's headers method internally
2022-05-20 21:40:12 +01:00
Jean Boussier
6291a9f6d3
Merge pull request #45104 from dorianmariefr/add-alias-for-method-method-for-debugging
Allow easier debugging of Action Dispatch requests
2022-05-20 12:33:28 -07:00
Jonathan Hefner
7415b93580 Avoid ActionController on ActionMailer::Base load
This refactor avoids unnecessarily loading `ActionController::Base` when
loading `ActionMailer::Base`.

Before:

```
$ bin/rails r 'Benchmark.memory { |x| x.report("load"){ ActionMailer::Base } }'
Calculating -------------------------------------
                load    10.013M memsize (     1.372M retained)
                        78.341k objects (    14.363k retained)
                        50.000  strings (    50.000  retained)
```

After:

```
$ bin/rails r 'Benchmark.memory { |x| x.report("load"){ ActionMailer::Base } }'
Calculating -------------------------------------
                load     5.043M memsize (   729.741k retained)
                        38.854k objects (     7.809k retained)
                        50.000  strings (    50.000  retained)
```
2022-05-20 11:57:34 -05: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
Guillermo Iguaran
6731fa8203
Merge pull request #45115 from ghiculescu/csp-helpers
Fix using helpers in `content_security_policy` and `permissions_policy`
2022-05-18 13:51:36 -07:00
Dorian Marié
190d1424a4 Allow easier debugging of Action Dispatch requests
Kernel#method was redefined so one couldn't do for instance.

method(:POST).source_location

Now when called without arguments it returns the method of the
request and when called with arguments it uses Kernel#method

Which makes debugging easier

Co-authored-by: Joé Dupuis <joe@dupuis.io>
2022-05-18 13:03:30 -07:00
Alex Ghiculescu
0ddad32af5 Fix using helpers in content_security_policy and permissions_policy
Fixes https://github.com/rails/rails/issues/45034

Currently helpers that are generated using `helper_method` cannot be used in `content_security_policy` and `permissions_policy`, this is because the use of `yield` causes `self` to be set incorrectly. By using `instance_exec` we ensure the scoping is correct so that you can access the same methods you'd be able to if you wrote your own `before_action`.
2022-05-18 11:55:54 -05: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
Jean Boussier
e2dbb942d9 Include the unexpected class in InvalidParameterKey message
It is best practice to include the unexpected value in logs
and error message as it can often make it much easier to understand
where the error come from.
2022-05-14 17:03:49 -04:00
Jean Boussier
ee2ab9866a Don't change the encoding of frozen parameters
Fix: https://github.com/rails/rails/issues/44923

The fix may seem very ad hoc, but this methods assumes all params
come from Rack, hence are mutable. So checking for frozen is a decent
proxy for ignoring the router defaults.
2022-05-12 09:21:08 -04:00
Jean Boussier
f19e896d0d
Merge pull request #44961 from franzliedke/patch-1
Complete check for custom CSRF storage strategies
2022-05-09 10:08:42 +02:00
Jean Boussier
4fed54f0a6
Merge pull request #44979 from acronin-stash/fix-module-middleware-name
Correctly get name of middleware when a it is Module
2022-05-09 10:07:38 +02:00
Gannon McGibbon
377ae3cee6
Merge pull request #44866 from stefkin/acp-consistent-has-value
Make behaviour of has_value?/value? more consistent
2022-05-06 10:14:35 -04:00
Seva Stefkin
743ab43686
Make behaviour of has_value?/value? more consistent 2022-05-06 15:52:22 +02:00
Jean Boussier
c30ef14927
Merge pull request #44937 from fatkodima/missing-exceptions-require
Add missing require of `action_controller/metal/exceptions` to `action_controller`
2022-05-03 19:03:53 +02:00
Aislinn Cronin
993e32bda5 update inspect method used to print name of middleware to check for module instead of class 2022-05-02 15:10:36 -04:00
Guillaume CABANEL
d0bd1e93a1 Update RDoc comments for #redirect
Add the default status code returned by `ActionDispatch::Routing::Redirection#redirect` in the RDoc comment.

Include an example

Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
2022-05-02 10:39:18 +02:00
Franz Liedke
fa938a909f
Complete check for custom CSRF storage strategies
As the `reset` method is called without further conditionals in line 342, all
custom strategies must implement this method as well.

This may have been an oversight in one of the many iterations of #44283.
2022-04-26 14:05:30 +02:00
Hartley McGuire
7777a11625
Remove to_ary from RackBody
It was added in 66f8997 to be compatible with Rack::ContentLength.
However, to_ary was removed from Rack::Response in 2.1.0, and
Rack::ContentLength stopped checking for response bodies to define
to_ary in 2.2.0. In addition, Rack 3 will eventually require response
bodies that define to_ary to have a proper return value.

Since the minimum supported Rack version is already 2.2.0, to_ary can
be safely removed now.
2022-04-24 15:14:25 -04:00