request-rescue 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a46a0e78ebdedc66b0a90b69c6b4e22be032bc12513c1896bdbad992327b08c6
4
+ data.tar.gz: 0c603c0d2f7d6c8636a19899d351f40e4151fce2f3b75f831cd06f3f145f67f3
5
+ SHA512:
6
+ metadata.gz: e9aa5738520d06804ffa073e8bddaa31dac2af7d003e122f93e418d921857bba6e237152019ec9b83ac2737445436b520276980ff81fbbb4a0eff55352848560
7
+ data.tar.gz: f2e4089294445a24adfa15a193453a00b9ad2b19c62d2663fb07880e9fca50bda51e90441b8d3a235170a0662d5afa827783b6043560772fea48d567c501050d
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Add Rails request middleware, a controller concern, mountable error pages and a Rack exception app.
6
+ - Support HTML and JSON errors, API-only applications and optional Apipie validation.
7
+ - Provide a migration mode for applications using feedmob-rescue 0.1.7.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 mike
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # Request Rescue
2
+
3
+ Request Rescue gives Rails applications consistent error responses for malformed queries, unrecognized HTTP methods, missing templates, unsupported formats and invalid Apipie parameters. A controller concern handles exceptions raised in your actions. The Rails engine provides mountable HTML and JSON error pages.
4
+
5
+ ## Install
6
+
7
+ Add `gem "request-rescue"` to your Gemfile and run `bundle install`. To try this checkout before the first RubyGems release, use `gem "request-rescue", path: "/path/to/request-rescue"`.
8
+
9
+ Include the concern in controllers where you want to handle these exceptions. It also works with `ActionController::API`.
10
+
11
+ ```ruby
12
+ class ApplicationController < ActionController::Base
13
+ include RequestRescue::Controller
14
+ end
15
+ ```
16
+
17
+ Mount the pages in the application's routes. The mount name is used by migration redirects.
18
+
19
+ ```ruby
20
+ Rails.application.routes.draw do
21
+ mount RequestRescue::Engine, at: "/errors", as: :request_rescue
22
+ end
23
+ ```
24
+
25
+ To render unhandled exceptions through Request Rescue, set the exception app in environments that show public error pages. Rails determines their HTTP status. A raised application exception produces a generic 500 response.
26
+
27
+ ```ruby
28
+ # config/environments/production.rb
29
+ config.exceptions_app = RequestRescue::ExceptionsApp
30
+ ```
31
+
32
+ ## Responses
33
+
34
+ | Request or exception | Default response |
35
+ | --- | --- |
36
+ | Malformed nested query | 400 |
37
+ | HTTP method unrecognized by Rails | 405 JSON |
38
+ | Unsupported controller format or missing template | 404 |
39
+ | Invalid cross-origin script request | 403 |
40
+ | Apipie missing or invalid parameter | 422 |
41
+
42
+ HTML applications render error pages by default. Clients can request JSON with `Accept: application/json`. API-only applications default to JSON. HEAD requests return the status and headers with an empty body. The middleware is installed automatically. Apipie integration is available when the host loads `apipie-rails`.
43
+
44
+ Development re-raises handled controller exceptions for debugging. Cross-origin script exceptions also propagate in the test environment.
45
+
46
+ ## Migrate from feedmob-rescue 0.1.7
47
+
48
+ 1. Replace the old Gemfile entry and change `include Feedmob::Rescue` to `include RequestRescue::Controller`.
49
+ 2. Replace the old engine with `RequestRescue::Engine` at the same mount path and name it `request_rescue`. Existing root mounts can continue using `at: "/"`. Keep the application's Apipie dependency if its controllers use Apipie.
50
+ 3. Set `config.request_rescue.legacy_responses = true` in the application configuration to preserve the previous redirects and empty 200 response to cross-origin script requests in production.
51
+
52
+ Migration mode redirects missing templates and unknown formats to the mounted `not_found` page and Apipie errors to `invalid_params`. The mounted pages return 200 in this mode. Existing root mounts can keep `config.exceptions_app = self.routes` for their numeric 404 and 500 routes. To preserve the original HTTP error status regardless of the mount path, use `RequestRescue::ExceptionsApp`. After clients can consume direct 404, 403 and 422 responses, disable migration mode. Rolling back requires restoring the old Gemfile entry, concern, engine and exception app together.
53
+
54
+ ## Verify a package locally
55
+
56
+ Run the verifier under the Ruby version for the selected Rails and Rack pair.
57
+
58
+ ```sh
59
+ RBENV_VERSION=3.0.3 APIPIE_VERSION=0.8.1 rbenv exec ruby bin/verify 6.1.5 2.2.4
60
+ ```
61
+
62
+ The verifier builds and installs the gem into a temporary directory, boots a Rails host and exercises its full Rack stack. It writes a package, dependency lockfile and JSON request results with the package SHA-256 under `pkg/`. Omit `APIPIE_VERSION` to verify installation without the optional adapter. Set `VERIFY_PACKAGE` to an existing build to test the same bytes across runtimes. Set `VERIFY_LOCK` to a previous result’s lockfile to replay its dependency resolution. See the [compatibility matrix](https://github.com/feed-mob/request-rescue/blob/main/PLAN.md) for the seven targeted Ruby/Rails pairs and their Rack versions.
63
+
64
+ ## Releases
65
+
66
+ Every pull request runs the compatibility matrix. The required **All request tests passed** check must pass before merging to `main`. Each merge starts the release workflow, which verifies the merged commit and publishes the version in `lib/request_rescue/version.rb` through RubyGems trusted publishing. The workflow skips publication if that version already exists. To release another version, update the version and changelog in a pull request.
67
+
68
+ ## License
69
+
70
+ [MIT](LICENSE.txt).
data/config/routes.rb ADDED
@@ -0,0 +1,6 @@
1
+ RequestRescue::Engine.routes.draw do
2
+ get "not_found", to: RequestRescue::ErrorResponse.new(404, legacy_page: true), as: :not_found
3
+ get "invalid_params", to: RequestRescue::ErrorResponse.new(422, legacy_page: true), as: :invalid_params
4
+ match "/404", to: RequestRescue::ErrorResponse.new(404, legacy_page: true), via: :all
5
+ match "/500", to: RequestRescue::ErrorResponse.new(500, legacy_page: true), via: :all
6
+ end
@@ -0,0 +1 @@
1
+ require_relative "request_rescue"
@@ -0,0 +1,46 @@
1
+ module RequestRescue
2
+ module Controller
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ rescue_from ActionController::UnknownFormat, ActionView::MissingTemplate, with: :request_rescue_not_found
7
+ rescue_from ActionController::InvalidCrossOriginRequest, with: :request_rescue_cross_origin
8
+ # Rails resolves string class names when handling an exception, so Apipie is optional.
9
+ rescue_from "Apipie::ParamMissing", "Apipie::ParamInvalid", with: :request_rescue_invalid_params
10
+ end
11
+
12
+ private
13
+
14
+ def request_rescue_not_found(error)
15
+ raise error if Rails.env.development?
16
+ return redirect_to(request_rescue.not_found_path) if Rails.application.config.request_rescue.legacy_responses
17
+
18
+ request_rescue_render(404)
19
+ end
20
+
21
+ def request_rescue_invalid_params(error)
22
+ raise error if Rails.env.development?
23
+ return redirect_to(request_rescue.invalid_params_path) if Rails.application.config.request_rescue.legacy_responses
24
+
25
+ request_rescue_render(422)
26
+ end
27
+
28
+ def request_rescue_cross_origin(error)
29
+ raise error if Rails.env.development? || Rails.env.test?
30
+ return head(:ok) if Rails.application.config.request_rescue.legacy_responses
31
+
32
+ request_rescue_render(403)
33
+ end
34
+
35
+ def request_rescue_render(code)
36
+ status, headers, body = ErrorResponse.new(code).call(request.env)
37
+ self.status = status
38
+ self.content_type = headers.fetch("content-type")
39
+ vary = response.get_header("Vary").to_s.split(/\s*,\s*/)
40
+ unless vary.include?("*") || vary.any? { |field| field.casecmp?("Accept") }
41
+ response.set_header("Vary", (vary + ["Accept"]).join(", "))
42
+ end
43
+ self.response_body = body
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,11 @@
1
+ module RequestRescue
2
+ class Engine < Rails::Engine
3
+ engine_name "request_rescue"
4
+ config.request_rescue = ActiveSupport::OrderedOptions.new
5
+ config.request_rescue.legacy_responses = false
6
+
7
+ initializer "request_rescue.middleware" do |app|
8
+ app.middleware.use RequestRescue::Middleware
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,56 @@
1
+ module RequestRescue
2
+ class ErrorResponse
3
+ MESSAGES = {
4
+ 400 => "Invalid request parameters",
5
+ 403 => "Forbidden",
6
+ 404 => "Page not found",
7
+ 405 => "Method not allowed",
8
+ 422 => "Invalid parameters",
9
+ 500 => "Internal server error"
10
+ }.freeze
11
+
12
+ def initialize(status, legacy_page: false)
13
+ @status = status
14
+ @legacy_page = legacy_page
15
+ end
16
+
17
+ def call(env)
18
+ message = MESSAGES.fetch(@status) { Rack::Utils::HTTP_STATUS_CODES.fetch(@status) }
19
+ json = @status == 405 || json_request?(env)
20
+ content_type = json ? "application/json" : "text/html"
21
+ content = if json
22
+ JSON.generate(errors: [message])
23
+ else
24
+ "<!doctype html><html><head><title>#{@status} #{message}</title></head>" \
25
+ "<body><h1>#{@status}</h1><p>#{message}</p><a href=\"/\">Home</a></body></html>"
26
+ end
27
+ method = env["action_dispatch.original_request_method"] || env["REQUEST_METHOD"]
28
+ status = @legacy_page && Rails.application.config.request_rescue.legacy_responses ? 200 : @status
29
+ [status, { "content-type" => "#{content_type}; charset=utf-8", "vary" => "Accept" },
30
+ method == "HEAD" ? [] : [content]]
31
+ end
32
+
33
+ private
34
+
35
+ def json_request?(env)
36
+ path = env["action_dispatch.original_path"] || env["PATH_INFO"]
37
+ return true if path.to_s.end_with?(".json")
38
+
39
+ accepted = ActionDispatch::Request.new(env).accepts
40
+ preference = accepted.find { |type| type == Mime[:json] || type == Mime[:html] }
41
+ preference ? preference == Mime[:json] : Rails.application.config.api_only
42
+ rescue ActionDispatch::Http::MimeNegotiation::InvalidType
43
+ Rails.application.config.api_only
44
+ end
45
+ end
46
+
47
+ # Rails rewrites PATH_INFO to the numeric HTTP status before dispatch.
48
+ class ExceptionsApp
49
+ def self.call(env)
50
+ path = env["PATH_INFO"].to_s
51
+ status = path.match?(%r{\A/[45]\d\d\z}) ? path[1..].to_i : 500
52
+ status = 500 unless Rack::Utils::HTTP_STATUS_CODES.key?(status)
53
+ ErrorResponse.new(status).call(env)
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,25 @@
1
+ module RequestRescue
2
+ class Middleware
3
+ def initialize(app)
4
+ @app = app
5
+ end
6
+
7
+ def call(env)
8
+ return ErrorResponse.new(405).call(env) unless ActionDispatch::Request::HTTP_METHODS.include?(env["REQUEST_METHOD"])
9
+ return ErrorResponse.new(400).call(env) unless valid_query?(env)
10
+
11
+ @app.call(env)
12
+ end
13
+
14
+ private
15
+
16
+ def valid_query?(env)
17
+ # Rack caches parsing here. Rails can still apply per-action encodings after routing.
18
+ Rack::Request.new(env).GET
19
+ true
20
+ rescue Rack::QueryParser::ParameterTypeError, Rack::QueryParser::InvalidParameterError, RangeError
21
+ # Old Rack releases use RangeError when the parser's nesting limit is reached.
22
+ false
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,3 @@
1
+ module RequestRescue
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,9 @@
1
+ require "logger"
2
+ require "rails"
3
+ require "action_controller/railtie"
4
+ require "json"
5
+ require_relative "request_rescue/version"
6
+ require_relative "request_rescue/error_response"
7
+ require_relative "request_rescue/middleware"
8
+ require_relative "request_rescue/controller"
9
+ require_relative "request_rescue/engine"
metadata ADDED
@@ -0,0 +1,116 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: request-rescue
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - FeedMob
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: railties
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 6.1.5
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '7.2'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: 6.1.5
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '7.2'
33
+ - !ruby/object:Gem::Dependency
34
+ name: actionpack
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: 6.1.5
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '7.2'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 6.1.5
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '7.2'
53
+ - !ruby/object:Gem::Dependency
54
+ name: rack
55
+ requirement: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: 2.2.3
60
+ - - "<"
61
+ - !ruby/object:Gem::Version
62
+ version: '4'
63
+ type: :runtime
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 2.2.3
70
+ - - "<"
71
+ - !ruby/object:Gem::Version
72
+ version: '4'
73
+ description:
74
+ email:
75
+ executables: []
76
+ extensions: []
77
+ extra_rdoc_files: []
78
+ files:
79
+ - CHANGELOG.md
80
+ - LICENSE.txt
81
+ - README.md
82
+ - config/routes.rb
83
+ - lib/request-rescue.rb
84
+ - lib/request_rescue.rb
85
+ - lib/request_rescue/controller.rb
86
+ - lib/request_rescue/engine.rb
87
+ - lib/request_rescue/error_response.rb
88
+ - lib/request_rescue/middleware.rb
89
+ - lib/request_rescue/version.rb
90
+ homepage: https://github.com/feed-mob/request-rescue
91
+ licenses:
92
+ - MIT
93
+ metadata:
94
+ source_code_uri: https://github.com/feed-mob/request-rescue
95
+ changelog_uri: https://github.com/feed-mob/request-rescue/blob/main/CHANGELOG.md
96
+ allowed_push_host: https://rubygems.org
97
+ post_install_message:
98
+ rdoc_options: []
99
+ require_paths:
100
+ - lib
101
+ required_ruby_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: 3.0.3
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ requirements: []
112
+ rubygems_version: 3.4.19
113
+ signing_key:
114
+ specification_version: 4
115
+ summary: Handle malformed requests and render error responses in Rails applications.
116
+ test_files: []