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

fix(lambda): version.fromVersionArn creates invalid Version object #29820

Merged
merged 2 commits into from Apr 12, 2024

Conversation

pahud
Copy link
Contributor

@pahud pahud commented Apr 12, 2024

Issue # (if applicable)

Closes #29813

Reason for this change

improve the fromFunctionArn() to better handle the input ARN

Description of changes

fromFunctionArn() does not handle the ARN correctly if the input ARN has trailing version or alias.

Description of how you validated changes

See unit tests

Checklist


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

@aws-cdk-automation aws-cdk-automation requested a review from a team April 12, 2024 20:22
@github-actions github-actions bot added bug This issue is a bug. effort/small Small work item – less than a day of effort p1 labels Apr 12, 2024
@mergify mergify bot added the contribution/core This is a PR that came from AWS. label Apr 12, 2024
Copy link
Collaborator

@aws-cdk-automation aws-cdk-automation left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pull request linter has failed. See the aws-cdk-automation comment below for failure reasons. If you believe this pull request should receive an exemption, please comment and provide a justification.

A comment requesting an exemption should contain the text Exemption Request. Additionally, if clarification is needed add Clarification Request to a comment.

@pahud
Copy link
Contributor Author

pahud commented Apr 12, 2024

Exemption Request - unit tests added

Copy link
Contributor

@GavinZZ GavinZZ left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link
Contributor

@paulhcsun paulhcsun left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a couple comments

packages/aws-cdk-lib/aws-lambda/lib/function.ts Outdated Show resolved Hide resolved
* See lambda resource ARN format here: https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html
*/
const parts = functionArn.split(':');
if (parts.length > 7) {
Copy link
Contributor

@paulhcsun paulhcsun Apr 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not really a fan hardcoding this check with > 7 but I also don't really foresee this ever changing in terms of sections of an ARN so I guess it's ok. We should just add a description of what the 7 means.

Copy link

@rehos rehos Apr 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@paulhcsun see my comment here too. It is about the fact that the functionArn can be an unresolved token instead of a literal string too (for example when it is passed as a parameter to the CloudFormation stack). I also added a code snippet on how to handle that case too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fromFunctionArn only accepts functionArn as string. Should we consider that condition?

Copy link

@rehos rehos Apr 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pahud and @paulhcsun in the following code snippet is a stack that accepts the lambda function version arn as a parameter (for example because the actual function was created in another stack earlier in the ci/cd pipeline).

const myFunctionVersionArn = new cdk.CfnParameter(stack, 'MyFunctionVersionArn');

const version = lambda.Version.fromVersionArn(stack, 'MyVersionFunction', myFunctionVersionArn.valueAsString);

The arn that is passed to fromVersionArn is a tokenized string (value not known at compile time) and is eventually passed to fromFunctionArn because it is called by fromVersionArn under the hood. And fromVersionArn passes it down without stripping the version part from the arn.

At the moment the fix has been applied to Function.fromFunctionArn, but I think you may assume people pass the correct arn to that function. The real problem is in fromVersionArn. This function "knows" it will receive a version arn so it also should know that it should strip the version to get a valid functionArn. So I think this line should be fixed. If you do that then the Fn.join(Fn.select(.., Fn.split...) will only be generated when it is really needed.

public static fromVersionArn(scope: Construct, id: string, versionArn: string): IVersion {
      const version = extractQualifierFromArn(versionArn);

      let functionArn: string;

      if (Token.isUnresolved(versionArn)) {
            const parts =  Fn.split(':', versionArn);
            functionArn = cdk.Fn.join(':', [
                Fn.select(0, parts),
                Fn.select(1, parts),
                Fn.select(2, parts),
                Fn.select(3, parts),
                Fn.select(4, parts),
                Fn.select(5, parts),
                Fn.select(6, parts),
            ]);
      } else {
            const parts = versionArn.split(':');
            functionArn = parts.slice(0, 7).join(':');
      }

      const lambda = Function.fromFunctionArn(scope, `${id}Function`, functionArn);
  
      class Import extends QualifiedFunctionBase implements IVersion {
        public readonly version = version;
        public readonly lambda = lambda;
        public readonly functionName = `${lambda.functionName}:${version}`;
        public readonly functionArn = versionArn;
        public readonly grantPrincipal = lambda.grantPrincipal;
        public readonly role = lambda.role;
        public readonly architecture = lambda.architecture;
  
        protected readonly qualifier = version;
        protected readonly canCreatePermissions = this._isStackAccount();
  
        public addAlias(name: string, opts: AliasOptions = {}): Alias {
          return addAlias(this, this, name, opts);
        }
  
        public get edgeArn(): string {
          if (version === '$LATEST') {
            throw new Error('$LATEST function version cannot be used for Lambda@Edge');
          }
          return this.functionArn;
        }
      }
      return new Import(scope, id);
    }

@paulhcsun paulhcsun changed the title fix(lambda): Version.fromVersionArn creates invalid Version object fix(lambda): version.fromVersionArn creates invalid Version object Apr 12, 2024
@paulhcsun paulhcsun added the pr-linter/exempt-integ-test The PR linter will not require integ test changes label Apr 12, 2024
Co-authored-by: paulhcsun <47882901+paulhcsun@users.noreply.github.com>
@aws-cdk-automation aws-cdk-automation dismissed their stale review April 12, 2024 21:03

✅ Updated pull request passes all PRLinter validations. Dismissing previous PRLinter review.

Copy link
Contributor

@paulhcsun paulhcsun left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @pahud!

@aws-cdk-automation
Copy link
Collaborator

AWS CodeBuild CI Report

  • CodeBuild project: AutoBuildv2Project1C6BFA3F-wQm2hXv2jqQv
  • Commit ID: 4ff9cf1
  • Result: SUCCEEDED
  • Build Logs (available for 30 days)

Powered by github-codebuild-logs, available on the AWS Serverless Application Repository

Copy link
Contributor

mergify bot commented Apr 12, 2024

Thank you for contributing! Your pull request will be updated from main and then merged automatically (do not update manually, and be sure to allow changes to be pushed to your fork).

@mergify mergify bot merged commit 8198884 into aws:main Apr 12, 2024
11 checks passed
@rehos
Copy link

rehos commented Apr 13, 2024

I reviewed the code and I don't think it works when the function arn is an unresolved token (i.e. passed as a parameter to the CloudFormation stack). See my comment and suggestions here

@mindstorms6
Copy link
Contributor

I think this change is backwards incompatible - it broke our stack.

Previously, if you passed a function arn with a version, the getFunctionArn would retain that version. It no longer does - and this caused an outage for us (by causing an APIG authorizer to point to the "root" lambda function instead of a specific alias - where it didn't haver permissions)

@rehos
Copy link

rehos commented Apr 20, 2024

Sorry to hear the change caused an outage. My issue still isn't fixed with the change (see also my comment above, in which I also suggested not to change Function.fromFunctionArn, but instead fix Version.fromVersionArn).

This still generates an invalid stack:

const DemoClientVersionArn = new cdk.CfnParameter(this, 'DemoClientVersionArn');

const demoClientVersion = lambda.Version.fromVersionArn(this, 'DemoClientVersion', DemoClientVersionArn.valueAsString);

const demoClientCurrentAlias = new lambda.Alias(this, 'DemoClientCurrentAlias', {
    aliasName: 'current',
    version: demoClientVersion,
});

// The function url resource created by the CDK causes a CloudFormation deployment error
// because the version qualifier is still part of the functionArn of the lambda.Function
// created by lambda.Version.fromVersionArn
const demoClientFunctionUrl = new lambda.FunctionUrl(this, 'DemoClientFunctionUrl', {
    authType: lambda.FunctionUrlAuthType.AWS_IAM,
    invokeMode: lambda.InvokeMode.RESPONSE_STREAM,
    function: demoClientCurrentAlias,
});

mergify bot pushed a commit that referenced this pull request Apr 29, 2024
…object" (#30003)

### Issue # (if applicable)

Revert #29820

Closes #30002

### Reason for this change



### Description of changes



### Description of how you validated changes



### Checklist
- [x] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md)

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
moelasmar pushed a commit that referenced this pull request Apr 29, 2024
…object" (#30003)

### Issue # (if applicable)

Revert #29820

Closes #30002

### Reason for this change



### Description of changes



### Description of how you validated changes



### Checklist
- [x] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md)

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug This issue is a bug. contribution/core This is a PR that came from AWS. effort/small Small work item – less than a day of effort p1 pr-linter/exempt-integ-test The PR linter will not require integ test changes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

aws_lambda: Version.fromVersionArn creates invalid Version object
6 participants