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: CachePolicy is not supported when deployed in China #31033

Open
Chenming88 opened this issue Aug 6, 2024 · 6 comments
Open

cloudfront: CachePolicy is not supported when deployed in China #31033

Chenming88 opened this issue Aug 6, 2024 · 6 comments
Labels
@aws-cdk/aws-cloudfront Related to Amazon CloudFront bug This issue is a bug. effort/medium Medium work item – several days of effort p2

Comments

@Chenming88
Copy link

Describe the bug

AWS China does not support CachePolicy, but a default value is assigned in the cdk, causing the deployment to fail. #13584

I use the way I override cachePolicyId=underfined, which works for defaultCacheBehavior, but because I need to use multiple Behaviors. cacheBehaviors return is a LazyAny type and can't be overwritten, which makes it impossible to circumvent aws restrictions. I hope you can fix this bug, thank you very much.

Expected Behavior

The new CloudFront distribution can be deployed to AWS China regions.

Current Behavior

5:38:40 PM | UPDATE_FAILED | AWS::CloudFront::Distribution | cloudfrontcloudfrontdistributionAC735BF7
Resource handler returned message: "Invalid request provided: The parameter CachePolicyId can't be set for this region. (Service: CloudFront, Status Code: 400, Request ID: 654c85b7-0854-446d-b7f2-1a1e49452bff)" (RequestToken:
a2525e84-fff0-fa4b-bfe9-db7e90db4eeb, HandlerErrorCode: InvalidRequest)

❌ sandbox-cn-north-1 failed: Error: The stack named sandbox-cn-north-1 failed to deploy: UPDATE_ROLLBACK_COMPLETE: Resource handler returned message: "Invalid request provided: The parameter CachePolicyId can't be set for this region. (Service: CloudFront, Status Code: 400, Request ID: 654c85b7-0854-446d-b7f2-1a1e49452bff)" (RequestToken: a2525e84-fff0-fa4b-bfe9-db7e90db4eeb, HandlerErrorCode: InvalidRequest)
at FullCloudFormationDeployment.monitorDeployment (/usr/local/lib/node_modules/aws-cdk/lib/index.js:431:10615)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.deployStack2 [as deployStack] (/usr/local/lib/node_modules/aws-cdk/lib/index.js:434:196750)
at async /usr/local/lib/node_modules/aws-cdk/lib/index.js:434:178719

Reproduction Steps

this.distribution = new Distribution(this, `cloudfront-distribution`, {
  domainNames: [rootDomain],
  defaultBehavior: {
    origin: new S3Origin(bucket, { originPath }),
    allowedMethods: AllowedMethods.ALLOW_GET_HEAD,
    viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
    cachedMethods: CachedMethods.CACHE_GET_HEAD,
    responseHeadersPolicy,
  },
  additionalBehaviors: {
    "/test/*": {
      origin: new S3Origin(bucket),
      allowedMethods: AllowedMethods.ALLOW_GET_HEAD,
      viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      cachedMethods: CachedMethods.CACHE_GET_HEAD,
      responseHeadersPolicy,
    },
  },
  defaultRootObject: "index.html",
  httpVersion: HttpVersion.HTTP2,
  enableIpv6: false,
  enableLogging: true,
});

Possible Solution

No response

Additional Information/Context

Because the cacheBehaviors type is LazyAny, it is not rewrite successfully, resulting in the same error

const cfn = this.distribution.node.findChild("Resource") as CfnDistribution;
const distributionConfig = cfn.distributionConfig as CfnDistribution.DistributionConfigProperty;

cfn.distributionConfig = {
  ...cfn.distributionConfig,
  defaultCacheBehavior: {
    ...distributionConfig.defaultCacheBehavior,
    cachePolicyId: undefined,
    forwardedValues: { queryString: false },
    defaultTtl: cdk.Duration.days(1).toSeconds(),
    minTtl: cdk.Duration.hours(1).toSeconds(),
    maxTtl: cdk.Duration.days(365).toSeconds(),
  },
  // cacheBehaviors: Array.isArray(distributionConfig.cacheBehaviors)
  //   ? distributionConfig.cacheBehaviors.map((behavior) => ({
  //     ...behavior,
  //     cachePolicyId: undefined,
  //     forwardedValues: { queryString: false },
  //     defaultTtl: cdk.Duration.days(1).toSeconds(),
  //     minTtl: cdk.Duration.hours(1).toSeconds(),
  //     maxTtl: cdk.Duration.days(365).toSeconds(),
  //   })) : distributionConfig.cacheBehaviors, // TODO: cacheBehaviors type is LazyAny
};

CDK CLI Version

2.123.0

Framework Version

No response

Node.js Version

v18.14.1

OS

mac

Language

TypeScript

Language Version

No response

Other information

No response

@Chenming88 Chenming88 added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Aug 6, 2024
@github-actions github-actions bot added the @aws-cdk/aws-cloudfront Related to Amazon CloudFront label Aug 6, 2024
@pahud pahud changed the title aws-cdk-lib/aws-cloudfront: CachePolicy is not supported when deployed in China cloudfront: CachePolicy is not supported when deployed in China Aug 6, 2024
@pahud pahud added p1 effort/medium Medium work item – several days of effort and removed needs-triage This issue or PR still needs to be triaged. labels Aug 6, 2024
@pahud
Copy link
Contributor

pahud commented Aug 6, 2024

Yes #13584 is still relevant. I just reopened it. We need a PR to address that.

@pahud pahud self-assigned this Aug 6, 2024
@pahud
Copy link
Contributor

pahud commented Aug 6, 2024

internal tracking: V1476577865

@pahud
Copy link
Contributor

pahud commented Aug 7, 2024

Hi @Chenming88

We are still pending for the response from cloudfront team before we know how to address that for China regions with #31038.

Before we fix this issue from there, I guess you could write a CDK Aspect to override or remove the cachePolicyId.

I don't have immediate sample for that but this could be a workaround.

Check out here for the doc of CDK Aspects.

@Chenming88
Copy link
Author

Hi @Chenming88

We are still pending for the response from cloudfront team before we know how to address that for China regions with #31038.

Before we fix this issue from there, I guess you could write a CDK Aspect to override or remove the cachePolicyId.

I don't have immediate sample for that but this could be a workaround.

Check out here for the doc of CDK Aspects.

Thanks for your help, I found a way to handle LazyAny type using Aspects, which is my way around.

// Later, apply to the stack
Aspects.of(this).add({
  visit(node: IConstruct) {
    if (node instanceof CfnDistribution) {
      const distributionConfig = node.distributionConfig as CfnDistribution.DistributionConfigProperty;
      const resolvedCacheBehaviorsDefs = cdk.Stack.of(node).resolve(distributionConfig.cacheBehaviors) as CfnDistribution.CacheBehaviorProperty[];
      node.distributionConfig = {
        ...distributionConfig,
        cacheBehaviors: resolvedCacheBehaviorsDefs.map(cacheBehavior => {
          return {
            ...cacheBehavior,
            cachePolicyId: undefined,
            forwardedValues: { queryString: false },
            defaultTtl: cdk.Duration.days(1).toSeconds(),
            minTtl: cdk.Duration.hours(1).toSeconds(),
            maxTtl: cdk.Duration.days(365).toSeconds(),
          }
        }),
      }
    }
  }
});

@pahud
Copy link
Contributor

pahud commented Aug 14, 2024

Hi

This works for me as well:

export class DummyStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const origin = defaultOrigin();
    const dist = new cloudfront.Distribution(this, 'MyDist', { defaultBehavior: { origin } });
    const cfndist = dist.node.defaultChild as cloudfront.CfnDistribution;
    cfndist.addPropertyDeletionOverride('DistributionConfig.DefaultCacheBehavior.CachePolicyId');
    cfndist.addPropertyOverride('DistributionConfig.DefaultCacheBehavior.ForwardedValues', {
      "QueryString": false
    });
  }
}

cdk synth

 MyDistDB88FD9A:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        DefaultCacheBehavior:
          Compress: true
          ForwardedValues:
            QueryString: false
          TargetOriginId: dummystack7MyDistOrigin1E2CDA54E
          ViewerProtocolPolicy: allow-all
        Enabled: true
        HttpVersion: http2
        IPV6Enabled: true
        Origins:
          - CustomOriginConfig:
              OriginProtocolPolicy: https-only
            DomainName: www.example.com
            Id: dummystack7MyDistOrigin1E2CDA54E

Let me know if this works for you.

related to #13584 (comment)

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

Hi

This works for me as well:

export class DummyStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const origin = defaultOrigin();
    const dist = new cloudfront.Distribution(this, 'MyDist', { defaultBehavior: { origin } });
    const cfndist = dist.node.defaultChild as cloudfront.CfnDistribution;
    cfndist.addPropertyDeletionOverride('DistributionConfig.DefaultCacheBehavior.CachePolicyId');
    cfndist.addPropertyOverride('DistributionConfig.DefaultCacheBehavior.ForwardedValues', {
      "QueryString": false
    });
  }
}

cdk synth

 MyDistDB88FD9A:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        DefaultCacheBehavior:
          Compress: true
          ForwardedValues:
            QueryString: false
          TargetOriginId: dummystack7MyDistOrigin1E2CDA54E
          ViewerProtocolPolicy: allow-all
        Enabled: true
        HttpVersion: http2
        IPV6Enabled: true
        Origins:
          - CustomOriginConfig:
              OriginProtocolPolicy: https-only
            DomainName: www.example.com
            Id: dummystack7MyDistOrigin1E2CDA54E

Let me know if this works for you.

related to #13584 (comment)

@pahud For multiple Behaviors, it's not enough to just modify DefaultCacheBehavior. That's okay, I've already bypassed this in my previous reply.

@github-actions github-actions bot removed the response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. label Aug 14, 2024
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. effort/medium Medium work item – several days of effort p2
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants