API Gateway invocation scope for Lambda needs review

Restrict API Gateway’s Lambda permission to required API routes and check caller authentication separately.

Description

Set SourceArn on AWS::Lambda::Permission to the API, stage, method and path that invoke the function.

Potential impact

A broad grant can let another route on the same API run the function if it uses that integration, increasing costs.

Remediation

Use apigateway.amazonaws.com as the principal. Configure API client authentication and authorization, and any authorization checks inside the function, separately.

Examples

Define function and supply the actual Region, account and API ID in the ARN. Both examples limit the source account to the stack’s account.

Before

yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: "Allow API Gateway to invoke Lambda"
Resources:
  s3Permission3:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt function.Arn
      Action: lambda:InvokeFunction
      Principal: apigateway.amazonaws.com
      SourceAccount: !Ref "AWS::AccountId"
      SourceArn: arn:aws:execute-api:eu-central-1:123456789012:api-id/*/*

After

yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: "Allow API Gateway to invoke Lambda"
Resources:
  apiPermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt function.Arn
      Action: lambda:InvokeFunction
      Principal: apigateway.amazonaws.com
      SourceAccount: !Ref "AWS::AccountId"
      SourceArn: arn:aws:execute-api:eu-central-1:123456789012:api-id/prod/GET/orders

apiPermission permits only GET /orders on prod. Since its logical ID differs, remove the old broad grant from s3Permission3 and verify which routes can invoke the function.

References