File size: 9,065 Bytes
b40c49c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""

from __future__ import annotations

from collections import UserDict
from typing import TYPE_CHECKING, Any

import regex as re

from cfnlint.helpers import ensure_list

if TYPE_CHECKING:
    from cfnlint.schema import Schema


_all_property_types = [
    "AWS::Amplify::Branch",
    "AWS::Amplify::Domain",
    "AWS::AppSync::DomainName",
    "AWS::AppSync::FunctionConfiguration",
    "AWS::AppSync::Resolver",
    "AWS::AutoScaling::AutoScalingGroup",
    "AWS::Backup::BackupSelection",
    "AWS::Backup::BackupVault",
    "AWS::CodeArtifact::Domain",
    "AWS::CodeArtifact::Repository",
    "AWS::EC2::CapacityReservation",
    "AWS::EC2::Instance",
    "AWS::EC2::SecurityGroup",
    "AWS::EC2::Subnet",
    "AWS::EC2::VPC",
    "AWS::EFS::MountTarget",
    "AWS::EKS::Nodegroup",
    "AWS::ElasticLoadBalancingV2::LoadBalancer",
    "AWS::Events::EventBus",
    "AWS::EventSchemas::Discoverer",
    "AWS::EventSchemas::Registry",
    "AWS::EventSchemas::Schema",
    "AWS::GameLift::GameSessionQueue",
    "AWS::GameLift::MatchmakingConfiguration",
    "AWS::GameLift::MatchmakingRuleSet",
    "AWS::Grafana::Workspace",
    "AWS::Greengrass::ConnectorDefinition",
    "AWS::Greengrass::CoreDefinition",
    "AWS::Greengrass::DeviceDefinition",
    "AWS::Greengrass::FunctionDefinition",
    "AWS::Greengrass::Group",
    "AWS::Greengrass::LoggerDefinition",
    "AWS::Greengrass::ResourceDefinition",
    "AWS::Greengrass::SubscriptionDefinition",
    "AWS::ImageBuilder::Component",
    "AWS::ImageBuilder::ContainerRecipe",
    "AWS::ImageBuilder::DistributionConfiguration",
    "AWS::ImageBuilder::ImagePipeline",
    "AWS::ImageBuilder::ImageRecipe",
    "AWS::ImageBuilder::InfrastructureConfiguration",
    "AWS::Neptune::DBCluster",
    "AWS::RDS::DBInstance",
    "AWS::RDS::DBParameterGroup",
    "AWS::RoboMaker::RobotApplication",
    "AWS::RoboMaker::SimulationApplication",
    "AWS::Route53Resolver::ResolverRule",
    "AWS::Route53Resolver::ResolverRuleAssociation",
    "AWS::S3::AccessPoint",
    "AWS::SageMaker::DataQualityJobDefinition",
    "AWS::SageMaker::ModelBiasJobDefinition",
    "AWS::SageMaker::ModelExplainabilityJobDefinition",
    "AWS::SageMaker::ModelQualityJobDefinition",
    "AWS::SageMaker::MonitoringSchedule",
    "AWS::SNS::Topic",
    "AWS::SQS::Queue",
    "AWS::SSM::Parameter",
    "AWS::StepFunctions::Activity",
]

# Non registry resources that have a difference between readOnlyProperties
# what is supported by GetAtt
_exceptions = {
    "AWS::AppMesh::GatewayRoute": [
        "GatewayRouteName",
        "MeshName",
        "MeshOwner",
        "VirtualGatewayName",
    ],
    "AWS::AppMesh::Mesh": [
        "MeshName",
    ],
    "AWS::AppMesh::Route": [
        "MeshName",
        "MeshOwner",
        "RouteName",
        "VirtualRouterName",
    ],
    "AWS::AppMesh::VirtualGateway": [
        "MeshName",
        "MeshOwner",
        "VirtualGatewayName",
    ],
    "AWS::AppMesh::VirtualNode": [
        "MeshName",
        "MeshOwner",
        "VirtualNodeName",
    ],
    "AWS::AppMesh::VirtualRouter": [
        "MeshName",
        "MeshOwner",
        "VirtualRouterName",
    ],
    "AWS::AppMesh::VirtualService": [
        "MeshName",
        "MeshOwner",
        "VirtualServiceName",
    ],
    "AWS::AppSync::DataSource": [
        "Name",
    ],
    "AWS::Cloud9::EnvironmentEC2": [
        "Name",
    ],
    "AWS::CloudWatch::InsightRule": [
        "RuleName",
    ],
    "AWS::DocDB::DBCluster": [
        "Port",
    ],
    "AWS::Greengrass::ConnectorDefinition": [
        "Name",
    ],
    "AWS::Greengrass::CoreDefinition": [
        "Name",
    ],
    "AWS::Greengrass::DeviceDefinition": [
        "Name",
    ],
    "AWS::Greengrass::FunctionDefinition": [
        "Name",
    ],
    "AWS::Greengrass::Group": [
        "Name",
        "RoleArn",
    ],
    "AWS::Greengrass::LoggerDefinition": [
        "Name",
    ],
    "AWS::Greengrass::ResourceDefinition": [
        "Name",
    ],
    "AWS::Greengrass::SubscriptionDefinition": [
        "Name",
    ],
    "AWS::IoT1Click::Device": [
        "Enabled",
    ],
    "AWS::IoT1Click::Placement": [
        "PlacementName",
        "ProjectName",
    ],
    "AWS::IoT1Click::Project": [
        "ProjectName",
    ],
    "AWS::Kinesis::StreamConsumer": [
        "ConsumerName",
        "StreamARN",
    ],
    "AWS::ManagedBlockchain::Member": [
        "NetworkId",
    ],
    "AWS::MediaConvert::JobTemplate": [
        "Name",
    ],
    "AWS::MediaConvert::Preset": [
        "Name",
    ],
    "AWS::MediaConvert::Queue": [
        "Name",
    ],
    "AWS::MediaLive::Input": [
        "Destinations",
        "Sources",
    ],
    "AWS::OpsWorks::Instance": ["AvailabilityZone"],
    "AWS::OpsWorks::UserProfile": ["SshUsername"],
    "AWS::Route53Resolver::ResolverEndpoint": [
        "Direction",
        "Name",
    ],
    "AWS::SageMaker::CodeRepository": ["CodeRepositoryName"],
    "AWS::SageMaker::Endpoint": [
        "EndpointName",
    ],
    "AWS::SageMaker::EndpointConfig": ["EndpointConfigName"],
    "AWS::SageMaker::Model": ["ModelName"],
    "AWS::SageMaker::NotebookInstance": ["NotebookInstanceName"],
    "AWS::SageMaker::NotebookInstanceLifecycleConfig": [
        "NotebookInstanceLifecycleConfigName"
    ],
    "AWS::SageMaker::Workteam": ["WorkteamName"],
    "AWS::ServiceDiscovery::Service": ["Name"],
    "AWS::Transfer::User": [
        "ServerId",
        "UserName",
    ],
}

_unnamed_unknown_types = (
    "Custom::",
    "AWS::Serverless::",
    "AWS::CloudFormation::CustomResource",
    "Module",
)


class AttributeDict(UserDict):
    def __init__(self, __dict: None = None) -> None:
        super().__init__(__dict)
        self.data: dict[str, str] = {}

    def __getitem__(self, key: str) -> str:
        possible_items = {}
        for k, v in self.data.items():
            if re.fullmatch(k, key) or k == key:
                possible_items[k] = v
        if not possible_items:
            raise KeyError(key)
        longest_match = sorted(possible_items.keys(), key=len)[-1]
        return possible_items[longest_match]

    def get(self, key: str, default: Any = None) -> Any:
        try:
            return self.__getitem__(key)
        except KeyError:
            return default

    def __repr__(self) -> str:
        keys = []
        for k in self.data.keys():
            keys.append(k.replace("\\", ""))
        return f"{keys!r}"


class GetAtts:
    """Class for helping with GetAtt logic"""

    def __init__(self, schema: "Schema") -> None:
        self._attrs = AttributeDict()
        if schema.type_name in _all_property_types:
            for name, value in schema.schema.get("properties", {}).items():
                self._process_schema(value, schema, f"/properties/{name}")
            return
        if schema.type_name in _exceptions:
            for name in _exceptions[schema.type_name]:
                self._attrs[self._pointer_to_attr(f"/properties/{name}")] = (
                    f"/properties/{name}"
                )

        if schema.type_name == "AWS::CloudFormation::Stack":
            self._attrs["Outputs\\..*"] = "/properties/CfnLintStringType"
            return

        if schema.type_name == "AWS::ServiceCatalog::CloudFormationProvisionedProduct":
            for ro_attr in schema.schema.get("readOnlyProperties", []):
                if ro_attr == "/properties/Outputs":
                    self._attrs["Outputs\\..*"] = "/properties/CfnLintStringType"
                else:
                    self._attrs[self._pointer_to_attr(ro_attr)] = ro_attr
            return

        for unnamed_type in _unnamed_unknown_types:
            if schema.type_name.startswith(unnamed_type):
                self._attrs[".*"] = "/properties/CfnLintAllTypes"

        for ro_attr in schema.schema.get("readOnlyProperties", []):
            self._attrs[self._pointer_to_attr(ro_attr)] = ro_attr

    def _pointer_to_attr(self, pointer: str) -> str:
        return ".".join(pointer.split("/")[2:])

    def _process_schema(self, obj: dict[str, Any], schema: "Schema", path: str):
        types = ensure_list(obj.get("type"))
        if "object" in types:
            for prop, value in obj.get("properties", {}).items():
                self._process_schema(value, schema, f"{path}/{prop}")
        elif "array" in types:
            # GetAtt doesn't support going into an array of objects or another array
            # so we only look at an array of strings, etc.
            if obj.get("items", {}).get("type") in ["object", "array"]:
                return
            self._attrs[self._pointer_to_attr(path)] = path
        elif obj.get("$ref"):
            _, obj = schema.resolver.resolve(obj.get("$ref"))
            self._process_schema(obj, schema, path)
        else:
            self._attrs[self._pointer_to_attr(path)] = path

    @property
    def attrs(self) -> AttributeDict:
        return self._attrs