aws-cdk: (CloudFront): Initial Create Succeeds, Subsequent Updates Fail with Invalid request provided: AWS::CloudFront::PublicKey

The following code will create a proper Cloudfront PublicKey and it is usable to restrict access to private resources.

But, any updates to the stack that update the CloudFront PublicKey will fail with:

Resource handler returned message: "Invalid request provided: AWS::CloudFront::PublicKey" (RequestToken: fd28451c-389a-cdd8-d3f7-2bb76874bfee, HandlerErrorCode: InvalidRequest)

Reproduction Steps

        cloudfront_public_key = cloudfront.PublicKey(
            self, "cloudfront-public-key",
            encoded_key=<generated_public_key>
        )
        cloudfront_keygroup = cloudfront.KeyGroup(
            self, "cloudfront-keygroup",
            items=[cloudfront_public_key]
        )

What did you expect to happen?

I would expect the PublicKey to update without error.

What actually happened?

Environment

  • **CDK CLI Version : ** 1.108.0 (build b23f781)
  • Framework Version: 1.108.0 (build b23f781)
  • Node.js Version: v12.18.2
  • OS : CodeBuild/CodePipeline
  • Language (Version): Python 3.7.4

Other


This is šŸ› Bug Report

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 13
  • Comments: 41 (19 by maintainers)

Commits related to this issue

Most upvoted comments

in public-key.ts

https://github.com/aws/aws-cdk/blob/e220bc8ca9b75bcbb4bb7447703f32737b47fc77/packages/aws-cdk-lib/aws-cloudfront/lib/public-key.ts#L69

The issue is with callerReference: this.node.addr. This generates a new value on each deployment because:

  1. node.addr is a unique identifier generated by CDK for each construct instance
  2. It changes between deployments as it’s based on the construct tree path
  3. CloudFront’s PublicKey API requires the callerReference to remain constant after creation

When CDK tries to update the PublicKey with a new callerReference, CloudFront rejects the change since this field is immutable. This explains why initial creation works but subsequent updates fail.

The fix would be to use a stable callerReference that doesn’t change between deployments.

I’ll bring this up to the team for further review with potential fix.

Just bumped this to p1. We’ll review this issue immediately. Thank you for bringing this up to our attention.

I’m getting absolutely destroyed by this bug, currently.

…what the heck, guys?! This has been open for YEARS.

    const publicKeyConfig = new cloudfront.PublicKey(this, publicKeyName, {
      encodedKey: publicKey,
      publicKeyName: publicKeyName,
      comment: 'Public key for URL signing',
    });

First run is fine. Subsequent runs error out, miserably.

This is inside an AWS Amplify Custom CDK resource…so a lot of things all break as a result. CI/CD pipeline has come to a grinding halt. Totally.

This is just a question of uniqueness in the name generated for the resources – both for cloudfront publicKey names, as well as for secrets in SSM.

It turns out, it’s not such a hard problem to solve.

WARNING: This means on each run, old keys and secrets get nuked! They don’t get updated or versioned!

Leaving this here for anyone else that lands on the same issue or problem.

I have solved it thusly:

    // Get the project name from AmplifyHelper
    // and create a standard prefix for all resources - "projectName-env"
    const { projectName, envName } = AmplifyHelpers.getProjectInfo();
    const resourcePrefix = `${projectName}-${envName}`;

    // !! UUID usage side-steps cloudformation/cdk issue with naming of CloudFront public keys + Secrets Manager Secrets
    // Fortunately, you won't have to go and delete any old keys manually - CFN seems to handle this for you
    // Issue: https://github.com/aws/aws-cdk/issues/15301
    // Generate a UUID and take the first segment
    const uniqueId = uuidv4().split('-')[0];
    const publicKeyName = `${resourcePrefix}-cdnPublicKey-${uniqueId}`.slice(0, 128);
    const privateKeyName = `amplifyCustomCDK/${projectName}/${envName}/cdnPrivateKey-${uniqueId}`.slice(0, 512);

    // Generate a public/private key pair
    const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
      modulusLength: 2048,
      publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
      },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
      }
    });

    // Store the private key in Secrets Manager
    const privateKeySecret = new secretsmanager.Secret(this, privateKeyName, {
      secretName: privateKeyName,
      generateSecretString: {
        secretStringTemplate: JSON.stringify({ privateKey }),
        generateStringKey: 'privateKey',
      },
    });

    // Create a CloudFront public key from our generated key pair
    const publicKeyConfig = new cloudfront.PublicKey(this, publicKeyName, {
      encodedKey: publicKey,
      publicKeyName: publicKeyName,
      comment: 'Public key for URL signing',
    });

We’re still investigating this issue. A potential workaround now would be to change the logical ID of the public key, which will force a new one to be created with the correct properties.

Thanks @pahud. I’m on vacation until July 12th. However, the code I linked to above in my CDK wrapper specifically for working with PublicKey should be useful for triage in the meantime. (I would consider that minimal on any OSS repo I manage since the code is isolated) I highlighted the workarounds, and you can see the custom resource used to create the key. Commenting out the workaround will reliably reproduce CDK attempting to update the key.

Brother read the others in the issue. Sheesh.

only coming up on 4 years since this was opened and it’s still an issue. just ran into it. come on, folks.

Thanks to @armenr suggestion and @comcalvi for the suggestions.

It did help our case, but it was creating an new edge case i.e every time there is a new deployment, the earlier signed cookies would get invalidated (we are using Cloudfront Signed cookies)

One of the signed cookie name is ā€œCloudFront-Key-Pair-Idā€ and the since the Public Key resource ID has is changed on subsequent deployments, the earlier key id is deleted making the older cookies invalid!!

So here is the workaround we implemented (with 2 minor manual steps):

let cloudfrontPublicKey: cloudfront.IPublicKey;

if (!config.CLOUDFRONT_PUBLIC_KEY_ID) {
  cloudfrontPublicKey = new cloudfront.PublicKey(this, "cloudfrontPublicKey", {
      encodedKey: publicKey,
    }
  );
  cloudfrontPublicKey.applyRemovalPolicy(RemovalPolicy.RETAIN); // This is important otherwise it will destroy the resource in "else" block
  return cloudfrontPublicKey;
} else {
  cloudfrontPublicKey = cloudfront.PublicKey.fromPublicKeyId(
    this,
    "cloudfrontPublicKey",
    config.CLOUDFRONT_PUBLIC_KEY_ID
  );
}

// In the last step, we print the public key id
new cdk.CfnOutput(this, "cloudfrontPublicKeyId", {
  value: cloudfrontPublicKey.publicKeyId,
});

How it works:

  1. We create a new cloudfront public key (for the first time) and print out it’s ID
  2. Now, we add this public key id to our config (manually) so that it can be used for subsequent deployments
  3. In the subsequent deployments, since the key id exists, we won’t create it, and hence no error, and we will also get our public key object (if we want to use it for some other purposes like cloudfront key group or something else)
  4. Lastly, when you destroy the resources, we’ll have to (manually) remove the cloudfront key id

This method adds 2 manual steps which are only to be done once, i.e during creation and during deletion, so it’s definitely worth the trade off for solving our specific problem of cookies invalidation on new deployments!