-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathAPIGatewayProxyFunction.cs
More file actions
372 lines (309 loc) · 16.7 KB
/
APIGatewayProxyFunction.cs
File metadata and controls
372 lines (309 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.AspNetCoreServer.Internal;
using Microsoft.AspNetCore.Http.Features.Authentication;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
namespace Amazon.Lambda.AspNetCoreServer
{
/// <summary>
/// APIGatewayProxyFunction is the base class for Lambda functions hosting the ASP.NET Core framework and exposed to the web via API Gateway.
///
/// The derived class implements the Init method similar to Main function in the ASP.NET Core. The function handler for the Lambda function will point
/// to this base class FunctionHandlerAsync method.
/// </summary>
public abstract class APIGatewayProxyFunction : AbstractAspNetCoreFunction<APIGatewayProxyRequest, APIGatewayProxyResponse>
{
/// <summary>
/// Key to access the ILambdaContext object from the HttpContext.Items collection.
/// </summary>
[Obsolete("References should be updated to Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction.LAMBDA_CONTEXT")]
public new const string LAMBDA_CONTEXT = AbstractAspNetCoreFunction.LAMBDA_CONTEXT;
/// <summary>
/// Key to access the APIGatewayProxyRequest object from the HttpContext.Items collection.
/// </summary>
[Obsolete("References should be updated to Amazon.Lambda.AspNetCoreServer.AbstractAspNetCoreFunction.LAMBDA_REQUEST_OBJECT")]
public const string APIGATEWAY_REQUEST = AbstractAspNetCoreFunction.LAMBDA_REQUEST_OBJECT;
/// <summary>
/// The modes for when the ASP.NET Core framework will be initialized.
/// </summary>
[Obsolete("References should be updated to Amazon.Lambda.AspNetCoreServer.StartupMode")]
public enum AspNetCoreStartupMode
{
/// <summary>
/// Initialize during the construction of APIGatewayProxyFunction
/// </summary>
Constructor = StartupMode.Constructor,
/// <summary>
/// Initialize during the first incoming request
/// </summary>
FirstRequest = StartupMode.FirstRequest
}
/// <summary>
/// Default Constructor. The ASP.NET Core Framework will be initialized as part of the construction.
/// </summary>
protected APIGatewayProxyFunction()
: base()
{
}
/// <summary>
///
/// </summary>
/// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param>
[Obsolete("Calls to the constructor should be replaced with the constructor that takes a Amazon.Lambda.AspNetCoreServer.StartupMode as the parameter.")]
protected APIGatewayProxyFunction(AspNetCoreStartupMode startupMode)
: base((StartupMode)startupMode)
{
}
/// <summary>
///
/// </summary>
/// <param name="startupMode">Configure when the ASP.NET Core framework will be initialized</param>
protected APIGatewayProxyFunction(StartupMode startupMode)
: base(startupMode)
{
}
/// <summary>
/// Constructor used by Amazon.Lambda.AspNetCoreServer.Hosting to support ASP.NET Core projects using the Minimal API style.
/// </summary>
/// <param name="hostedServices"></param>
protected APIGatewayProxyFunction(IServiceProvider hostedServices)
: base(hostedServices)
{
_hostServices = hostedServices;
}
private protected override void InternalCustomResponseExceptionHandling(APIGatewayProxyResponse apiGatewayResponse, ILambdaContext lambdaContext, Exception ex)
{
apiGatewayResponse.MultiValueHeaders["ErrorType"] = new List<string> { ex.GetType().Name };
}
/// <summary>
/// Convert the JSON document received from API Gateway into the InvokeFeatures object.
/// InvokeFeatures is then passed into IHttpApplication to create the ASP.NET Core request objects.
/// </summary>
/// <param name="features"></param>
/// <param name="apiGatewayRequest"></param>
/// <param name="lambdaContext"></param>
protected override void MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext)
{
{
var authFeatures = (IHttpAuthenticationFeature)features;
var authorizer = apiGatewayRequest?.RequestContext?.Authorizer;
if (authorizer != null)
{
// handling claims output from cognito user pool authorizer
if (authorizer.Claims != null && authorizer.Claims.Count != 0)
{
var identity = new ClaimsIdentity(authorizer.Claims.Select(
entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity");
_logger.LogDebug(
$"Configuring HttpContext.User with {authorizer.Claims.Count} claims coming from API Gateway's Request Context");
authFeatures.User = new ClaimsPrincipal(identity);
}
else
{
// handling claims output from custom lambda authorizer
var identity = new ClaimsIdentity(
authorizer.Where(x => x.Value != null && !string.Equals(x.Key, "claims", StringComparison.OrdinalIgnoreCase))
.Select(entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity");
_logger.LogDebug(
$"Configuring HttpContext.User with {authorizer.Count} claims coming from API Gateway's Request Context");
authFeatures.User = new ClaimsPrincipal(identity);
}
}
// Call consumers customize method in case they want to change how API Gateway's request
// was marshalled into ASP.NET Core request.
PostMarshallHttpAuthenticationFeature(authFeatures, apiGatewayRequest, lambdaContext);
}
{
var requestFeatures = (IHttpRequestFeature)features;
requestFeatures.Scheme = "https";
requestFeatures.Method = this.ParseHttpMethod(apiGatewayRequest);
string path = this.ParseHttpPath(apiGatewayRequest);
var rawQueryString = Utilities.CreateQueryStringParameters(
apiGatewayRequest.QueryStringParameters, apiGatewayRequest.MultiValueQueryStringParameters, true);
requestFeatures.RawTarget = apiGatewayRequest.Path + rawQueryString;
requestFeatures.QueryString = rawQueryString;
requestFeatures.Path = path;
requestFeatures.PathBase = string.Empty;
if (!string.IsNullOrEmpty(apiGatewayRequest?.RequestContext?.Path))
{
// This is to cover the case where the request coming in is https://myapigatewayid.execute-api.us-west-2.amazonaws.com/Prod where
// Prod is the stage name and there is no ending '/'. Path will be set to '/' so to make sure we detect the correct base path
// append '/' on the end to make the later EndsWith and substring work correctly.
var requestContextPath = apiGatewayRequest.RequestContext.Path;
if (path.EndsWith("/") && !requestContextPath.EndsWith("/"))
{
requestContextPath += "/";
}
else if (!path.EndsWith("/") && requestContextPath.EndsWith("/"))
{
// Handle a trailing slash in the request path: e.g. https://myapigatewayid.execute-api.us-west-2.amazonaws.com/Prod/foo/
requestFeatures.Path = path += "/";
}
if (requestContextPath.EndsWith(path))
{
requestFeatures.PathBase = requestContextPath.Substring(0,
requestContextPath.Length - requestFeatures.Path.Length);
}
}
requestFeatures.Path = Utilities.DecodeResourcePath(requestFeatures.Path);
Utilities.SetHeadersCollection(requestFeatures.Headers, apiGatewayRequest.Headers, apiGatewayRequest.MultiValueHeaders);
requestFeatures.Headers = this.AddMissingRequestHeaders(apiGatewayRequest, requestFeatures.Headers);
if (!string.IsNullOrEmpty(apiGatewayRequest.Body))
{
requestFeatures.Body = Utilities.ConvertLambdaRequestBodyToAspNetCoreBody(apiGatewayRequest.Body, apiGatewayRequest.IsBase64Encoded);
}
// Make sure the content-length header is set if header was not present.
const string contentLengthHeaderName = "Content-Length";
if (!requestFeatures.Headers.ContainsKey(contentLengthHeaderName))
{
requestFeatures.Headers[contentLengthHeaderName] = requestFeatures.Body == null ? "0" : requestFeatures.Body.Length.ToString(CultureInfo.InvariantCulture);
}
// Call consumers customize method in case they want to change how API Gateway's request
// was marshalled into ASP.NET Core request.
PostMarshallRequestFeature(requestFeatures, apiGatewayRequest, lambdaContext);
}
{
// set up connection features
var connectionFeatures = (IHttpConnectionFeature)features;
if (!string.IsNullOrEmpty(apiGatewayRequest?.RequestContext?.Identity?.SourceIp) &&
IPAddress.TryParse(apiGatewayRequest.RequestContext.Identity.SourceIp, out var remoteIpAddress))
{
connectionFeatures.RemoteIpAddress = remoteIpAddress;
}
if (apiGatewayRequest?.Headers?.TryGetValue("X-Forwarded-Port", out var forwardedPort) == true)
{
connectionFeatures.RemotePort = int.Parse(forwardedPort, CultureInfo.InvariantCulture);
}
connectionFeatures.ConnectionId = apiGatewayRequest.RequestContext?.ConnectionId;
// Call consumers customize method in case they want to change how API Gateway's request
// was marshalled into ASP.NET Core request.
PostMarshallConnectionFeature(connectionFeatures, apiGatewayRequest, lambdaContext);
}
{
var tlsConnectionFeature = (ITlsConnectionFeature)features;
var clientCertPem = apiGatewayRequest?.RequestContext?.Identity?.ClientCert?.ClientCertPem;
if (clientCertPem != null)
{
tlsConnectionFeature.ClientCertificate = Utilities.GetX509Certificate2FromPem(clientCertPem);
}
PostMarshallTlsConnectionFeature(tlsConnectionFeature, apiGatewayRequest, lambdaContext);
}
}
/// <summary>
/// Convert the response coming from ASP.NET Core into APIGatewayProxyResponse which is
/// serialized into the JSON object that API Gateway expects.
/// </summary>
/// <param name="responseFeatures"></param>
/// <param name="statusCodeIfNotSet">Sometimes the ASP.NET server doesn't set the status code correctly when successful, so this parameter will be used when the value is 0.</param>
/// <param name="lambdaContext"></param>
/// <returns><see cref="APIGatewayProxyResponse"/></returns>
protected override APIGatewayProxyResponse MarshallResponse(IHttpResponseFeature responseFeatures, ILambdaContext lambdaContext, int statusCodeIfNotSet = 200)
{
var response = new APIGatewayProxyResponse
{
StatusCode = responseFeatures.StatusCode != 0 ? responseFeatures.StatusCode : statusCodeIfNotSet
};
string contentType = null;
string contentEncoding = null;
if (responseFeatures.Headers != null)
{
response.MultiValueHeaders = new Dictionary<string, IList<string>>();
response.Headers = new Dictionary<string, string>();
foreach (var kvp in responseFeatures.Headers)
{
response.MultiValueHeaders[kvp.Key] = kvp.Value.ToList();
// Remember the Content-Type for possible later use
if (kvp.Key.Equals("Content-Type", StringComparison.CurrentCultureIgnoreCase) && response.MultiValueHeaders[kvp.Key].Count > 0)
{
contentType = response.MultiValueHeaders[kvp.Key][0];
}
else if (kvp.Key.Equals("Content-Encoding", StringComparison.CurrentCultureIgnoreCase) && response.MultiValueHeaders[kvp.Key].Count > 0)
{
contentEncoding = response.MultiValueHeaders[kvp.Key][0];
}
}
}
if (contentType == null)
{
response.MultiValueHeaders["Content-Type"] = new List<string>() { null };
}
if (responseFeatures.Body != null)
{
// Figure out how we should treat the response content, check encoding first to see if body is compressed, then check content type
var rcEncoding = GetResponseContentEncodingForContentEncoding(contentEncoding);
if (rcEncoding != ResponseContentEncoding.Base64)
{
rcEncoding = GetResponseContentEncodingForContentType(contentType);
}
(response.Body, response.IsBase64Encoded) = Utilities.ConvertAspNetCoreBodyToLambdaBody(responseFeatures.Body, rcEncoding);
}
PostMarshallResponseFeature(responseFeatures, response, lambdaContext);
_logger.LogDebug($"Response Base 64 Encoded: {response.IsBase64Encoded}");
return response;
}
/// <summary>
/// Get the http path from the request.
/// </summary>
/// <param name="apiGatewayRequest"></param>
/// <returns>string</returns>
protected virtual string ParseHttpPath(APIGatewayProxyRequest apiGatewayRequest)
{
string path = null;
// Replaces {proxy+} in path, if exists
if (apiGatewayRequest.PathParameters != null && apiGatewayRequest.PathParameters.TryGetValue("proxy", out var proxy) &&
!string.IsNullOrEmpty(apiGatewayRequest.Resource))
{
var proxyPath = proxy;
path = apiGatewayRequest.Resource.Replace("{proxy+}", proxyPath);
// Adds all the rest of non greedy parameters in apiGateway.Resource to the path
foreach (var pathParameter in apiGatewayRequest.PathParameters.Where(pp => pp.Key != "proxy"))
{
path = path.Replace($"{{{pathParameter.Key}}}", pathParameter.Value);
}
}
if (string.IsNullOrEmpty(path))
{
path = apiGatewayRequest.Path;
}
if (!path.StartsWith("/"))
{
path = "/" + path;
}
return path;
}
/// <summary>
/// Get the http method from the request.
/// </summary>
/// <param name="apiGatewayRequest"></param>
/// <returns>string</returns>
protected virtual string ParseHttpMethod(APIGatewayProxyRequest apiGatewayRequest)
{
return apiGatewayRequest.HttpMethod;
}
/// <summary>
/// Add missing headers to request.
/// </summary>
/// <returns>IHeaderDictionary</returns>
protected virtual IHeaderDictionary AddMissingRequestHeaders(APIGatewayProxyRequest apiGatewayRequest, IHeaderDictionary headers)
{
if (!headers.ContainsKey("Host"))
{
var apiId = apiGatewayRequest?.RequestContext?.ApiId ?? "";
var stage = apiGatewayRequest?.RequestContext?.Stage ?? "";
headers["Host"] = $"apigateway-{apiId}-{stage}";
}
return headers;
}
}
}