From a20a1788a21820390371ba8021979bab5bc68bea Mon Sep 17 00:00:00 2001 From: Yusuf Burak PEKER <25burak25@gmail.com> Date: Sat, 21 Nov 2026 21:10:37 +0300 Subject: [PATCH 1/2] Return 413 when the ASP.NET Core response exceeds the Lambda payload limit --- .../865140eb-dc31-4391-a433-73444862d7a9.json | 11 +++++ .../APIGatewayHttpApiV2ProxyFunction.cs | 9 ++++ .../APIGatewayProxyFunction.cs | 10 +++++ .../Internal/Utilities.cs | 19 +++++++++ .../TestApiGatewayHttpApiV2Calls.cs | 9 ++++ .../TestCallingWebAPI.cs | 9 ++++ .../UtilitiesTest.cs | 24 +++++++++++ .../large-response-apigateway-request.json | 34 +++++++++++++++ .../large-response-httpapi-v2-request.json | 41 +++++++++++++++++++ .../Controllers/LargeResponseController.cs | 15 +++++++ 10 files changed, 181 insertions(+) create mode 100644 .autover/changes/865140eb-dc31-4391-a433-73444862d7a9.json create mode 100644 Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-apigateway-request.json create mode 100644 Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-httpapi-v2-request.json create mode 100644 Libraries/test/TestWebApp/Controllers/LargeResponseController.cs diff --git a/.autover/changes/865140eb-dc31-4391-a433-73444862d7a9.json b/.autover/changes/865140eb-dc31-4391-a433-73444862d7a9.json new file mode 100644 index 000000000..09c11cd6c --- /dev/null +++ b/.autover/changes/865140eb-dc31-4391-a433-73444862d7a9.json @@ -0,0 +1,11 @@ +{ + "Projects": [ + { + "Name": "Amazon.Lambda.AspNetCoreServer", + "Type": "Patch", + "ChangelogMessages": [ + "Return a 413 status code when the response body exceeds the Lambda response payload limit for API Gateway REST and HTTP API functions instead of failing the invocation." + ] + } + ] +} diff --git a/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayHttpApiV2ProxyFunction.cs b/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayHttpApiV2ProxyFunction.cs index da759ace9..37c4d0fdf 100644 --- a/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayHttpApiV2ProxyFunction.cs +++ b/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayHttpApiV2ProxyFunction.cs @@ -329,6 +329,15 @@ protected override APIGatewayHttpApiV2ProxyResponse MarshallResponse(IHttpRespon } #pragma warning restore CS0618 + if (Utilities.IsResponseBodyTooLarge(response.Body, response.IsBase64Encoded)) + { + _logger.LogError($"Response body exceeds the Lambda response payload limit of {Utilities.MaxResponsePayloadSize} bytes, returning status code 413"); + response = new APIGatewayHttpApiV2ProxyResponse + { + StatusCode = (int)HttpStatusCode.RequestEntityTooLarge + }; + } + PostMarshallResponseFeature(responseFeatures, response, lambdaContext); _logger.LogDebug($"Response Base 64 Encoded: {response.IsBase64Encoded}"); diff --git a/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayProxyFunction.cs b/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayProxyFunction.cs index 28ffcee00..988fb110b 100644 --- a/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayProxyFunction.cs +++ b/Libraries/src/Amazon.Lambda.AspNetCoreServer/APIGatewayProxyFunction.cs @@ -369,6 +369,16 @@ protected override APIGatewayProxyResponse MarshallResponse(IHttpResponseFeature } #pragma warning restore CS0618 + + if (Utilities.IsResponseBodyTooLarge(response.Body, response.IsBase64Encoded)) + { + _logger.LogError($"Response body exceeds the Lambda response payload limit of {Utilities.MaxResponsePayloadSize} bytes, returning status code 413"); + response = new APIGatewayProxyResponse + { + StatusCode = (int)HttpStatusCode.RequestEntityTooLarge + }; + } + PostMarshallResponseFeature(responseFeatures, response, lambdaContext); _logger.LogDebug($"Response Base 64 Encoded: {response.IsBase64Encoded}"); diff --git a/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs b/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs index 5aee012c7..4f2680d98 100644 --- a/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs +++ b/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs @@ -126,6 +126,25 @@ internal static (string body, bool isBase64Encoded) ConvertAspNetCoreBodyToLambd } } + /// + /// The maximum size in bytes of a buffered (non-streaming) Lambda response payload. + /// + internal const int MaxResponsePayloadSize = 6 * 1024 * 1024; + + /// + /// Checks if the Lambda response body is larger than Lambda allows for a buffered response. + /// + internal static bool IsResponseBodyTooLarge(string body, bool isBase64Encoded) + { + if (body == null) + { + return false; + } + + var size = isBase64Encoded ? body.Length : Encoding.UTF8.GetByteCount(body); + return size > MaxResponsePayloadSize; + } + /// /// Add a '?' to the start of a non-empty query string, otherwise return null. /// diff --git a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestApiGatewayHttpApiV2Calls.cs b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestApiGatewayHttpApiV2Calls.cs index 3810b1e49..ca68a4d4f 100644 --- a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestApiGatewayHttpApiV2Calls.cs +++ b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestApiGatewayHttpApiV2Calls.cs @@ -62,6 +62,15 @@ public async Task TestGetBinaryContent() Assert.Equal(binExpected, binActual); } + [Fact] + public async Task TestResponseTooLargeReturns413() + { + var response = await InvokeAPIGatewayRequest("large-response-httpapi-v2-request.json"); + + Assert.Equal((int)HttpStatusCode.RequestEntityTooLarge, response.StatusCode); + Assert.Null(response.Body); + } + [Fact] public async Task TestEncodePlusInResourcePath() { diff --git a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestCallingWebAPI.cs b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestCallingWebAPI.cs index 497ed6d33..ff8c9f4d1 100644 --- a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestCallingWebAPI.cs +++ b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/TestCallingWebAPI.cs @@ -252,6 +252,15 @@ public async Task TestGetBinaryContent() Assert.Equal(binExpected, binActual); } + [Fact] + public async Task TestResponseTooLargeReturns413() + { + var response = await InvokeAPIGatewayRequest("large-response-apigateway-request.json"); + + Assert.Equal((int)HttpStatusCode.RequestEntityTooLarge, response.StatusCode); + Assert.Null(response.Body); + } + [Fact] public async Task TestEncodePlusInResourcePath() { diff --git a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs index f05c0f156..8e9626f54 100644 --- a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs +++ b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs @@ -22,6 +22,30 @@ public void TestHttpApiV2QueryStringEncoding(string starting, string expected) Assert.Equal(expected, encoded); } + [Theory] + [InlineData(Utilities.MaxResponsePayloadSize, false, false)] + [InlineData(Utilities.MaxResponsePayloadSize + 1, false, true)] + [InlineData(Utilities.MaxResponsePayloadSize, true, false)] + [InlineData(Utilities.MaxResponsePayloadSize + 1, true, true)] + public void TestIsResponseBodyTooLarge(int size, bool isBase64Encoded, bool expected) + { + Assert.Equal(expected, Utilities.IsResponseBodyTooLarge(new string('a', size), isBase64Encoded)); + } + + [Fact] + public void TestIsResponseBodyTooLargeCountsUtf8Bytes() + { + // Each character is 2 bytes in UTF-8, so this body is over the limit even though it has fewer characters. + var body = new string('é',Utilities.MaxResponsePayloadSize / 2 + 1); + Assert.True(Utilities.IsResponseBodyTooLarge(body, false)); + } + + [Fact] + public void TestIsResponseBodyTooLargeNullBody() + { + Assert.False(Utilities.IsResponseBodyTooLarge(null, false)); + } + // This test is ensure middleware will the status code at 200. [Fact] public void EnsureStatusCodeStartsAtIs200() diff --git a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-apigateway-request.json b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-apigateway-request.json new file mode 100644 index 000000000..1a20e0612 --- /dev/null +++ b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-apigateway-request.json @@ -0,0 +1,34 @@ +{ + "resource": "/{proxy+}", + "path": "/api/largeresponse", + "httpMethod": "GET", + "headers": null, + "queryStringParameters": null, + "pathParameters": { + "proxy": "api/largeresponse" + }, + "stageVariables": null, + "requestContext": { + "accountId": "AAAAAAAAAAAA", + "resourceId": "5agfss", + "stage": "test-invoke-stage", + "requestId": "test-invoke-request", + "identity": { + "cognitoIdentityPoolId": null, + "accountId": "AAAAAAAAAAAA", + "cognitoIdentityId": null, + "caller": "BBBBBBBBBBBB", + "apiKey": "test-invoke-api-key", + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": "arn:aws:iam::AAAAAAAAAAAA:root", + "userAgent": "Apache-HttpClient/4.5.x (Java/1.8.0_102)", + "user": "AAAAAAAAAAAA" + }, + "resourcePath": "/{proxy+}", + "httpMethod": "GET", + "apiId": "t2yh6sjnmk" + }, + "body": null +} \ No newline at end of file diff --git a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-httpapi-v2-request.json b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-httpapi-v2-request.json new file mode 100644 index 000000000..5f1e5c614 --- /dev/null +++ b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/large-response-httpapi-v2-request.json @@ -0,0 +1,41 @@ +{ + "version": "2.0", + "routeKey": "ANY /{proxy+}", + "rawPath": "/api/largeresponse", + "rawQueryString": "", + "headers": { + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "cache-control": "no-cache", + "content-length": "0", + "host": "uo9pe23ec6.execute-api.us-east-1.amazonaws.com", + "postman-token": "cf1272a5-6626-4957-badc-c8c93726578a", + "user-agent": "PostmanRuntime/7.20.1", + "x-amzn-trace-id": "Root=1-5e7a98e3-da5ec4c6555f976320f6ab34", + "x-forwarded-for": "192.182.149.40", + "x-forwarded-port": "443", + "x-forwarded-proto": "https" + }, + "requestContext": { + "accountId": "626492997873", + "apiId": "uo9pe23ec6", + "domainName": "uo9pe23ec6.execute-api.us-east-1.amazonaws.com", + "domainPrefix": "uo9pe23ec6", + "http": { + "method": "GET", + "path": "/api/largeresponse", + "protocol": "HTTP/1.1", + "sourceIp": "192.182.149.40", + "userAgent": "PostmanRuntime/7.20.1" + }, + "requestId": "J6zTog-0oAMEJCQ=", + "routeKey": "ANY /{proxy+}", + "stage": "$default", + "time": "24/Mar/2020:23:33:55 +0000", + "timeEpoch": 1585092835963 + }, + "pathParameters": { + "proxy": "api/largeresponse" + }, + "isBase64Encoded": false +} \ No newline at end of file diff --git a/Libraries/test/TestWebApp/Controllers/LargeResponseController.cs b/Libraries/test/TestWebApp/Controllers/LargeResponseController.cs new file mode 100644 index 000000000..f36ef68c0 --- /dev/null +++ b/Libraries/test/TestWebApp/Controllers/LargeResponseController.cs @@ -0,0 +1,15 @@ +using Microsoft.AspNetCore.Mvc; + +namespace TestWebApp.Controllers +{ + [Route("api/largeresponse")] + public class LargeResponseController : Controller + { + [HttpGet] + public IActionResult Get() + { + // Larger than the 6 MB Lambda response payload limit. + return Content(new string('*', 7 * 1024 * 1024), "text/plain"); + } + } +} From add45e77e3ca3f95568d6f74897fe6ecf28c3e82 Mon Sep 17 00:00:00 2001 From: Yusuf Burak PEKER <25burak25@gmail.com> Date: Wed, 25 Nov 2026 08:19:58 +0300 Subject: [PATCH 2/2] Measure the JSON-escaped response body and keep headroom for the rest of the response --- .../Internal/Utilities.cs | 40 ++++++++++- .../UtilitiesTest.cs | 67 +++++++++++++++++-- 2 files changed, 100 insertions(+), 7 deletions(-) diff --git a/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs b/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs index 4f2680d98..d5c7b11a6 100644 --- a/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs +++ b/Libraries/src/Amazon.Lambda.AspNetCoreServer/Internal/Utilities.cs @@ -11,6 +11,7 @@ using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Text.Encodings.Web; using System.Threading; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; @@ -131,8 +132,22 @@ internal static (string body, bool isBase64Encoded) ConvertAspNetCoreBodyToLambd /// internal const int MaxResponsePayloadSize = 6 * 1024 * 1024; + /// + /// Bytes of the payload kept for the rest of the serialized response: the status code, + /// headers, cookies and the JSON property names around the body. + /// + internal const int ResponseEnvelopeHeadroom = 16 * 1024; + + /// + /// The largest body, measured as it is written into the serialized response, that still fits + /// in the Lambda response payload together with . + /// + internal const int MaxResponseBodySize = MaxResponsePayloadSize - ResponseEnvelopeHeadroom; + /// /// Checks if the Lambda response body is larger than Lambda allows for a buffered response. + /// The body is measured as a JSON string, escaped the way the Lambda JSON serializer writes it, + /// and a fixed is kept for the rest of the response. /// internal static bool IsResponseBodyTooLarge(string body, bool isBase64Encoded) { @@ -141,8 +156,29 @@ internal static bool IsResponseBodyTooLarge(string body, bool isBase64Encoded) return false; } - var size = isBase64Encoded ? body.Length : Encoding.UTF8.GetByteCount(body); - return size > MaxResponsePayloadSize; + // Escaping never makes the body smaller, so the raw size is a lower bound. + if (Encoding.UTF8.GetByteCount(body) > MaxResponseBodySize) + { + return true; + } + + // An escaped character takes at most 6 bytes ("\uXXXX"), so a body this short fits + // without measuring the escaped form. + if ((long)body.Length * 6 <= MaxResponseBodySize) + { + return false; + } + + return GetJsonEncodedSize(body) > MaxResponseBodySize; + } + + /// + /// The number of UTF-8 bytes the string takes inside a JSON string value, escaped with + /// like the Lambda JSON serializers do. + /// + internal static int GetJsonEncodedSize(string value) + { + return Encoding.UTF8.GetByteCount(JavaScriptEncoder.UnsafeRelaxedJsonEscaping.Encode(value)); } /// diff --git a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs index 8e9626f54..6387232df 100644 --- a/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs +++ b/Libraries/test/Amazon.Lambda.AspNetCoreServer.Test/UtilitiesTest.cs @@ -23,21 +23,78 @@ public void TestHttpApiV2QueryStringEncoding(string starting, string expected) } [Theory] - [InlineData(Utilities.MaxResponsePayloadSize, false, false)] - [InlineData(Utilities.MaxResponsePayloadSize + 1, false, true)] - [InlineData(Utilities.MaxResponsePayloadSize, true, false)] - [InlineData(Utilities.MaxResponsePayloadSize + 1, true, true)] + [InlineData(Utilities.MaxResponseBodySize, false, false)] + [InlineData(Utilities.MaxResponseBodySize + 1, false, true)] + [InlineData(Utilities.MaxResponseBodySize, true, false)] + [InlineData(Utilities.MaxResponseBodySize + 1, true, true)] public void TestIsResponseBodyTooLarge(int size, bool isBase64Encoded, bool expected) { Assert.Equal(expected, Utilities.IsResponseBodyTooLarge(new string('a', size), isBase64Encoded)); } + [Fact] + public void TestIsResponseBodyTooLargeKeepsHeadroomBelowPayloadLimit() + { + Assert.True(Utilities.MaxResponseBodySize < Utilities.MaxResponsePayloadSize); + Assert.True(Utilities.IsResponseBodyTooLarge(new string('a', Utilities.MaxResponsePayloadSize), false)); + } + [Fact] public void TestIsResponseBodyTooLargeCountsUtf8Bytes() { // Each character is 2 bytes in UTF-8, so this body is over the limit even though it has fewer characters. - var body = new string('é',Utilities.MaxResponsePayloadSize / 2 + 1); + var body = new string('é', Utilities.MaxResponseBodySize / 2 + 1); + Assert.True(Utilities.IsResponseBodyTooLarge(body, false)); + } + + [Theory] + [InlineData('"')] + [InlineData('\\')] + [InlineData('\n')] + public void TestIsResponseBodyTooLargeCountsJsonEscaping(char escaped) + { + // Each character is written as two bytes in the serialized response ("\"", "\\", "\n"), + // so this body is over the limit although its raw size is about half of it. + var body = new string(escaped, Utilities.MaxResponseBodySize / 2 + 1); Assert.True(Utilities.IsResponseBodyTooLarge(body, false)); + Assert.False(Utilities.IsResponseBodyTooLarge(new string(escaped, Utilities.MaxResponseBodySize / 2), false)); + } + + [Fact] + public void TestIsResponseBodyTooLargeCountsUnicodeEscapes() + { + // Control characters without a short escape are written as "\u0001" (6 bytes). + var body = new string('\u0001', Utilities.MaxResponseBodySize / 6 + 1); + Assert.True(Utilities.IsResponseBodyTooLarge(body, false)); + Assert.False(Utilities.IsResponseBodyTooLarge(new string('\u0001', Utilities.MaxResponseBodySize / 6), false)); + } + + [Fact] + public void TestLargestAllowedBodyFitsInSerializedResponse() + { + // The largest body that passes the check, mixed with characters that need escaping, + // still fits in the payload limit once the whole response is serialized. + var pattern = "a\"\\\né<\u0001"; + var builder = new StringBuilder(); + var count = Utilities.MaxResponseBodySize / Utilities.GetJsonEncodedSize(pattern); + for (var i = 0; i < count; i++) + { + builder.Append(pattern); + } + var body = builder.ToString(); + Assert.True(Utilities.GetJsonEncodedSize(body) > Utilities.MaxResponseBodySize - Utilities.GetJsonEncodedSize(pattern)); + Assert.False(Utilities.IsResponseBodyTooLarge(body, false)); + + var response = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse + { + StatusCode = 200, + Body = body, + Headers = new Dictionary { { "Content-Type", "text/plain; charset=utf-8" } }, + MultiValueHeaders = new Dictionary> { { "Content-Type", new List { "text/plain; charset=utf-8" } } } + }; + using var stream = new System.IO.MemoryStream(); + new Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer().Serialize(response, stream); + Assert.True(stream.Length <= Utilities.MaxResponsePayloadSize, $"Serialized response is {stream.Length} bytes"); } [Fact]