public APIGatewayHttpApiV2ProxyResponse Update(APIGatewayHttpApiV2ProxyRequest request)
        {
            var notes  = getNotes();
            var noteId = request.PathParameters["id"];

            if (notes.ContainsKey(noteId))
            {
                Console.WriteLine(request.Body);
                var body = JsonSerializer.Deserialize <Dictionary <string, string> >(request.Body);
                var note = notes[noteId];
                note.Content = body["content"];
                return(new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body = JsonSerializer.Serialize <Note>(note, jsonSerializeOptions),
                });
            }

            return(new APIGatewayHttpApiV2ProxyResponse
            {
                StatusCode = (int)HttpStatusCode.NotFound,
                Body = JsonSerializer.Serialize <Dictionary <string, bool> >(new Dictionary <string, bool> {
                    ["error"] = true
                }),
            });
        }
        public async Task<APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayHttpApiV2ProxyAsync(
            Func<APIGatewayHttpApiV2ProxyRequest, ILambdaContext, Task<APIGatewayHttpApiV2ProxyResponse>> asyncHandler,
            APIGatewayHttpApiV2ProxyRequest request,
            ILambdaContext context,
            string operationName = null,
            IDictionary<string, string> tags = null)
        {
            using (var tracker = new TelemetryTracker(context, operationName, tags, request.Headers))
            {
                try
                {
                    APIGatewayHttpApiV2ProxyResponse apiGatewayProxyResponse = await asyncHandler(request, context);
                    if (!apiGatewayProxyResponse.IsSuccessStatusCode())
                    {
                        tracker.SetErrorCounter();

                        // Preserve the legacy logging.
                        LambdaLogger.Log($"[ERR] Invoking lambda function. Http status code: {apiGatewayProxyResponse.StatusCode}. Response body: {apiGatewayProxyResponse.Body}{Environment.NewLine}");
                    }

                    return apiGatewayProxyResponse;
                }
                catch (Exception e)
                {
                    tracker.SetException(e);
                    throw;
                }
            }
        }
        public async Task <APIGatewayHttpApiV2ProxyResponse> FunctionHandler(APIGatewayHttpApiV2ProxyRequest eventTrigger)
        {
            Console.WriteLine(JsonSerializer.Serialize(eventTrigger));

            var body = eventTrigger.Body;

            if (eventTrigger.IsBase64Encoded)
            {
                body = Encoding.UTF8.GetString(Convert.FromBase64String(body));
            }

            // Add "id" from path parameters to JSON body
            var data = JsonSerializer.Deserialize <Dictionary <string, dynamic> >(body);

            data["id"] = eventTrigger.PathParameters["id"];
            var dataJSON = JsonSerializer.Serialize(data);

            var client = new AmazonDynamoDBClient();
            var table  = Table.LoadTable(client, Environment.GetEnvironmentVariable("TABLE_NAME"));

            await table.PutItemAsync(Document.FromJson(dataJSON));

            return(new APIGatewayHttpApiV2ProxyResponse
            {
                StatusCode = 204
            });
        }
Beispiel #4
0
        /// <summary>
        /// A Lambda function that returns the blog identified by blogId
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <APIGatewayHttpApiV2ProxyResponse> GetBlogAsync(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
        {
            string blogId = null;

            if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME))
            {
                blogId = request.PathParameters[ID_QUERY_STRING_NAME];
            }
            else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(ID_QUERY_STRING_NAME))
            {
                blogId = request.QueryStringParameters[ID_QUERY_STRING_NAME];
            }

            if (string.IsNullOrEmpty(blogId))
            {
                return(new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Body = $"Missing required parameter {ID_QUERY_STRING_NAME}"
                });
            }

            context.Logger.LogLine($"Getting the blog {blogId}");

            var response = new APIGatewayHttpApiV2ProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = $"Fetched blog {blogId}",
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            };

            return(response);
        }
 public APIGatewayHttpApiV2ProxyResponse List(APIGatewayHttpApiV2ProxyRequest request)
 {
     return(new APIGatewayHttpApiV2ProxyResponse
     {
         StatusCode = (int)HttpStatusCode.OK,
         Body = JsonSerializer.Serialize <Dictionary <string, Note> >(getNotes(), jsonSerializeOptions),
     });
 }
        /// <summary>
        /// The Handler function triggered by the AWS APIGateway.
        /// </summary>
        /// <param name="gwEvent">Data passed from the APIGateway to the handler. The Handler only checks for one QueryParameter withe the name "d" and then tries to decode its value.</param>
        /// <returns>The response that will beconverted to a HTTP response by the API Gateway</returns>
        /// <example>Parameter d structure: content of the parameter is aes encrypted and base62 encoded. Format: "[optional salt];[validuntil ISO 8601];[target url urlencoded];[target ip];[salt]*"</example>
        public async Task <APIGatewayHttpApiV2ProxyResponse> Handler(APIGatewayHttpApiV2ProxyRequest gwEvent)
        {
            var key    = Environment.GetEnvironmentVariable("ENCRYPTION_KEY");
            var dataok = gwEvent.QueryStringParameters.TryGetValue("d", out var data);

            if (!dataok)
            {
                return(new APIGatewayHttpApiV2ProxyResponse()
                {
                    StatusCode = 400, Body = "Missing Data"
                });
            }

            try
            {
                var prd  = ProxyRequestDataDecoder.CreateFromEncodedAndEncrypted(data, key);
                var body = $"ValidUntil: {prd.ValidUntil:O}  -  SourceIP: {prd.IP}  -  Url: {prd.Url}";
                if (prd.ValidUntil < DateTime.Now)
                {
                    LambdaLogger.Log($"Token outdated : {body}");
                    return(new APIGatewayHttpApiV2ProxyResponse()
                    {
                        StatusCode = 400, Body = "Token not valid anymore."
                    });
                }

                if (!prd.Debug)
                {
                    var cli = new HttpClient();
                    LambdaLogger.Log($"Triggering Request: {body}");
                    var result = await cli.SendAsync(CreateRequest(prd));

                    LambdaLogger.Log($"Request result: {result.StatusCode}");
                    return(new APIGatewayHttpApiV2ProxyResponse()
                    {
                        StatusCode = 200, Body = "MyFunc"
                    });
                }
                else
                {
                    LambdaLogger.Log($"Debug Request: {body}");
                    return(new APIGatewayHttpApiV2ProxyResponse()
                    {
                        StatusCode = 200, Body = body
                    });
                }
            }
            catch (Exception ex)
            {
                LambdaLogger.Log($"Exception while processing: {ex.Message}");
                LambdaLogger.Log(ex.StackTrace);
                return(new APIGatewayHttpApiV2ProxyResponse()
                {
                    StatusCode = 400, Body = ex.Message
                });
            }
        }
 public APIGatewayHttpApiV2ProxyResponse Handler(APIGatewayHttpApiV2ProxyRequest request)
 {
     return(new APIGatewayHttpApiV2ProxyResponse
     {
         StatusCode = (int)HttpStatusCode.OK,
         Body = $"Hello, World! Your request was received at {request.RequestContext.Time}.",
         Headers = new Dictionary <string, string> {
             { "Content-Type", "application/json" }
         }
     });
 }
Beispiel #8
0
 public APIGatewayHttpApiV2ProxyResponse Handler(APIGatewayHttpApiV2ProxyRequest request)
 {
     return(new APIGatewayHttpApiV2ProxyResponse
     {
         StatusCode = (int)HttpStatusCode.OK,
         Body = "Hello World!",
         Headers = new Dictionary <string, string> {
             { "Content-Type", "application/json" }
         }
     });
 }
        public async Task <APIGatewayHttpApiV2ProxyResponse> Handle(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
        {
            var inner  = JsonConvert.DeserializeObject <S3Event>(request.Body);
            var result = await FunctionHandler(inner, context);

            var response = new APIGatewayHttpApiV2ProxyResponse
            {
                Body = JsonConvert.SerializeObject(result)
            };

            return(response);
        }
        public async Task <APIGatewayHttpApiV2ProxyResponse> Handle(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
        {
            var json   = UTF8Encoding.UTF8.GetBytes(request.Body);
            var inner  = JsonSerializer.Deserialize <S3Event>(json);
            var result = await FunctionHandler(inner, context);

            var response = new APIGatewayHttpApiV2ProxyResponse
            {
                Body = JsonSerializer.Serialize(result)
            };

            return(response);
        }
Beispiel #11
0
        public APIGatewayProxyResponse FunctionHandler(APIGatewayHttpApiV2ProxyRequest apigProxyEvent, ILambdaContext context)
        {
            Console.WriteLine($"Processing request data for request {apigProxyEvent.RequestContext.RequestId}.");
            Console.WriteLine($"Body size = {apigProxyEvent.Body.Length}.");
            var headerNames = string.Join(", ", apigProxyEvent.Headers.Keys);

            Console.WriteLine($"Specified headers = {headerNames}.");

            return(new APIGatewayProxyResponse
            {
                Body = apigProxyEvent.Body,
                StatusCode = 200,
            });
        }
Beispiel #12
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool FunctionHandler(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
        {
            var input = JsonSerializer.Serialize(request);

            context.Logger.LogLine($"req: {input}");
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            };

            var user         = JsonSerializer.Deserialize <User>(request.Body, options);
            var isAuthorized = false;

            if (user.Roles.Contains("admin"))
            {
                isAuthorized = true;
            }
            context.Logger.LogLine($"User: {user.Name}, authorized: {isAuthorized}");
            return(isAuthorized);
        }
        public APIGatewayHttpApiV2ProxyResponse Get(APIGatewayHttpApiV2ProxyRequest request)
        {
            var notes  = getNotes();
            var noteId = request.PathParameters["id"];

            if (notes.ContainsKey(noteId))
            {
                return(new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body = JsonSerializer.Serialize <Note>(notes[noteId], jsonSerializeOptions),
                });
            }

            return(new APIGatewayHttpApiV2ProxyResponse
            {
                StatusCode = (int)HttpStatusCode.NotFound,
                Body = JsonSerializer.Serialize <Dictionary <string, bool> >(new Dictionary <string, bool> {
                    ["error"] = true
                }),
            });
        }
Beispiel #14
0
        public Tuple <double, double> Add([FromBody] string complexNumbers, ILambdaContext context, APIGatewayHttpApiV2ProxyRequest request)
        {
            context.Logger.Log($"Request {JsonSerializer.Serialize(request)}");

            var components = complexNumbers.Split(";");

            if (components.Length != 2)
            {
                throw new ArgumentException(@$ "Complex numbers must be in format " "1,2;3,4" ", but found " "{complexNumbers}" "");
            }

            var firstComponent = components[0].Split(",");

            if (firstComponent.Count() != 2)
            {
                throw new ArgumentException(@$ "Complex number must be in format " "1,2" ", but found " "{firstComponent}" "");
            }

            var secondComponent = components[1].Split(",");

            if (secondComponent.Count() != 2)
            {
                throw new ArgumentException(@$ "Complex number must be in format " "1,2" ", but found " "{secondComponent}" "");
            }

            var c1     = new Complex(int.Parse(firstComponent[0]), int.Parse(firstComponent[1]));
            var c2     = new Complex(int.Parse(secondComponent[0]), int.Parse(secondComponent[1]));
            var result = c1 + c2;

            return(new Tuple <double, double>(result.Real, result.Imaginary));
        }
        /// <inheritdoc />
        /// <summary>
        /// This overriding method is what the Lambda function handler points to.
        /// </summary>
        public override async Task <APIGatewayHttpApiV2ProxyResponse> FunctionHandlerAsync(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext lambdaContext)
        {
            if (!TelemetryConfiguration.TracingEnabled && !TelemetryConfiguration.MetricsEnabled)
            {
                return(await base.FunctionHandlerAsync(request, lambdaContext).ConfigureAwait(false));
            }

            return(await s_functionWrapper.InvokeAPIGatewayHttpApiV2ProxyAsync(
                       base.FunctionHandlerAsync,
                       request,
                       lambdaContext).ConfigureAwait(false));
        }
        /// <summary>
        /// Amazon EventBridge event schedule rule to keep the Lambda/s warm
        /// Payload: { "RouteKey": "WarmingLambda", "Body": "3" }
        /// </summary>
        /// <param name="request"></param>
        /// <param name="lambdaContext"></param>
        /// <returns></returns>
        public override async Task <APIGatewayHttpApiV2ProxyResponse> FunctionHandlerAsync(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext lambdaContext)
        {
            LambdaLogger.Log("In overridden FunctionHandlerAsync...");

            if (request.RouteKey == "WarmingLambda")
            {
                int.TryParse(request.Body, out var concurrencyCount);

                if (concurrencyCount > 1)
                {
                    LambdaLogger.Log($"Warming instance {concurrencyCount}.");
                    var client = new AmazonLambdaClient();
                    await client.InvokeAsync(new InvokeRequest
                    {
                        FunctionName   = lambdaContext.FunctionName,
                        InvocationType = InvocationType.RequestResponse,
                        Payload        = JsonSerializer.Serialize(new APIGatewayHttpApiV2ProxyRequest
                        {
                            RouteKey = request.RouteKey,
                            Body     = (concurrencyCount - 1).ToString()
                        })
                    });
                }

                return(new APIGatewayHttpApiV2ProxyResponse());
            }

            return(await base.FunctionHandlerAsync(request, lambdaContext));
        }
Beispiel #17
0
        public async Task <APIGatewayHttpApiV2ProxyResponse> InboundParse(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
        {
            APIGatewayHttpApiV2ProxyResponse response;

            var getParameterResponse = await _ssmClient.GetParameterAsync(new GetParameterRequest
            {
                Name           = AuthenticationKeyParameterName,
                WithDecryption = true
            });

            var authenticationKey = getParameterResponse?.Parameter?.Value;

            string authenticationKeyPresented = null;

            request.QueryStringParameters?.TryGetValue(AuthenticationQueryParameterKey, out authenticationKeyPresented);

            if (string.IsNullOrEmpty(authenticationKeyPresented) || string.IsNullOrEmpty(authenticationKey) ||
                authenticationKeyPresented != authenticationKey)
            {
                context.Logger.LogLine($"Failed to authenticate.");

                return(new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.Unauthorized
                });
            }

            try
            {
                context.Logger.LogLine("Request Headers:");
                foreach (var header in request.Headers)
                {
                    context.Logger.LogLine($"{header.Key}: {header.Value}");
                }
                context.Logger.LogLine($"Request IsBase64Encoded:\n{request.IsBase64Encoded}");
                context.Logger.LogLine($"Request Body:\n{request.Body}");

                var requestBody = new MemoryStream(Convert.FromBase64String(request.Body));

                var parser       = new WebhookParser();
                var inboundEmail = parser.ParseInboundEmailWebhook(requestBody);
                context.Logger.LogLine($"InboundEmail Subject:\n{inboundEmail.Subject}");
                context.Logger.LogLine($"InboundEmail To:\n{inboundEmail.To[0].Email}");
                context.Logger.LogLine($"InboundEmail From:\n{inboundEmail.From.Email}");
                context.Logger.LogLine($"InboundEmail DKIM:\n{inboundEmail.Dkim}");
                context.Logger.LogLine($"InboundEmail SPF:\n{inboundEmail.Spf}");

                context.Logger.LogLine($"InboundEmail Envelope.From:\n{inboundEmail.Envelope.From}");

                response = new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = "Success",
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    }
                };
            }
            catch (Exception ex)
            {
                var exception = ex.ToString();
                context.Logger.LogLine($"Exception occurred:\n{exception}");

                response = new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = ex.Message,
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    }
                };
            }

            return(response);
        }