From 6635c334896b2d803ca159fe45a204e3a8a07f7d Mon Sep 17 00:00:00 2001 From: Yusheng Li Date: Mon, 21 Aug 2023 14:17:13 +0800 Subject: [PATCH] fix(PDK): fix response body repeated when kong.response.get_raw_body() called multiple times (#11424) (cherry picked from commit 48a2de21ee765f84742b382b9a043d16da4d7348) --- CHANGELOG/unreleased/kong/11424.yaml | 7 ++++++ kong/pdk/response.lua | 1 + t/01-pdk/08-response/14-get_raw_body.t | 34 ++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 CHANGELOG/unreleased/kong/11424.yaml diff --git a/CHANGELOG/unreleased/kong/11424.yaml b/CHANGELOG/unreleased/kong/11424.yaml new file mode 100644 index 000000000000..3b0440be7f07 --- /dev/null +++ b/CHANGELOG/unreleased/kong/11424.yaml @@ -0,0 +1,7 @@ +message: Fix response body gets repeated when `kong.response.get_raw_body()` is called multiple times in a request lifecycle. +type: bugfix +scope: PDK +prs: + - 11424 +jiras: + - "FTI-5296" diff --git a/kong/pdk/response.lua b/kong/pdk/response.lua index 9ae4ab9f55e1..2c02c641e1bb 100644 --- a/kong/pdk/response.lua +++ b/kong/pdk/response.lua @@ -609,6 +609,7 @@ local function new(self, major_version) end arg[1] = body_buffer + ngx.ctx.KONG_BODY_BUFFER = nil return body_buffer end diff --git a/t/01-pdk/08-response/14-get_raw_body.t b/t/01-pdk/08-response/14-get_raw_body.t index 97db3cc593f7..b9cf7853d237 100644 --- a/t/01-pdk/08-response/14-get_raw_body.t +++ b/t/01-pdk/08-response/14-get_raw_body.t @@ -73,3 +73,37 @@ Enhanced by Body Filter Called 3 times --- no_error_log [error] + + + +=== TEST 3: response.get_raw_body() calls multiple times +--- http_config eval: $t::Util::HttpConfig +--- config + location = /t { + content_by_lua_block { + ngx.print("hello, world!\n") + } + body_filter_by_lua_block { + local PDK = require "kong.pdk" + local pdk = PDK.new() + -- call pdk.response.get_raw_body() multiple times + ngx.ctx.called = (ngx.ctx.called or 0) + 1 + for i = 1, 3 do + ngx.ctx.called2 = (ngx.ctx.called2 or 0) + 1 + local body = pdk.response.get_raw_body() + if body then + assert("hello, world!\n" == body) + end + end + } + log_by_lua_block { + assert(ngx.ctx.called == 2) + assert(ngx.ctx.called2 == 6) + } + } +--- request +GET /t +--- response_body +hello, world! +--- no_error_log +[error]