Skip to content

Make use to #media_type instead of #content_type to avoid false negatives (e.g., multipart/form-data; boundary=...) #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions lib/hanami/action/mime.rb
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,13 @@ def enforce_accept(request, config)
# @since 2.0.0
# @api private
def enforce_content_type(request, config)
content_type = request.content_type
# Compare media type (without parameters) instead of full Content-Type header
# to avoid false negatives (e.g., multipart/form-data; boundary=...)
media_type = request.media_type

return if content_type.nil?
return if media_type.nil?

return if accepted_mime_type?(content_type, config)
return if accepted_mime_type?(media_type, config)

yield
end
Expand Down
9 changes: 9 additions & 0 deletions spec/integration/hanami/controller/mime_type_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@
end
end

context "when uploading a file to an action with format multipart/form-data configured" do
it "does not return 415 for valid multipart/form-data request with boundary" do
response = app.post("/upload", "CONTENT_TYPE" => "multipart/form-data; boundary=----abc123")

expect(response.status).to eq(200)
expect(response.body).to eq("multipart/form-data; boundary=----abc123")
end
end

context "when Content-Type are sent and formats are configured to accept all" do
it "accepts the request with a custom content type" do
response = app.get("/relaxed", "CONTENT_TYPE" => "application/custom")
Expand Down
11 changes: 11 additions & 0 deletions spec/support/fixtures.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1597,6 +1597,16 @@ def handle(*, res)
end
end

class UploadAction < Hanami::Action
config.formats.add :multipart, "multipart/form-data"
config.format :multipart

def handle(req, res)
res.format = :txt
res.body = req.content_type
end
end

class Restricted < Hanami::Action
config.formats.add :custom, "application/custom"

Expand Down Expand Up @@ -1641,6 +1651,7 @@ def initialize
get "/custom_from_accept", to: Mimes::CustomFromAccept.new
get "/strict", to: Mimes::Strict.new
get "/relaxed", to: Mimes::Relaxed.new
post "/upload", to: Mimes::UploadAction.new
end
end

Expand Down