Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .autover/changes/865140eb-dc31-4391-a433-73444862d7a9.json
Original file line number Diff line number Diff line change
@@ -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."
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,25 @@ internal static (string body, bool isBase64Encoded) ConvertAspNetCoreBodyToLambd
}
}

/// <summary>
/// The maximum size in bytes of a buffered (non-streaming) Lambda response payload.
/// </summary>
internal const int MaxResponsePayloadSize = 6 * 1024 * 1024;

/// <summary>
/// Checks if the Lambda response body is larger than Lambda allows for a buffered response.
/// </summary>
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;
}

/// <summary>
/// Add a '?' to the start of a non-empty query string, otherwise return null.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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");
}
}
}