From 39f9ee9ce5d16c0e79e18ef588c69a445829fde4 Mon Sep 17 00:00:00 2001 From: johnlanni Date: Sat, 31 Oct 2026 20:04:04 +0800 Subject: [PATCH 1/4] feat(wrapper): add per-request body delivery requirement Signed-off-by: johnlanni --- pkg/iface/context.go | 4 + pkg/wrapper/plugin_wrapper.go | 22 +++++ pkg/wrapper/plugin_wrapper_test.go | 141 +++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+) create mode 100644 pkg/wrapper/plugin_wrapper_test.go diff --git a/pkg/iface/context.go b/pkg/iface/context.go index 16f917a..636079a 100644 --- a/pkg/iface/context.go +++ b/pkg/iface/context.go @@ -58,6 +58,10 @@ type HttpContext interface { WriteUserAttributeToLogWithKey(key string) error // You can call this function to set custom trace span attribute WriteUserAttributeToTrace() error + // RequireRequestBody requests buffered delivery to ProcessRequestBody for the current request, + // including binary, encoded, and WebSocket upgrade requests. If the complete body is unavailable, + // the wrapper sends a 503 response and pauses the request. The response body path is unchanged. + RequireRequestBody() // If the onHttpRequestBody handle is not set, the request body will not be read by default DontReadRequestBody() // If the onHttpResponseBody handle is not set, the request body will not be read by default diff --git a/pkg/wrapper/plugin_wrapper.go b/pkg/wrapper/plugin_wrapper.go index 380177b..2882631 100644 --- a/pkg/wrapper/plugin_wrapper.go +++ b/pkg/wrapper/plugin_wrapper.go @@ -49,6 +49,8 @@ const ( PluginIDKey = "_plugin_id_" VMLeaseKeyPrefix = "higress_wasm_vm_lease" ConfigStoreLeaderKey = "config_store" + + RequiredRequestBodyFailureStatusCode = 503 ) type oldParseConfigFunc[PluginConfig any] func(json gjson.Result, config *PluginConfig, log log.Log) error @@ -764,6 +766,7 @@ type CommonHttpCtx[PluginConfig any] struct { config *PluginConfig needRequestBody bool needResponseBody bool + requireRequestBody bool streamingRequestBody bool streamingResponseBody bool pauseStreamingResponse bool @@ -921,6 +924,11 @@ func (ctx *CommonHttpCtx[PluginConfig]) Method() string { return ctx.method } +func (ctx *CommonHttpCtx[PluginConfig]) RequireRequestBody() { + ctx.requireRequestBody = true + ctx.needRequestBody = true +} + func (ctx *CommonHttpCtx[PluginConfig]) DontReadRequestBody() { ctx.needRequestBody = false } @@ -1095,6 +1103,20 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr if !ctx.needRequestBody { return types.ActionContinue } + if ctx.requireRequestBody && ctx.plugin.vm.onHttpRequestBody != nil { + if !endOfStream { + return types.ActionPause + } + body, err := proxywasm.GetHttpRequestBody(0, bodySize) + if err != nil || len(body) != bodySize { + ctx.plugin.vm.log.Warnf("get required request body failed: %v, expected %d bytes, got %d", err, bodySize, len(body)) + if sendErr := proxywasm.SendHttpResponse(RequiredRequestBodyFailureStatusCode, nil, nil, -1); sendErr != nil { + ctx.plugin.vm.log.Errorf("send request body failure response failed: %v", sendErr) + } + return types.ActionPause + } + return ctx.plugin.vm.onHttpRequestBody(ctx, *ctx.config, body) + } if ctx.plugin.vm.onHttpStreamingRequestBody != nil && ctx.streamingRequestBody { chunk, _ := proxywasm.GetHttpRequestBody(0, bodySize) modifiedChunk := ctx.plugin.vm.onHttpStreamingRequestBody(ctx, *ctx.config, chunk, endOfStream) diff --git a/pkg/wrapper/plugin_wrapper_test.go b/pkg/wrapper/plugin_wrapper_test.go new file mode 100644 index 0000000..bb91d11 --- /dev/null +++ b/pkg/wrapper/plugin_wrapper_test.go @@ -0,0 +1,141 @@ +// Copyright (c) 2022 Alibaba Group Holding Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wrapper + +import ( + "testing" + + "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/proxytest" + "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/types" + "github.com/stretchr/testify/require" +) + +type bodyDeliveryHarness struct { + host proxytest.HostEmulator + contextID uint32 + requestBody []byte + requestBodyCalls int + responseBodyCallCount int +} + +func newBodyDeliveryHarness(t *testing.T, requireBody bool) *bodyDeliveryHarness { + t.Helper() + h := &bodyDeliveryHarness{} + vm := NewCommonVmCtx[struct{}]( + "body-delivery-test", + ProcessRequestHeaders(func(ctx HttpContext, _ struct{}) types.Action { + if requireBody { + ctx.RequireRequestBody() + } + return types.ActionContinue + }), + ProcessRequestBody(func(_ HttpContext, _ struct{}, body []byte) types.Action { + h.requestBodyCalls++ + h.requestBody = append([]byte(nil), body...) + return types.ActionContinue + }), + ProcessResponseBody(func(_ HttpContext, _ struct{}, _ []byte) types.Action { + h.responseBodyCallCount++ + return types.ActionContinue + }), + ) + host, reset := proxytest.NewHostEmulator(proxytest.NewEmulatorOption().WithVMContext(vm)) + t.Cleanup(reset) + host.RegisterForeignFunction("get_log_level", func([]byte) []byte { return make([]byte, 4) }) + require.Equal(t, types.OnPluginStartStatusOK, host.StartPlugin()) + h.host = host + h.contextID = host.InitializeHttpContext() + return h +} + +func (h *bodyDeliveryHarness) callRequestHeaders(headers [][2]string) types.Action { + headers = append(headers, [2]string{":authority", "default.test.com"}) + return h.host.CallOnRequestHeaders(h.contextID, headers, false) +} + +func TestRequireRequestBodyRawDelivery(t *testing.T) { + payload := []byte{0, 1, 2, 0xff, 'a', 'b', 'c'} + tests := []struct { + name string + headers [][2]string + }{ + {name: "binary content type", headers: [][2]string{{"content-type", "application/octet-stream"}}}, + {name: "identity encoding", headers: [][2]string{{"content-encoding", "identity"}}}, + {name: "gzip encoding", headers: [][2]string{{"content-encoding", "gzip"}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h := newBodyDeliveryHarness(t, true) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(tt.headers)) + require.Equal(t, types.ActionPause, h.host.CallOnRequestBody(h.contextID, payload[:3], false)) + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, payload[3:], true)) + require.Equal(t, 1, h.requestBodyCalls) + require.Equal(t, payload, h.requestBody) + require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) + }) + } +} + +func TestRequireRequestBodyWebSocketRequestOnly(t *testing.T) { + h := newBodyDeliveryHarness(t, true) + headers := [][2]string{{"connection", "upgrade"}, {"upgrade", "websocket"}} + require.Equal(t, types.ActionContinue, h.callRequestHeaders(headers)) + payload := []byte{0x81, 0x02, 'h', 'i'} + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, payload, true)) + require.Equal(t, payload, h.requestBody) + require.Equal(t, 1, h.requestBodyCalls) + + require.Equal(t, types.ActionContinue, h.host.CallOnResponseHeaders(h.contextID, nil, false)) + require.Equal(t, types.ActionContinue, h.host.CallOnResponseBody(h.contextID, []byte("response"), true)) + require.Zero(t, h.responseBodyCallCount) +} + +func TestRequireRequestBodyBufferFailure(t *testing.T) { + h := newBodyDeliveryHarness(t, true) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil)) + require.Equal(t, types.ActionPause, h.host.CallOnRequestBody(h.contextID, nil, true)) + require.Zero(t, h.requestBodyCalls) + response := h.host.GetSentLocalResponse(h.contextID) + require.NotNil(t, response) + require.Equal(t, uint32(RequiredRequestBodyFailureStatusCode), response.StatusCode) +} + +func TestRequestBodyLegacySkips(t *testing.T) { + tests := []struct { + name string + headers [][2]string + }{ + {name: "binary content type", headers: [][2]string{{"content-type", "application/octet-stream"}}}, + {name: "content encoding", headers: [][2]string{{"content-encoding", "gzip"}}}, + {name: "websocket", headers: [][2]string{{"connection", "upgrade"}, {"upgrade", "websocket"}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h := newBodyDeliveryHarness(t, false) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(tt.headers)) + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, []byte("skipped"), true)) + require.Zero(t, h.requestBodyCalls) + require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) + }) + } + + t.Run("plain body remains delivered", func(t *testing.T) { + h := newBodyDeliveryHarness(t, false) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil)) + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, []byte("plain"), true)) + require.Equal(t, []byte("plain"), h.requestBody) + require.Equal(t, 1, h.requestBodyCalls) + }) +} From d0582d5a3ebbe86152194eefe0192caf01069f55 Mon Sep 17 00:00:00 2001 From: johnlanni Date: Sat, 31 Oct 2026 21:57:49 +0800 Subject: [PATCH 2/4] fix(wrapper): complete required body delivery Signed-off-by: johnlanni --- pkg/iface/context.go | 4 -- pkg/wrapper/plugin_wrapper.go | 74 ++++++++++++++++++++---------- pkg/wrapper/plugin_wrapper_test.go | 52 +++++++++++++++++---- 3 files changed, 93 insertions(+), 37 deletions(-) diff --git a/pkg/iface/context.go b/pkg/iface/context.go index 636079a..16f917a 100644 --- a/pkg/iface/context.go +++ b/pkg/iface/context.go @@ -58,10 +58,6 @@ type HttpContext interface { WriteUserAttributeToLogWithKey(key string) error // You can call this function to set custom trace span attribute WriteUserAttributeToTrace() error - // RequireRequestBody requests buffered delivery to ProcessRequestBody for the current request, - // including binary, encoded, and WebSocket upgrade requests. If the complete body is unavailable, - // the wrapper sends a 503 response and pauses the request. The response body path is unchanged. - RequireRequestBody() // If the onHttpRequestBody handle is not set, the request body will not be read by default DontReadRequestBody() // If the onHttpResponseBody handle is not set, the request body will not be read by default diff --git a/pkg/wrapper/plugin_wrapper.go b/pkg/wrapper/plugin_wrapper.go index 2882631..c8f2e12 100644 --- a/pkg/wrapper/plugin_wrapper.go +++ b/pkg/wrapper/plugin_wrapper.go @@ -40,7 +40,15 @@ import ( type Log log.Log type PluginContext iface.PluginContext -type HttpContext iface.HttpContext +type HttpContext interface { + iface.HttpContext + // RequireRequestBody requests exactly one buffered ProcessRequestBody call per request, + // including binary, encoded, WebSocket upgrade, and header-only requests. Header-only requests + // receive an empty body immediately after ProcessRequestHeaders. DontReadRequestBody does not + // cancel required delivery. If the complete body is unavailable or exceeds the configured buffer + // limit, the wrapper sends a 503 response and pauses the request without calling ProcessRequestBody. + RequireRequestBody() +} const ( CustomLogKey = "custom_log" @@ -762,24 +770,26 @@ func (ctx *CommonPluginCtx[PluginConfig]) NewHttpContext(contextID uint32) types type CommonHttpCtx[PluginConfig any] struct { types.DefaultHttpContext - plugin *CommonPluginCtx[PluginConfig] - config *PluginConfig - needRequestBody bool - needResponseBody bool - requireRequestBody bool - streamingRequestBody bool - streamingResponseBody bool - pauseStreamingResponse bool - requestBodySize int - responseBodySize int - contextID uint32 - userContext map[string]interface{} - userAttribute map[string]interface{} - bufferQueue [][]byte - responseCallback iface.RouteResponseCallback - executionPhase iface.HTTPExecutionPhase - requestHeaderEndOfStream bool - responseHeaderEndOfStream bool + plugin *CommonPluginCtx[PluginConfig] + config *PluginConfig + needRequestBody bool + needResponseBody bool + requireRequestBody bool + requestBodyCallbackInvoked bool + streamingRequestBody bool + streamingResponseBody bool + pauseStreamingResponse bool + requestBodySize int + requestBodyBufferLimit uint32 + responseBodySize int + contextID uint32 + userContext map[string]interface{} + userAttribute map[string]interface{} + bufferQueue [][]byte + responseCallback iface.RouteResponseCallback + executionPhase iface.HTTPExecutionPhase + requestHeaderEndOfStream bool + responseHeaderEndOfStream bool // Cached request pseudo-headers from the header phase scheme string host string @@ -972,6 +982,7 @@ func (ctx *CommonHttpCtx[PluginConfig]) DisableReroute() { func (ctx *CommonHttpCtx[PluginConfig]) SetRequestBodyBufferLimit(size uint32) { ctx.plugin.vm.log.Debugf("SetRequestBodyBufferLimit: %d", size) + ctx.requestBodyBufferLimit = size _ = proxywasm.SetProperty([]string{"set_decoder_buffer_limit"}, []byte(strconv.Itoa(int(size)))) } @@ -1091,7 +1102,13 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestHeaders(numHeaders int, end if ctx.plugin.vm.onHttpRequestHeaders == nil { return types.ActionContinue } - return ctx.plugin.vm.onHttpRequestHeaders(ctx, *config) + action := ctx.plugin.vm.onHttpRequestHeaders(ctx, *config) + if ctx.requireRequestBody && ctx.requestHeaderEndOfStream && + !ctx.requestBodyCallbackInvoked && ctx.plugin.vm.onHttpRequestBody != nil { + ctx.requestBodyCallbackInvoked = true + return ctx.plugin.vm.onHttpRequestBody(ctx, *config, nil) + } + return action } func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStream bool) types.Action { @@ -1100,10 +1117,17 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr if ctx.config == nil { return types.ActionContinue } - if !ctx.needRequestBody { - return types.ActionContinue - } if ctx.requireRequestBody && ctx.plugin.vm.onHttpRequestBody != nil { + if ctx.requestBodyCallbackInvoked { + return types.ActionContinue + } + if ctx.requestBodyBufferLimit > 0 && uint32(bodySize) > ctx.requestBodyBufferLimit { + ctx.plugin.vm.log.Warnf("required request body exceeds buffer limit: %d bytes, limit %d", bodySize, ctx.requestBodyBufferLimit) + if sendErr := proxywasm.SendHttpResponse(RequiredRequestBodyFailureStatusCode, nil, nil, -1); sendErr != nil { + ctx.plugin.vm.log.Errorf("send request body failure response failed: %v", sendErr) + } + return types.ActionPause + } if !endOfStream { return types.ActionPause } @@ -1115,8 +1139,12 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr } return types.ActionPause } + ctx.requestBodyCallbackInvoked = true return ctx.plugin.vm.onHttpRequestBody(ctx, *ctx.config, body) } + if !ctx.needRequestBody { + return types.ActionContinue + } if ctx.plugin.vm.onHttpStreamingRequestBody != nil && ctx.streamingRequestBody { chunk, _ := proxywasm.GetHttpRequestBody(0, bodySize) modifiedChunk := ctx.plugin.vm.onHttpStreamingRequestBody(ctx, *ctx.config, chunk, endOfStream) diff --git a/pkg/wrapper/plugin_wrapper_test.go b/pkg/wrapper/plugin_wrapper_test.go index bb91d11..da43665 100644 --- a/pkg/wrapper/plugin_wrapper_test.go +++ b/pkg/wrapper/plugin_wrapper_test.go @@ -30,7 +30,7 @@ type bodyDeliveryHarness struct { responseBodyCallCount int } -func newBodyDeliveryHarness(t *testing.T, requireBody bool) *bodyDeliveryHarness { +func newBodyDeliveryHarness(t *testing.T, requireBody bool, headerOptions ...func(HttpContext)) *bodyDeliveryHarness { t.Helper() h := &bodyDeliveryHarness{} vm := NewCommonVmCtx[struct{}]( @@ -39,6 +39,9 @@ func newBodyDeliveryHarness(t *testing.T, requireBody bool) *bodyDeliveryHarness if requireBody { ctx.RequireRequestBody() } + for _, option := range headerOptions { + option(ctx) + } return types.ActionContinue }), ProcessRequestBody(func(_ HttpContext, _ struct{}, body []byte) types.Action { @@ -60,9 +63,9 @@ func newBodyDeliveryHarness(t *testing.T, requireBody bool) *bodyDeliveryHarness return h } -func (h *bodyDeliveryHarness) callRequestHeaders(headers [][2]string) types.Action { +func (h *bodyDeliveryHarness) callRequestHeaders(headers [][2]string, endOfStream bool) types.Action { headers = append(headers, [2]string{":authority", "default.test.com"}) - return h.host.CallOnRequestHeaders(h.contextID, headers, false) + return h.host.CallOnRequestHeaders(h.contextID, headers, endOfStream) } func TestRequireRequestBodyRawDelivery(t *testing.T) { @@ -78,7 +81,7 @@ func TestRequireRequestBodyRawDelivery(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := newBodyDeliveryHarness(t, true) - require.Equal(t, types.ActionContinue, h.callRequestHeaders(tt.headers)) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(tt.headers, false)) require.Equal(t, types.ActionPause, h.host.CallOnRequestBody(h.contextID, payload[:3], false)) require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, payload[3:], true)) require.Equal(t, 1, h.requestBodyCalls) @@ -91,7 +94,7 @@ func TestRequireRequestBodyRawDelivery(t *testing.T) { func TestRequireRequestBodyWebSocketRequestOnly(t *testing.T) { h := newBodyDeliveryHarness(t, true) headers := [][2]string{{"connection", "upgrade"}, {"upgrade", "websocket"}} - require.Equal(t, types.ActionContinue, h.callRequestHeaders(headers)) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(headers, false)) payload := []byte{0x81, 0x02, 'h', 'i'} require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, payload, true)) require.Equal(t, payload, h.requestBody) @@ -102,10 +105,39 @@ func TestRequireRequestBodyWebSocketRequestOnly(t *testing.T) { require.Zero(t, h.responseBodyCallCount) } -func TestRequireRequestBodyBufferFailure(t *testing.T) { +func TestRequireRequestBodyHeaderEndOfStream(t *testing.T) { h := newBodyDeliveryHarness(t, true) - require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil)) - require.Equal(t, types.ActionPause, h.host.CallOnRequestBody(h.contextID, nil, true)) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil, true)) + require.Equal(t, 1, h.requestBodyCalls) + require.Empty(t, h.requestBody) + require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) + + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, []byte("unexpected"), true)) + require.Equal(t, 1, h.requestBodyCalls) + require.Empty(t, h.requestBody) +} + +func TestRequireRequestBodyOverridesDontReadRequestBody(t *testing.T) { + h := newBodyDeliveryHarness(t, true, func(ctx HttpContext) { + ctx.DontReadRequestBody() + }) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil, false)) + payload := []byte("required") + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, payload, true)) + require.Equal(t, 1, h.requestBodyCalls) + require.Equal(t, payload, h.requestBody) + require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) +} + +func TestRequireRequestBodyBufferLimitExceeded(t *testing.T) { + const bufferLimit = 4 + payload := []byte("larger than the buffer limit") + h := newBodyDeliveryHarness(t, true, func(ctx HttpContext) { + ctx.SetRequestBodyBufferLimit(bufferLimit) + }) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil, false)) + require.Equal(t, types.ActionPause, h.host.CallOnRequestBody(h.contextID, payload[:2], false)) + require.Equal(t, types.ActionPause, h.host.CallOnRequestBody(h.contextID, payload[2:], true)) require.Zero(t, h.requestBodyCalls) response := h.host.GetSentLocalResponse(h.contextID) require.NotNil(t, response) @@ -124,7 +156,7 @@ func TestRequestBodyLegacySkips(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := newBodyDeliveryHarness(t, false) - require.Equal(t, types.ActionContinue, h.callRequestHeaders(tt.headers)) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(tt.headers, false)) require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, []byte("skipped"), true)) require.Zero(t, h.requestBodyCalls) require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) @@ -133,7 +165,7 @@ func TestRequestBodyLegacySkips(t *testing.T) { t.Run("plain body remains delivered", func(t *testing.T) { h := newBodyDeliveryHarness(t, false) - require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil)) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil, false)) require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, []byte("plain"), true)) require.Equal(t, []byte("plain"), h.requestBody) require.Equal(t, 1, h.requestBodyCalls) From 84a22968a15a1ad8dc49d414a72d07f8a3993718 Mon Sep 17 00:00:00 2001 From: johnlanni Date: Sat, 31 Oct 2026 23:06:28 +0800 Subject: [PATCH 3/4] fix(wrapper): handle required body termination Signed-off-by: johnlanni --- pkg/wrapper/plugin_wrapper.go | 44 +++++++++++++++++++-------- pkg/wrapper/plugin_wrapper_test.go | 49 ++++++++++++++++++++++++++++-- 2 files changed, 78 insertions(+), 15 deletions(-) diff --git a/pkg/wrapper/plugin_wrapper.go b/pkg/wrapper/plugin_wrapper.go index c8f2e12..59b1c73 100644 --- a/pkg/wrapper/plugin_wrapper.go +++ b/pkg/wrapper/plugin_wrapper.go @@ -1103,14 +1103,33 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestHeaders(numHeaders int, end return types.ActionContinue } action := ctx.plugin.vm.onHttpRequestHeaders(ctx, *config) + if action == types.ActionPause { + return action + } if ctx.requireRequestBody && ctx.requestHeaderEndOfStream && !ctx.requestBodyCallbackInvoked && ctx.plugin.vm.onHttpRequestBody != nil { - ctx.requestBodyCallbackInvoked = true - return ctx.plugin.vm.onHttpRequestBody(ctx, *config, nil) + return ctx.deliverRequiredRequestBody(0) } return action } +func (ctx *CommonHttpCtx[PluginConfig]) deliverRequiredRequestBody(bodySize int) types.Action { + var body []byte + var err error + if bodySize > 0 { + body, err = proxywasm.GetHttpRequestBody(0, bodySize) + } + if err != nil || len(body) != bodySize { + ctx.plugin.vm.log.Warnf("get required request body failed: %v, expected %d bytes, got %d", err, bodySize, len(body)) + if sendErr := proxywasm.SendHttpResponse(RequiredRequestBodyFailureStatusCode, nil, nil, -1); sendErr != nil { + ctx.plugin.vm.log.Errorf("send request body failure response failed: %v", sendErr) + } + return types.ActionPause + } + ctx.requestBodyCallbackInvoked = true + return ctx.plugin.vm.onHttpRequestBody(ctx, *ctx.config, body) +} + func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStream bool) types.Action { defer recoverFunc() ctx.executionPhase = iface.DecodeData @@ -1128,19 +1147,11 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr } return types.ActionPause } + ctx.requestBodySize = bodySize if !endOfStream { return types.ActionPause } - body, err := proxywasm.GetHttpRequestBody(0, bodySize) - if err != nil || len(body) != bodySize { - ctx.plugin.vm.log.Warnf("get required request body failed: %v, expected %d bytes, got %d", err, bodySize, len(body)) - if sendErr := proxywasm.SendHttpResponse(RequiredRequestBodyFailureStatusCode, nil, nil, -1); sendErr != nil { - ctx.plugin.vm.log.Errorf("send request body failure response failed: %v", sendErr) - } - return types.ActionPause - } - ctx.requestBodyCallbackInvoked = true - return ctx.plugin.vm.onHttpRequestBody(ctx, *ctx.config, body) + return ctx.deliverRequiredRequestBody(bodySize) } if !ctx.needRequestBody { return types.ActionContinue @@ -1170,6 +1181,15 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr return types.ActionContinue } +func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestTrailers(numTrailers int) types.Action { + defer recoverFunc() + if ctx.config == nil || !ctx.requireRequestBody || ctx.requestBodyCallbackInvoked || + ctx.plugin.vm.onHttpRequestBody == nil { + return types.ActionContinue + } + return ctx.deliverRequiredRequestBody(ctx.requestBodySize) +} + func (ctx *CommonHttpCtx[PluginConfig]) OnHttpResponseHeaders(numHeaders int, endOfStream bool) types.Action { defer recoverFunc() ctx.executionPhase = iface.EncodeHeader diff --git a/pkg/wrapper/plugin_wrapper_test.go b/pkg/wrapper/plugin_wrapper_test.go index da43665..269e095 100644 --- a/pkg/wrapper/plugin_wrapper_test.go +++ b/pkg/wrapper/plugin_wrapper_test.go @@ -17,6 +17,7 @@ package wrapper import ( "testing" + "github.com/higress-group/proxy-wasm-go-sdk/proxywasm" "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/proxytest" "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/types" "github.com/stretchr/testify/require" @@ -27,12 +28,17 @@ type bodyDeliveryHarness struct { contextID uint32 requestBody []byte requestBodyCalls int + requestHeaderAction types.Action + requestBodyAction types.Action responseBodyCallCount int } func newBodyDeliveryHarness(t *testing.T, requireBody bool, headerOptions ...func(HttpContext)) *bodyDeliveryHarness { t.Helper() - h := &bodyDeliveryHarness{} + h := &bodyDeliveryHarness{ + requestHeaderAction: types.ActionContinue, + requestBodyAction: types.ActionContinue, + } vm := NewCommonVmCtx[struct{}]( "body-delivery-test", ProcessRequestHeaders(func(ctx HttpContext, _ struct{}) types.Action { @@ -42,12 +48,12 @@ func newBodyDeliveryHarness(t *testing.T, requireBody bool, headerOptions ...fun for _, option := range headerOptions { option(ctx) } - return types.ActionContinue + return h.requestHeaderAction }), ProcessRequestBody(func(_ HttpContext, _ struct{}, body []byte) types.Action { h.requestBodyCalls++ h.requestBody = append([]byte(nil), body...) - return types.ActionContinue + return h.requestBodyAction }), ProcessResponseBody(func(_ HttpContext, _ struct{}, _ []byte) types.Action { h.responseBodyCallCount++ @@ -117,6 +123,43 @@ func TestRequireRequestBodyHeaderEndOfStream(t *testing.T) { require.Empty(t, h.requestBody) } +func TestRequireRequestBodyHeaderPauseSkipsBodyDelivery(t *testing.T) { + h := newBodyDeliveryHarness(t, true, func(ctx HttpContext) { + require.NoError(t, proxywasm.SendHttpResponse(403, nil, nil, -1)) + }) + h.requestHeaderAction = types.ActionPause + require.Equal(t, types.ActionPause, h.callRequestHeaders(nil, true)) + require.Zero(t, h.requestBodyCalls) + response := h.host.GetSentLocalResponse(h.contextID) + require.NotNil(t, response) + require.Equal(t, uint32(403), response.StatusCode) +} + +func TestRequireRequestBodyEmptyTerminalBody(t *testing.T) { + h := newBodyDeliveryHarness(t, true) + require.Equal(t, types.ActionContinue, h.callRequestHeaders(nil, false)) + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, nil, true)) + require.Equal(t, 1, h.requestBodyCalls) + require.Empty(t, h.requestBody) + require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) +} + +func TestRequireRequestBodyTrailersDeliverBufferedBody(t *testing.T) { + h := newBodyDeliveryHarness(t, true) + payload := []byte{0, 0, 0, 0, 1, 'x'} + headers := [][2]string{{"content-type", "application/grpc"}} + require.Equal(t, types.ActionContinue, h.callRequestHeaders(headers, false)) + require.Equal(t, types.ActionPause, h.host.CallOnRequestBody(h.contextID, payload, false)) + require.Zero(t, h.requestBodyCalls) + require.Equal(t, types.ActionContinue, h.host.CallOnRequestTrailers(h.contextID, [][2]string{{"x-checksum", "abc"}})) + require.Equal(t, 1, h.requestBodyCalls) + require.Equal(t, payload, h.requestBody) + require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) + + require.Equal(t, types.ActionContinue, h.host.CallOnRequestTrailers(h.contextID, nil)) + require.Equal(t, 1, h.requestBodyCalls) +} + func TestRequireRequestBodyOverridesDontReadRequestBody(t *testing.T) { h := newBodyDeliveryHarness(t, true, func(ctx HttpContext) { ctx.DontReadRequestBody() From 759d75e755d1251e950cc66c7b1a67584bea4948 Mon Sep 17 00:00:00 2001 From: johnlanni Date: Sat, 31 Oct 2026 23:36:53 +0800 Subject: [PATCH 4/4] fix(wrapper): enforce required body delivery Fail invalid required-body opt-ins and preserve exactly-once empty-body delivery when request headers pause. Signed-off-by: johnlanni --- pkg/wrapper/plugin_wrapper.go | 41 ++++++++++++++----- pkg/wrapper/plugin_wrapper_test.go | 64 ++++++++++++++++++++++++++---- 2 files changed, 86 insertions(+), 19 deletions(-) diff --git a/pkg/wrapper/plugin_wrapper.go b/pkg/wrapper/plugin_wrapper.go index 59b1c73..a278585 100644 --- a/pkg/wrapper/plugin_wrapper.go +++ b/pkg/wrapper/plugin_wrapper.go @@ -44,9 +44,11 @@ type HttpContext interface { iface.HttpContext // RequireRequestBody requests exactly one buffered ProcessRequestBody call per request, // including binary, encoded, WebSocket upgrade, and header-only requests. Header-only requests - // receive an empty body immediately after ProcessRequestHeaders. DontReadRequestBody does not - // cancel required delivery. If the complete body is unavailable or exceeds the configured buffer - // limit, the wrapper sends a 503 response and pauses the request without calling ProcessRequestBody. + // receive an empty body immediately after ProcessRequestHeaders, even when that callback pauses; + // the header pause action is preserved. The plugin must register ProcessRequestBody. + // DontReadRequestBody does not cancel required delivery. If the complete body is unavailable or + // exceeds the configured buffer limit, the wrapper sends a 503 response and pauses the request + // without calling ProcessRequestBody. RequireRequestBody() } @@ -937,6 +939,12 @@ func (ctx *CommonHttpCtx[PluginConfig]) Method() string { func (ctx *CommonHttpCtx[PluginConfig]) RequireRequestBody() { ctx.requireRequestBody = true ctx.needRequestBody = true + if ctx.plugin.vm.onHttpRequestBody == nil { + ctx.plugin.vm.log.Errorf("RequireRequestBody requires ProcessRequestBody to be registered") + if err := proxywasm.SendHttpResponse(RequiredRequestBodyFailureStatusCode, nil, nil, -1); err != nil { + ctx.plugin.vm.log.Errorf("send request body failure response failed: %v", err) + } + } } func (ctx *CommonHttpCtx[PluginConfig]) DontReadRequestBody() { @@ -1103,12 +1111,15 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestHeaders(numHeaders int, end return types.ActionContinue } action := ctx.plugin.vm.onHttpRequestHeaders(ctx, *config) - if action == types.ActionPause { - return action + if ctx.requireRequestBody && ctx.plugin.vm.onHttpRequestBody == nil { + return types.ActionPause } - if ctx.requireRequestBody && ctx.requestHeaderEndOfStream && - !ctx.requestBodyCallbackInvoked && ctx.plugin.vm.onHttpRequestBody != nil { - return ctx.deliverRequiredRequestBody(0) + if ctx.requireRequestBody && ctx.requestHeaderEndOfStream && !ctx.requestBodyCallbackInvoked { + bodyAction := ctx.deliverRequiredRequestBody(0) + if action == types.ActionPause { + return action + } + return bodyAction } return action } @@ -1136,7 +1147,10 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr if ctx.config == nil { return types.ActionContinue } - if ctx.requireRequestBody && ctx.plugin.vm.onHttpRequestBody != nil { + if ctx.requireRequestBody { + if ctx.plugin.vm.onHttpRequestBody == nil { + return types.ActionPause + } if ctx.requestBodyCallbackInvoked { return types.ActionContinue } @@ -1159,6 +1173,9 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr if ctx.plugin.vm.onHttpStreamingRequestBody != nil && ctx.streamingRequestBody { chunk, _ := proxywasm.GetHttpRequestBody(0, bodySize) modifiedChunk := ctx.plugin.vm.onHttpStreamingRequestBody(ctx, *ctx.config, chunk, endOfStream) + if ctx.requireRequestBody && ctx.plugin.vm.onHttpRequestBody == nil { + return types.ActionPause + } err := proxywasm.ReplaceHttpRequestBody(modifiedChunk) if err != nil { ctx.plugin.vm.log.Warnf("replace request body chunk failed: %v", err) @@ -1183,10 +1200,12 @@ func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestBody(bodySize int, endOfStr func (ctx *CommonHttpCtx[PluginConfig]) OnHttpRequestTrailers(numTrailers int) types.Action { defer recoverFunc() - if ctx.config == nil || !ctx.requireRequestBody || ctx.requestBodyCallbackInvoked || - ctx.plugin.vm.onHttpRequestBody == nil { + if ctx.config == nil || !ctx.requireRequestBody || ctx.requestBodyCallbackInvoked { return types.ActionContinue } + if ctx.plugin.vm.onHttpRequestBody == nil { + return types.ActionPause + } return ctx.deliverRequiredRequestBody(ctx.requestBodySize) } diff --git a/pkg/wrapper/plugin_wrapper_test.go b/pkg/wrapper/plugin_wrapper_test.go index 269e095..50061a7 100644 --- a/pkg/wrapper/plugin_wrapper_test.go +++ b/pkg/wrapper/plugin_wrapper_test.go @@ -17,7 +17,6 @@ package wrapper import ( "testing" - "github.com/higress-group/proxy-wasm-go-sdk/proxywasm" "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/proxytest" "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/types" "github.com/stretchr/testify/require" @@ -123,16 +122,65 @@ func TestRequireRequestBodyHeaderEndOfStream(t *testing.T) { require.Empty(t, h.requestBody) } -func TestRequireRequestBodyHeaderPauseSkipsBodyDelivery(t *testing.T) { - h := newBodyDeliveryHarness(t, true, func(ctx HttpContext) { - require.NoError(t, proxywasm.SendHttpResponse(403, nil, nil, -1)) - }) +func TestRequireRequestBodyHeaderPauseDeliversBody(t *testing.T) { + h := newBodyDeliveryHarness(t, true) h.requestHeaderAction = types.ActionPause require.Equal(t, types.ActionPause, h.callRequestHeaders(nil, true)) - require.Zero(t, h.requestBodyCalls) - response := h.host.GetSentLocalResponse(h.contextID) + require.Equal(t, 1, h.requestBodyCalls) + require.Empty(t, h.requestBody) + require.Nil(t, h.host.GetSentLocalResponse(h.contextID)) + + require.Equal(t, types.ActionContinue, h.host.CallOnRequestBody(h.contextID, []byte("unexpected"), true)) + require.Equal(t, 1, h.requestBodyCalls) + require.Empty(t, h.requestBody) +} + +func TestRequireRequestBodyWithoutBufferedHandlerHeaderCallback(t *testing.T) { + vm := NewCommonVmCtx[struct{}]( + "required-body-without-buffered-handler", + ProcessRequestHeaders(func(ctx HttpContext, _ struct{}) types.Action { + ctx.RequireRequestBody() + return types.ActionContinue + }), + ) + host, reset := proxytest.NewHostEmulator(proxytest.NewEmulatorOption().WithVMContext(vm)) + t.Cleanup(reset) + host.RegisterForeignFunction("get_log_level", func([]byte) []byte { return make([]byte, 4) }) + require.Equal(t, types.OnPluginStartStatusOK, host.StartPlugin()) + contextID := host.InitializeHttpContext() + + headers := [][2]string{{":authority", "default.test.com"}} + require.Equal(t, types.ActionPause, host.CallOnRequestHeaders(contextID, headers, false)) + response := host.GetSentLocalResponse(contextID) + require.NotNil(t, response) + require.Equal(t, uint32(RequiredRequestBodyFailureStatusCode), response.StatusCode) + require.Equal(t, types.ActionPause, host.CallOnRequestBody(contextID, []byte("body"), true)) + require.Equal(t, types.ActionPause, host.CallOnRequestTrailers(contextID, nil)) +} + +func TestRequireRequestBodyWithoutBufferedHandlerStreamingCallback(t *testing.T) { + streamingCalls := 0 + vm := NewCommonVmCtx[struct{}]( + "required-body-with-streaming-handler", + ProcessStreamingRequestBody(func(ctx HttpContext, _ struct{}, chunk []byte, _ bool) []byte { + streamingCalls++ + ctx.RequireRequestBody() + return chunk + }), + ) + host, reset := proxytest.NewHostEmulator(proxytest.NewEmulatorOption().WithVMContext(vm)) + t.Cleanup(reset) + host.RegisterForeignFunction("get_log_level", func([]byte) []byte { return make([]byte, 4) }) + require.Equal(t, types.OnPluginStartStatusOK, host.StartPlugin()) + contextID := host.InitializeHttpContext() + + headers := [][2]string{{":authority", "default.test.com"}} + require.Equal(t, types.ActionContinue, host.CallOnRequestHeaders(contextID, headers, false)) + require.Equal(t, types.ActionPause, host.CallOnRequestBody(contextID, []byte("body"), true)) + require.Equal(t, 1, streamingCalls) + response := host.GetSentLocalResponse(contextID) require.NotNil(t, response) - require.Equal(t, uint32(403), response.StatusCode) + require.Equal(t, uint32(RequiredRequestBodyFailureStatusCode), response.StatusCode) } func TestRequireRequestBodyEmptyTerminalBody(t *testing.T) {