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 @@ -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;
Expand Down Expand Up @@ -126,6 +127,60 @@ 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>
/// 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.
/// </summary>
internal const int ResponseEnvelopeHeadroom = 16 * 1024;

/// <summary>
/// The largest body, measured as it is written into the serialized response, that still fits
/// in the Lambda response payload together with <see cref="ResponseEnvelopeHeadroom"/>.
/// </summary>
internal const int MaxResponseBodySize = MaxResponsePayloadSize - ResponseEnvelopeHeadroom;

/// <summary>
/// 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 <see cref="ResponseEnvelopeHeadroom"/> is kept for the rest of the response.
/// </summary>
internal static bool IsResponseBodyTooLarge(string body, bool isBase64Encoded)
{
if (body == null)
{
return false;
}

// 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;
}

/// <summary>
/// The number of UTF-8 bytes the string takes inside a JSON string value, escaped with
/// <see cref="JavaScriptEncoder.UnsafeRelaxedJsonEscaping"/> like the Lambda JSON serializers do.
/// </summary>
internal static int GetJsonEncodedSize(string value)
{
return Encoding.UTF8.GetByteCount(JavaScriptEncoder.UnsafeRelaxedJsonEscaping.Encode(value));
}

/// <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,87 @@ public void TestHttpApiV2QueryStringEncoding(string starting, string expected)
Assert.Equal(expected, encoded);
}

[Theory]
[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.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<string, string> { { "Content-Type", "text/plain; charset=utf-8" } },
MultiValueHeaders = new Dictionary<string, IList<string>> { { "Content-Type", new List<string> { "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]
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");
}
}
}