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

feat(cloudfront): function URL origin access control L2 construct #31339

Open
wants to merge 43 commits into
base: main
Choose a base branch
from

Conversation

watany-dev
Copy link
Contributor

@watany-dev watany-dev commented Sep 6, 2024

Issue # (if applicable)

#31629

Reason for this change

This change introduces support for Lambda Function URLs with custom Origin Access Control (OAC) in CloudFront distributions, enhancing security and control over CloudFront-Lambda integration.

Description of changes

  • Added a new feature allowing the configuration of Lambda Function URLs with custom OAC in CloudFront.
  • Implemented support for custom signing behavior and protocols for Lambda origins.
  • Included new tests to validate the correct behavior of OAC with Lambda Function URLs.

Description of how you validated changes

  • Ran unit tests to ensure that the OAC setup for Lambda Function URLs is correctly applied in CloudFront distributions.
  • Validated by deploying a sample CDK application to confirm the functionality and integration of Lambda Function URLs with CloudFront using OAC.

Checklist


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

@github-actions github-actions bot added p2 distinguished-contributor [Pilot] contributed 50+ PRs to the CDK labels Sep 6, 2024
@aws-cdk-automation aws-cdk-automation requested a review from a team September 6, 2024 09:45
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.

@watany-dev watany-dev changed the title WIP: feat(cloudfront): Function URL origin access control L2 construct feat(cloudfront): Function URL origin access control L2 construct Sep 7, 2024
@watany-dev watany-dev changed the title feat(cloudfront): Function URL origin access control L2 construct feat(cloudfront): function URL origin access control L2 construct Sep 7, 2024
@aws-cdk-automation aws-cdk-automation dismissed their stale review September 7, 2024 08:14

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

@aws-cdk-automation aws-cdk-automation added the pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member. label Sep 8, 2024
Copy link
Contributor

@gracelu0 gracelu0 left a comment

Choose a reason for hiding this comment

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

Thanks for working on this so quickly @watany-dev! :)

* An Origin for a Lambda Function URL with OAC.
*/
export class FunctionUrlOriginWithOAC extends cloudfront.OriginBase {
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's keep this class private as it's an implementation detail and not intended for public usage

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed.
a43bf40

@@ -59,4 +59,56 @@ describe('S3OriginAccessControl', () => {

expect(imported.originAccessControlId).toEqual(originAccessControlId);
});

test('creates a FunctionUrlOriginAccessControl with default properties', () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we nest the new tests under a new describe, e.g.

describe('FunctionUrlOriginAccessControl', () => {
    test(...);
});

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed.
3731370

new cloudfront.Distribution(stack, 'MyDistribution', {
defaultBehavior: {
origin: FunctionUrlOrigin.withOriginAccessControl(fnUrl, {
originAccessControl: undefined,
Copy link
Contributor

Choose a reason for hiding this comment

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

why is undefined passed here? Could we just leave out the props altogether?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed.
f660a83

}

new lambda.CfnPermission(scope, `InvokeFromApiFor${options.originId}`, {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we move this into a private function? It would make it clearer and easier to understand why a new permission is getting created

Copy link
Contributor

Choose a reason for hiding this comment

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

Also is it possible to use any existing grant or addPermission methods here instead? And how do we handle permissions for imported lambda functions?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It seems like there might still be a potential bug with addPermission, so I’m using cfnPermission instead. It’s not too complex, and since the cross-stack test is passing, I don't have any concerns. Here’s a reference (apologies, it's in Japanese!) https://dev.classmethod.jp/articles/cdk-over-21-lambda-create-error/.

Copy link
Contributor Author

@watany-dev watany-dev Sep 10, 2024

Choose a reason for hiding this comment

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

fixed.
2ad9170
989141b

},
});

// Set up integration test
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we add an assertion to this test that calls the cloudfront distribution endpoint and checks the response is as expected?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed.

Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks for adding those assertions! What I was thinking of originally was using the httpApiCall method to the distribution domain and verifying the response from the lambda (something like this test)

    const resp = JSON.stringify({
      statusCode: 200,
      body: 'Hello!!'
    });

    const fn = new lambda.Function(this, 'MyLambda', {
      runtime: lambda.Runtime.NODEJS_20_X,
      code: lambda.Code.fromInline(`exports.handler = async (event) => {return ${resp}}`),
      handler: 'index.handler'
    });
    ...
    const call = integ.assertions.httpApiCall(`https://${distribution.distributionDomainName}`);
    call.expect(ExpectedResult.objectLike({
      status: 200,
      body: 'Hello!!',
    }));

Let me know if that wouldn't work for some reason.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@gracelu0

Your comment passed the test correctly. This will ensure its appropriateness.


const template = Template.fromStack(stack);

template.hasResourceProperties('AWS::CloudFront::Distribution', {
Copy link
Contributor

Choose a reason for hiding this comment

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

since this test is checking for the correct permissions, can we also check the AWS::Lambda::Permission resource exists in the template and has the expected policy?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed.
7226680

@aws-cdk-automation aws-cdk-automation removed the pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member. label Sep 10, 2024
@watany-dev
Copy link
Contributor Author

@godwingrs22
Thanks for the review. Those are pertinent comments and have been corrected.


// Add a Lambda Function URL
const fnUrl = fn.addFunctionUrl({
authType: lambda.FunctionUrlAuthType.AWS_IAM,
Copy link
Member

@godwingrs22 godwingrs22 Sep 26, 2024

Choose a reason for hiding this comment

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

Just for my understanding, I would like to understand the behaviour of AuthType in Function URL with Cloudfront-Lambda integration with OAC origin.

  1. May i know if authType = AWS_IAM is the only supported authType in lamda function URL for Cloudfront OAC Lambda Function url origin?
  2. Or Is authType = None supported for OAC? If it is not supported, Let us mention it in ReadMe and also update the current example.
  3. If both are supported, I would recommend to have unit test for both types.

Copy link
Contributor Author

@watany-dev watany-dev Sep 27, 2024

Choose a reason for hiding this comment

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

OAC can communicate when authType = none and the necessary permissions are granted. When None is set in the L2 construct, the latter permission is automatically configured, so there are no issues. Therefore, I have prepared a test for the None case.

Copy link
Member

Choose a reason for hiding this comment

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

I did some deep dive on these two types and noticed the following behaviour.

  1. When authType = AWS_IAM, then Lambda expects the request is signed. If the request is not signed then it throws error.
  2. When authType = None, then Lambda function is configured for public access and can be accessed without any IAM credential.

Hence for OAC, I believe the current logic will allow the following scenario which shouldn't be allowed.

  1. If authType = None and OAC Signing is SIGV4_ALWAYS, then direct lambda call(without iam sigv4 credentials) is still being allowed and sigv4 credentials generated by cloudfront OAC in the request which is passed to lambda is not validated at lambda side as the authType is None. I believe this defeats the purpose of having OAC. The expectation will be if OAC is configured with SIGV4_ALWAYS, then we expect lambda is not publicly accessible directly and will be accessible only through cloudfront endpoint which internally performs sigv4 signing.

I recommend we throw synth exception if authType = None and OAC Signing is SIGV4_ALWAYS is used. Based on this AWS post, seems the recommended configuration is authType = AWS_IAM and OAC signing as SIGV4_ALWAYS.

Eg:

OAC Signing behaviour `SIGV4_ALWAYS` requires Lambda Function URL AuthType to be set to AWS_IAM

I would suggest you to validate the above scenario and also have separate unit test for each behaviour. Please correct me if my understanding is wrong.

Reference :
https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html

https://aws.amazon.com/blogs/networking-and-content-delivery/secure-your-lambda-function-urls-using-amazon-cloudfront-origin-access-control/

// Create CloudFront Distribution with OAC
const distribution = new cloudfront.Distribution(stack, 'Distribution', {
defaultBehavior: {
origin: origins.FunctionUrlOrigin.withOriginAccessControl(fnUrl),
Copy link
Member

Choose a reason for hiding this comment

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

Also I would recommend to have a another integ test for the custom OAC with new L2 construct FunctionUrlOriginAccessControl and using it in withOriginAccessControl method

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed,

super(domainName, props);
this.functionUrl = lambdaFunctionUrl;
this.props = props;
Copy link
Member

Choose a reason for hiding this comment

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

I believe we need this.originAccessControl = this.props?.originAccessControl still to set the custom OAC.

This is because originAccessControlId is being used in the bind method from this.originAccessControl. Hence for scenario where custom OAC is passed, I suspect it wont be able to retrieve the originAccessControlId based on the current logic. Please correct me if my understanding is incorrect.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You are right. I fixed it.

Copy link
Member

@godwingrs22 godwingrs22 left a comment

Choose a reason for hiding this comment

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

Thanks @watany-dev for addressing the feedback. I left few more comments. Also, Please be informed that this PR requires security review and I'm checking internally on the same. I'll let you know once it is security approved.

body: 'Hello!!',
}));

const customOacStack = new cdk.Stack(app, 'integ-cloudfront-function-url-origin-custom-oac');
Copy link
Member

Choose a reason for hiding this comment

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

I would recommend to have this integ test as a separate file so that the snapshot for this test will be generated separately.

Copy link
Contributor Author

@watany-dev watany-dev Sep 28, 2024

Choose a reason for hiding this comment

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

fixed
fea5a32

Comment on lines 174 to 180
// Make an HTTP call to the CloudFront distribution and verify the response
const customOacHttpCall = customOacInteg.assertions.httpApiCall(`https://${customOacDistribution.distributionDomainName}`);
customOacHttpCall.expect(ExpectedResult.objectLike({
status: 200,
body: 'Hello!!',
}));

Copy link
Member

Choose a reason for hiding this comment

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

Can we put another api call assertion below this to directly call lambda function url and make sure we are not able to get the expected response and getting HTTP 403 response code from lambda. Our expectation is we won't be able to call the lambda function url directly if OAC is setup and can be only accessible via cloudfront.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed. 873777b

Comment on lines 237 to 240
const oac = new cloudfront.FunctionUrlOriginAccessControl(stack, 'CustomOAC', {
originAccessControlName: 'CustomLambdaOAC',
signing: cloudfront.Signing.SIGV4_ALWAYS,
});
Copy link
Member

Choose a reason for hiding this comment

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

Can we separate this test case into two to validate below scenarios?

  1. Custom OAC without signing prop defined
  • This will create OAC with default signing which is SIGV4_ALWAYS
const oac = new cloudfront.FunctionUrlOriginAccessControl(stack, 'CustomOAC', {
      originAccessControlName: 'CustomLambdaOAC',
    });
  1. Custom OAC with signing prop defined
  • This will create OAC with signing defined. Let us use SIGV4_NO_OVERRIDE to assert
const oac = new cloudfront.FunctionUrlOriginAccessControl(stack, 'CustomOAC', {
      originAccessControlName: 'CustomLambdaOAC',
      signing: cloudfront.Signing.SIGV4_NO_OVERRIDE,
    });

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed, fd9f9b4


// Add a Lambda Function URL
const fnUrl = fn.addFunctionUrl({
authType: lambda.FunctionUrlAuthType.AWS_IAM,
Copy link
Member

Choose a reason for hiding this comment

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

I did some deep dive on these two types and noticed the following behaviour.

  1. When authType = AWS_IAM, then Lambda expects the request is signed. If the request is not signed then it throws error.
  2. When authType = None, then Lambda function is configured for public access and can be accessed without any IAM credential.

Hence for OAC, I believe the current logic will allow the following scenario which shouldn't be allowed.

  1. If authType = None and OAC Signing is SIGV4_ALWAYS, then direct lambda call(without iam sigv4 credentials) is still being allowed and sigv4 credentials generated by cloudfront OAC in the request which is passed to lambda is not validated at lambda side as the authType is None. I believe this defeats the purpose of having OAC. The expectation will be if OAC is configured with SIGV4_ALWAYS, then we expect lambda is not publicly accessible directly and will be accessible only through cloudfront endpoint which internally performs sigv4 signing.

I recommend we throw synth exception if authType = None and OAC Signing is SIGV4_ALWAYS is used. Based on this AWS post, seems the recommended configuration is authType = AWS_IAM and OAC signing as SIGV4_ALWAYS.

Eg:

OAC Signing behaviour `SIGV4_ALWAYS` requires Lambda Function URL AuthType to be set to AWS_IAM

I would suggest you to validate the above scenario and also have separate unit test for each behaviour. Please correct me if my understanding is wrong.

Reference :
https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html

https://aws.amazon.com/blogs/networking-and-content-delivery/secure-your-lambda-function-urls-using-amazon-cloudfront-origin-access-control/

@aws-cdk-automation aws-cdk-automation removed the pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member. label Sep 27, 2024
@watany-dev
Copy link
Contributor Author

@godwingrs22

I understand the content, but this cannot be achieved with the current implementation.

The lambda.FunctionUrl property does not include authType, which means, for example, the URL Auth Type of an imported function cannot be identified within the Origin construct.

May I request permission to add this property as a prerequisite patch? Once this property is added, we can merge it into the main branch, either in this commit or a separate one, to resolve this issue.

@mergify mergify bot dismissed godwingrs22’s stale review September 28, 2024 08:28

Pull request has been modified.

@aws-cdk-automation aws-cdk-automation added the pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member. label Sep 28, 2024
},
});
});
test('Creates Lambda Function URL origin with default OAC and origin properties', () => {
Copy link
Member

Choose a reason for hiding this comment

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

nit: seems this test is duplicated. It is similar to test Correctly creates a Lambda Function URL Origin with default properties

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@godwingrs22
Copy link
Member

The lambda.FunctionUrl property does not include authType, which means, for example, the URL Auth Type of an imported function cannot be identified within the Origin construct.

I see. Thanks for checking.

May I request permission to add this property as a prerequisite patch? Once this property is added, we can merge it into the main branch, either in this commit or a separate one, to resolve this issue.

Sorry, I didn't get it. Could you please elaborate your suggestion?

I think we can also update the readMe to specify to use the recommended value for Lambda Function url AuthType as AWS_IAM if OAC Signing SIGV4_ALWAYS is used. Also update the authtype given in the readMe example to AWS_IAM instead of None.

@watany-dev
Copy link
Contributor Author

@godwingrs22
I assumed that I was being asked for a validation feature, so I submitted a pull request at #31590. However, if this is unnecessary at this point and can be resolved by updating the Readme first, how does this draft look?
fcf8db0

@godwingrs22
Copy link
Member

Thank you @watany-dev for addressing the feedback promptly and appreciate your great effort.

I assumed that I was being asked for a validation feature, so I submitted a pull request at #31590. However, if this is unnecessary at this point and can be resolved by updating the Readme first, how does this draft look?

Let us keep the current readme with recommendation(which you have already updated) and also have this validation feature as well for the recommended AWS best practises. Hence, let's get the other PR #31590 merged first and then we can add this validation later in this PR. Regarding the validation, let's throw synth warning instead of exception to use the recommended value for function url authType = AWS_IAM if OAC signing is SIGV4_ALWAYS

Aside, I'm also following up internally for the security review and will let you know incase if there is any changes needs to be made from security prespective.

mergify bot pushed a commit that referenced this pull request Oct 3, 2024
…31590)

### Reason for this change

I will resolve this issue: #31339 (comment). In the current FunctionURL implementation, there is no way to access AuthType, and therefore, when writing logic that depends on AuthType, there is no method to reference it.

### Description of changes

I will fix the construct to allow access to functionurl.AuthType

### Description of how you validated changes

adding unittest and integ-test re-run.

### Reason for Exemption:
The fix introduces no changes to the resources being created.

### Clarification Request:
This fix only makes the internal property authType of the L2 Construct publicly accessible, and does not introduce any differences in the created resources.

### 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*
@aws-cdk-automation
Copy link
Collaborator

AWS CodeBuild CI Report

  • CodeBuild project: AutoBuildv2Project1C6BFA3F-wQm2hXv2jqQv
  • Commit ID: fce4e73
  • Result: FAILED
  • Build Logs (available for 30 days)

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
distinguished-contributor [Pilot] contributed 50+ PRs to the CDK p2 pr/needs-community-review This PR needs a review from a Trusted Community Member or Core Team Member.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants