Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(aws_apigatewayv2.HttpLambdaIntegration): add_routes integration to subroute doesn't take affect #18965

Closed
mitchboulay opened this issue Feb 14, 2022 · 7 comments · Fixed by #27861
Assignees
Labels
@aws-cdk/aws-apigatewayv2 Related to Amazon API Gateway v2 bug This issue is a bug. effort/medium Medium work item – several days of effort p1

Comments

@mitchboulay
Copy link

mitchboulay commented Feb 14, 2022

What is the problem?

Given (Pre configuration required):
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
API gateway configured with routes & subroutes, connected to a lambda function via CDK (Python)

Looks like a stack is not accepting multiple aws_apigatewayv2.HttpApi.add_routes() as done below in test.py

When (Action taken): Function looked up via Function.from_function_arn and applied to integration parameter of http_api.add_routes

Reproduction Steps

app.py

import os
from aws_cdk import core as cdk
from src.aws_modules.APIGateway_test.test import testStack as test

app = cdk.App()
environment = pc.getStackEnvironment()

if __name__ == "__main__":
    test(scope=app, id="test-stack-id",env=environment).run_stack()
    app.synth()

test.py

import os
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
from aws_cdk import (aws_apigatewayv2 as apigwv2,aws_lambda as lambda_)
from aws_cdk import core as cdk
from aws_cdk.aws_apigatewayv2_authorizers import HttpLambdaAuthorizer, HttpLambdaResponseType

class testStack(cdk.Stack):


    def run_stack(self):

        current_region = os.environ['CDK_DEFAULT_REGION']
        current_account = os.environ['CDK_DEFAULT_ACCOUNT']
        authorizer_lambda_name = "test-authorizer-api-dev"
        integration_lambda_name = "test-service-dev"

        api_name = "my-test-API-for-AWS"
        http_api = apigwv2.HttpApi(self, "test-api-gatewayv2",
        cors_preflight=apigwv2.CorsPreflightOptions(
        allow_headers=["*"],
        allow_methods=[apigwv2.CorsHttpMethod.ANY],
        allow_origins=["*"],
        max_age=cdk.Duration.days(10)

    )
        )


        authorizer_function = lambda_.Function.from_function_arn(
            self,
            id="found-function-authorizer",
            function_arn="arn:aws:lambda:{}:{}:function:{}".format(current_region,current_account,authorizer_lambda_name)
            )
        authorizer_test = HttpLambdaAuthorizer("test-authorizer", authorizer_function,
            response_types=[HttpLambdaResponseType.SIMPLE]
        )

        integration_function = lambda_.Function.from_function_arn(
            self,
            id="found-function-integration",
            function_arn="arn:aws:lambda:{}:{}:function:{}".format(current_region,current_account,integration_lambda_name)
            )
        function_integration = HttpLambdaIntegration("Test-FunctionIntegration", integration_function)


        http_api.add_routes(
            path="/companies",
            methods=[apigwv2.HttpMethod.GET],
            integration=function_integration,
            authorizer=authorizer_test
            )

        http_api.add_routes(
            path="/companies/swagger",
            methods=[apigwv2.HttpMethod.GET],
            integration=function_integration
            )

What did you expect to happen?

Then (Expected behavior, per documentation): Route has lambda integration defined, attached and working.

What actually happened?

Actual (Observed behavior): Route gains integration ID and appears to have function assigned to it but this is not the case. This is verified by navigating to the lambda function under Configuration, the sub-route is not defined as an endpoint.

CDK CLI Version

2.8.0 (build 8a5eb49)

Framework Version

No response

Node.js Version

v14.17.3

OS

MacOS

Language

Python

Language Version

Python 3.9.8

Other information

This looks to be an issue with the add_routes method as the from_function_arn works for the authorizer.

Workaround:

  1. CDK deploys API gateway
  2. Navigate API Gateway > integrations > Select sub route > Select HTTP method
  3. Select "Manage integration" button
  4. Select "Edit"
  5. Select "Save" button at bottom right
  6. Check lambda function > Configuration
  7. You will see the route is now there.
@mitchboulay mitchboulay added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Feb 14, 2022
@github-actions github-actions bot added the @aws-cdk/aws-apigatewayv2 Related to Amazon API Gateway v2 label Feb 14, 2022
@rockfreak
Copy link

I can verify this also exists in the javascript/typescript version of CDK and the same workaround works.

@peterwoodworth peterwoodworth added effort/small Small work item – less than a day of effort p1 and removed needs-triage This issue or PR still needs to be triaged. labels Feb 16, 2022
@otaviomacedo otaviomacedo removed their assignment Mar 4, 2022
@github-actions
Copy link

github-actions bot commented Mar 4, 2023

This issue has not received any attention in 1 year. If you want to keep this issue open, please leave a comment below and auto-close will be canceled.

@github-actions github-actions bot added the closing-soon This issue will automatically close in 4 days unless further comments are made. label Mar 4, 2023
@mitchboulay
Copy link
Author

This still needs addressing.

@github-actions github-actions bot removed the closing-soon This issue will automatically close in 4 days unless further comments are made. label Mar 4, 2023
@sumupitchayan sumupitchayan self-assigned this Oct 23, 2023
@sumupitchayan
Copy link
Contributor

sumupitchayan commented Nov 2, 2023

@mitchboulay can you confirm that this issue still exists for you?

I tried replicating this issue with an Integ Test by creating an HttpApi and adding a route and subroute with the same HttpLambdaIntegration using the following Typescript code, however it is succeeding for me and I am able to see both Integrations defined under Configuration section in the Lambda console.

import { HttpApi, HttpMethod } from '@aws-cdk/aws-apigatewayv2-alpha';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { ExpectedResult, IntegTest } from '@aws-cdk/integ-tests-alpha';
import { App, Stack } from 'aws-cdk-lib';
import { HttpLambdaIntegration } from '../../lib';

const app = new App();
const stack = new Stack(app, 'integ-lambda-proxy');

const httpApi = new HttpApi(stack, 'test-apigwv2-add-subroute-integration');

const lambdaHandler = new lambda.Function(stack, 'AlwaysSuccess - FirstRoute', {
  runtime: lambda.Runtime.NODEJS_18_X,
  handler: 'index.handler',
  code: new lambda.InlineCode('exports.handler = async function(event, context) { return { statusCode: 200, body: \'success - hit this lambda\' }; };'),
});

const lambdaHandlerIntegration = new HttpLambdaIntegration('my-lambda-integration', lambdaHandler);

httpApi.addRoutes({
  path: '/firstroute',
  methods: [HttpMethod.GET],
  integration: lambdaHandlerIntegration,
});

httpApi.addRoutes({
  path: '/firstroute/subroute',
  methods: [HttpMethod.GET],
  integration: lambdaHandlerIntegration,
});

const integ = new IntegTest(app, 'Integ', { testCases: [stack] });

integ.assertions.httpApiCall(httpApi.apiEndpoint + '/firstroute').expect(ExpectedResult.objectLike({
  status: 200,
  body: 'success - hit this lambda',
}));

integ.assertions.httpApiCall(httpApi.apiEndpoint + '/firstroute/subroute').expect(ExpectedResult.objectLike({
  status: 200,
  body: 'success - hit this lambda',
}));

Which version of CDK are you using? Perhaps this was fixed in a more recent version.

@sumupitchayan
Copy link
Contributor

@mitchboulay I was able to replicate your issue using an imported lambda function as you did above. The issue here is that imported lambdas are not able to add permissions unless they belong to the same account/region as the lambda we are importing from. So, Function.fromFunctionArn() will only work if the lambda belongs to the same account/region as the stack we're importing it into.

A workaround for this is to use fromFunctionAttributes() like below:

const myLambdaHandler: lambda.Function;

const lambdaFromFunctionAttributes = lambda.Function.fromFunctionAttributes(stack, 'my-referenced-lambda`, {
  functionArn: myLambdaHandler.functionArn,
  sameEnvironment: true,
});

After the linked PR merges, you will be able to use the fromFunctionName() instead of using the above and having to set sameEnvironment to true every time:

const myLambdaHandler: lambda.Function;

const lambdaFromFunctionName = lambda.Function.fromFunctionName(stack, 'my-referenced-lambda-from-name', 'my-lambda-handler');

@mitchboulay
Copy link
Author

Brilliant @sumupitchayan , much appreciated!

@mergify mergify bot closed this as completed in #27861 Nov 20, 2023
mergify bot pushed a commit that referenced this issue Nov 20, 2023
…ions do not get configured (#27861)

Closes #18965 

`HTTPLambdaIntegration` using imported lambda functions are currently not being configured. This is due to the fact that the `canCreatePermissions` property is set to false in imported lambdas, so the lambda permissions are never created.

This PR fixes this issue by:
- Setting the `sameEnvironment` property to `true` for lambdas imported using `fromFunctionName()`
- Adding clarification in documentation about imported lambdas needing to belong to the same stack account and region as that of the lambda being imported from be able to add permissions
- Adding a new warning to be thrown when the `addPermissions()` function is called on a lambda with `canCreatePermissions` set to false.

The new integ test file tests that imported lambdas using `fromFunctionName()` and `fromFunctionAttributes()` (with `sameEnvironment` set to `true`) work as expected, including on sub-route integrations.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
Copy link

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please either tag a team member or open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

@sumupitchayan sumupitchayan added effort/medium Medium work item – several days of effort and removed effort/small Small work item – less than a day of effort labels Nov 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
@aws-cdk/aws-apigatewayv2 Related to Amazon API Gateway v2 bug This issue is a bug. effort/medium Medium work item – several days of effort p1
Projects
None yet
5 participants