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

cloudfront: edgeLambdas not associating trigger #25783

Closed
ETisREAL opened this issue May 30, 2023 · 8 comments
Closed

cloudfront: edgeLambdas not associating trigger #25783

ETisREAL opened this issue May 30, 2023 · 8 comments
Labels
@aws-cdk/aws-cloudfront Related to Amazon CloudFront bug This issue is a bug. closing-soon This issue will automatically close in 4 days unless further comments are made. effort/medium Medium work item – several days of effort p3 response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.

Comments

@ETisREAL
Copy link

Describe the bug

Trying to associate an edge lambda function to a cloudfront distribution doesn't result in the association of the trigger event with the lambda function

Expected Behavior

Upon creation, I should be able to see the coudfront distribution associated as a trigger with the function

Current Behavior

Everything gets created, but the trigger event

Reproduction Steps

Here is my code... (granted, the logging doesn't work... working on it)

import * as cdk from "aws-cdk-lib"
import { Construct } from "constructs"
import { BlockPublicAccess, Bucket, BucketAccessControl } from "aws-cdk-lib/aws-s3"
import * as cloudfront from "aws-cdk-lib/aws-cloudfront"
import * as origins from "aws-cdk-lib/aws-cloudfront-origins"
import * as acm from "aws-cdk-lib/aws-certificatemanager"
import * as iam from 'aws-cdk-lib/aws-iam'
import { STAGE } from "../../bin/infrastucture"
import * as fs from 'fs'
import * as path from 'path'
import * as lambda from 'aws-cdk-lib/aws-lambda'
import { RetentionDays } from 'aws-cdk-lib/aws-logs'
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager'


interface OpenapiStackProps extends cdk.StackProps {
    STAGE: STAGE
    bucketDeployer?: iam.IUser
}

export class OpenapiStack extends cdk.Stack {

    readonly openapiBucketOrigin
    readonly openapiKeyId
    public openapiDistribution

    constructor(scope: Construct, id: string, props: OpenapiStackProps) {
        super(scope, id, props)
    
        const config = this.node.tryGetContext('stages')[props.STAGE]

        const openapiBucket = new Bucket(this, config.openapiBucketName, {
            bucketName: config.openapiBucketName,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
            autoDeleteObjects: true,
            accessControl: BucketAccessControl.BUCKET_OWNER_FULL_CONTROL,
            blockPublicAccess: BlockPublicAccess.BLOCK_ACLS
        })

        this.openapiKeyId = new cloudfront.PublicKey(this, `${props.STAGE}openapiPubKey`, {
            publicKeyName: `${props.STAGE}openapiPubKey`,
            encodedKey: fs.readFileSync(path.resolve('resources/cloudfront-keys/STGopenapiPubKey.pub'), {encoding: 'utf-8'})
        })

        this.openapiBucketOrigin = new origins.S3Origin(openapiBucket, { 
            originAccessIdentity: new cloudfront.OriginAccessIdentity(this, `${props.STAGE}-openapiOAI`, {
                comment: `OAI for ${props.STAGE}-Openapi cloudfront distribution`
            }) 
        })

        const openapiEdgeLambdaRole = new iam.Role(this, `${props.STAGE}openapiEdgeLambdaRole`, {
            roleName: `${props.STAGE}openapiEdgeLambdaRole`,
            assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
            inlinePolicies: {
                'AllowopenapiEdgeLambdaToLogInEveryRegion': new iam.PolicyDocument({
                    statements: [
                        new iam.PolicyStatement({
                            actions: [
                                "logs:CreateLogStream",
                                "logs:CreateLogGroup",
                                "logs:PutLogEvents"
                            ],
                            resources: ["arn:aws:logs:*:*:*"]
                        })
                    ]
                })
            }
        })

        const openapiEdgeLambda = new cloudfront.experimental.EdgeFunction(this, 'openapiSignURLHandler', {
            functionName: 'openapiSignURLHandler',
            code: lambda.Code.fromInline(`... CODE ...`),
            handler: 'index.signUrl',
            runtime: lambda.Runtime.NODEJS_16_X,
            logRetention: RetentionDays.ONE_DAY,
            role: openapiEdgeLambdaRole
        })

        this.openapiDistribution = new cloudfront.Distribution(this, `${props.STAGE}-openapiDistribution`, {
            defaultRootObject: 'index.html',
            domainNames: config.openapiDomainName,
            priceClass: cloudfront.PriceClass.PRICE_CLASS_100,
            certificate: acm.Certificate.fromCertificateArn(this, `${props.STAGE}-openapiCertificate`, config.openapiCertificateArn),
            defaultBehavior: {
                origin: this.openapiBucketOrigin,
                allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
                viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS
            },
            additionalBehaviors: {
                'private/*': {
                    origin: this.openapiBucketOrigin,
                    allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
                    viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
                    trustedKeyGroups: [
                        new cloudfront.KeyGroup(this, 'openapiKeyGroup', {
                            keyGroupName: 'openapiKeyGroup',
                            items: [this.openapiKeyId]
                        })
                    ],
                    edgeLambdas: [
                        {
                            eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
                            functionVersion: openapiEdgeLambda.currentVersion,
                            includeBody: true
                        }
                    ]
                }
            }
        })

        props.bucketDeployer?.attachInlinePolicy( 
            new iam.Policy(this, `${props.STAGE.toLowerCase()}-deploy-openapi-to-s3`, {
                statements: [
                    new iam.PolicyStatement({
                        actions: [ 
                            "s3:PutObject",
                            "s3:GetObject",
                            "s3:AbortMultipartUpload",
                            "s3:ListBucket",
                            "s3:DeleteObject",
                            "s3:GetObjectVersion",
                            "s3:ListMultipartUploadParts"
                        ],
                        resources: [openapiBucket.bucketArn, `${openapiBucket.bucketArn}/*`]
                    })
                ]
            })
        )

    }
}

Possible Solution

I'm pretty sure is just a missing line of code on the association between the distribution and the function

Additional Information/Context

No response

CDK CLI Version

2.81

Framework Version

No response

Node.js Version

v18.04

OS

Linux - Ubuntu

Language

Typescript

Language Version

No response

Other information

No response

@ETisREAL ETisREAL added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels May 30, 2023
@github-actions github-actions bot added the @aws-cdk/aws-cloudfront Related to Amazon CloudFront label May 30, 2023
@pahud
Copy link
Contributor

pahud commented Jun 5, 2023

Hi

Which region are you deploying? us-east-1 ?

@pahud pahud self-assigned this Jun 5, 2023
@pahud pahud added response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. p2 effort/medium Medium work item – several days of effort and removed needs-triage This issue or PR still needs to be triaged. labels Jun 5, 2023
@ETisREAL
Copy link
Author

ETisREAL commented Jun 7, 2023

Hello

Yes, I am deploying everything in us-east-1. Still, no luck

@github-actions github-actions bot removed the response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. label Jun 7, 2023
@rv2673
Copy link
Contributor

rv2673 commented Oct 1, 2023

@ETisREAL how did you check for presence of trigger event?

The cloudfront trigger is only shown/visible on the specific lamba version in home region us-east-1. Not on latest or replicas.

If you go to lamba in aws console you need to select version under version tab to see the triggers for that version.

@ETisREAL
Copy link
Author

ETisREAL commented Oct 1, 2023

Hi @rv2673 I checked the current version on us-east-1 region, but still it didn't appear. To be honest, I've dropped that option by now, so maybe I should try again and see if I still have the same issue now, but at the time I am sure I checked the version and the region

@pahud
Copy link
Contributor

pahud commented Jun 14, 2024

@ETisREAL I created a very tiny sample. Can you try the EdgeFunction like this and let me know if it works for you?

image

@pahud pahud added response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. p3 and removed p2 labels Jun 14, 2024
@pahud pahud removed their assignment Jun 14, 2024
Copy link

This issue has not received a response in a while. 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 Jun 16, 2024
@ETisREAL
Copy link
Author

Hi @pahud I confirm that now everything is working as expected! Awesome!

Thank you very much for the time you dedicated to this issue :)

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
@aws-cdk/aws-cloudfront Related to Amazon CloudFront bug This issue is a bug. closing-soon This issue will automatically close in 4 days unless further comments are made. effort/medium Medium work item – several days of effort p3 response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.
Projects
None yet
Development

No branches or pull requests

3 participants