AWS - HTTP API Gateway - How do I block favicon requests?

977 Views Asked by At

I'm using a HTTP API Gateway to trigger a lambda invocation. When I use the url from postman, no issues. When I use it from my browser, it always makes a 2nd request, for the favicon.

Is there anyway in the gateway itself to block the favicon request from getting to the lambda?

I'm using the following terraform:

resource "aws_apigatewayv2_api" "retry_api" {
  name          = "${var.environment}_${var.cdp_domain}_retry_api"
  protocol_type = "HTTP"
  description   = "To pass commands into the retry lambda."
  target = module.retry-support.etl_lambda_arn
}

resource "aws_lambda_permission" "allow_retry_api" {
  statement_id  = "AllowAPIgatewayInvokation"
  action        = "lambda:InvokeFunction"
  function_name = module.retry-support.etl_lambda_arn
  principal     = "apigateway.amazonaws.com"
  source_arn = "${aws_apigatewayv2_api.retry_api.execution_arn}/*/*"
}
2

There are 2 best solutions below

0
On BEST ANSWER

This won't block the favicon request made from the browser, rather won't invoke the Lambda for those requests.

Assuming the API endpoint is /hello and the http method is GET, you can restrict api-gateway to invoke the lambda for only this URL. The format would be like this.

arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/GET/hello

So the source_arn in aws_lambda_permission would change to something like this

source_arn = "${aws_apigatewayv2_api.retry_api.execution_arn}/*/*/GET/hello"

The answer assumes the existing / in the end is for apiId and stage respectively. Otherwise check the value for ${aws_apigatewayv2_api.retry_api.execution_arn} and make modifications accordingly.

This answer can also help. You can provide the openapi specification in the body for your supported path only. For the above case the relevant path section of the openapi specification invoking a Lambda named HelloWorldFunction would look like

  "paths": {
        "/hello": {
          "get": {
            "x-amazon-apigateway-integration": {
              "httpMethod": "POST",
              "type": "aws_proxy",
              "uri": {
                "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloWorldFunction.Arn}/invocations"
              },
              "payloadFormatVersion": "2.0"
            },
            "responses": {} //Provide the expected response model
          }
        }
      }

Here is a link to OpenApi Specification.

0
On

Normally, I would do this by putting cloudfront in front of the API gateway, and map the favicon.ico to an S3 bucket.

If you really want to handle it at the API GW level, you can create a /favicon.ico route, and set the integration to MOCK - this will return a specific value, and not invoke lambda (or any other back end).