aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.61k stars 3.91k forks source link

core: CfnResource.isCfnResource is too permissive #30473

Open michanto opened 4 months ago

michanto commented 4 months ago

Describe the bug

I created a construct class with a cfnResourceType property. I use that type to search for a CfnResource under the parent of that construct. But my non-CfnResource class is recognized as a CfnResource by the CDK because it has a cfnResourceType property! Wrong!

Expected Behavior

public static isCfnResource(x: any): x is CfnResource {
    return CfnElement.isCfnElement(x) && x.cfnResourceType !== undefined;
  }

That would be a lot better because isCfnElement has an RTTI symbol property.

Current Behavior

public static isCfnResource(x: any): x is CfnResource {
    return x !== null && typeof(x) === 'object' && x.cfnResourceType !== undefined;
  }

Reproduction Steps

class BucketHelperClass extends Construct {
  readonly cfnResourceType = CfnBucket.CFN_RESOURCE_TYPE_NAME
}
let helper = new BucketHelperClass(new App(), "Helper")
if (CfnResource.isCfnResource(helper)) {
  throw new Error('No it is not a CfnResource!');
}

Possible Solution

Either this:

public static isCfnResource(x: any): x is CfnResource {
    return CfnElement.isCfnElement(x) && x.cfnResourceType !== undefined;
  }

Or maybe:

const CFN_RESOURCE_SYMBOL = Symbol.for('@aws-cdk/core.CfnResource');

Additional Information/Context

When I try to synthesize a stack with a fake CfnResource, I get the following error:

[CDK] TypeError: source.addDependency is not a function

CDK CLI Version

2.120.0 (build 58b90c4)

Framework Version

No response

Node.js Version

10.2.5

OS

MacOS

Language

TypeScript

Language Version

No response

Other information

No response

pahud commented 4 months ago

Agree. But looking at this discussion

https://github.com/aws/aws-cdk/pull/28001#pullrequestreview-1731529704

What do you think about it? @tmokmss @go-to-k ?

michanto commented 4 months ago

Both could be supported by just adding isCfnElement to the existing?

Or you could adopt my Construct RTTI class

tmokmss commented 4 months ago

I agree that the current state is undesirable and should be fixed. However, I can't think of a way to make sure it's not a breaking change. I think the proposed change will not cause any problem, but there are so many cdk users in the world...

go-to-k commented 4 months ago

I have the same opinion with @tmokmss . (But I think it's probably OK.)

michanto commented 4 months ago

Even if you decide not to fix isCfnResource itself, you should fix the addDependency error on synthesis. That's definitely a bug.