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] 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"); + } + } +}