From 6be78efcb2848d740b5c1c16511953a05b328e82 Mon Sep 17 00:00:00 2001 From: Aleksander Klenov Date: Mon, 15 May 2023 14:40:00 +0700 Subject: [PATCH] Fixed request crash with empty body and unexpected header Content-Type --- CHANGELOG.md | 5 +++++ http/server.lua | 10 +++++++--- .../integration/http_server_requests_test.lua | 20 +++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d581ba7..d5aaf6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed +- Fixed request crash with empty body and unexpected header Content-Type (#189) + ## [1.5.0] - 2023-03-29 ### Added diff --git a/http/server.lua b/http/server.lua index 2e67a45..286be38 100644 --- a/http/server.lua +++ b/http/server.lua @@ -208,21 +208,25 @@ local function request_content_type(self) end local function post_param(self, name) - if self:content_type() == 'multipart/form-data' then + local body = self:read_cached() + + if body == '' then + rawset(self, 'post_params', {}) + elseif self:content_type() == 'multipart/form-data' then -- TODO: do that! rawset(self, 'post_params', {}) elseif self:content_type() == 'application/json' then local params = self:json() rawset(self, 'post_params', params) elseif self:content_type() == 'application/x-www-form-urlencoded' then - local params = lib.params(self:read_cached()) + local params = lib.params(body) local pres = {} for k, v in pairs(params) do pres[ uri_unescape(k) ] = uri_unescape(v, true) end rawset(self, 'post_params', pres) else - local params = lib.params(self:read_cached()) + local params = lib.params(body) local pres = {} for k, v in pairs(params) do pres[ uri_unescape(k) ] = uri_unescape(v) diff --git a/test/integration/http_server_requests_test.lua b/test/integration/http_server_requests_test.lua index fce82ce..06fd185 100644 --- a/test/integration/http_server_requests_test.lua +++ b/test/integration/http_server_requests_test.lua @@ -426,3 +426,23 @@ g.test_get_dot_slash = function() local r = http_client.get(helpers.base_uri .. '/dot_slash.') t.assert_equals(r.status, 200) end + +g.test_unwanted_content_type = function() + local httpd = g.httpd + httpd:route({ + path = '/unwanted-content-type' + }, function(req) + local response = req:render{ json = req:param() } + response.status = 200 + return response + end) + + local opt = { + headers = { + ['Content-Type'] = 'application/json' + } + } + local r = http_client.get(helpers.base_uri .. '/unwanted-content-type', opt) + t.assert_equals(r.status, 200) + t.assert_equals(r.body, '[]') +end