File size: 8,547 Bytes
2c17839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""

from __future__ import annotations

import json
import logging
import os
from collections import deque
from typing import Any, Iterator, Sequence

from update_schemas_manually import Patch, ResourcePatch, build_patches

from cfnlint.schema.resolver import RefResolver

LOGGER = logging.getLogger("cfnlint")


def _descend(instance: Any, keywords: Sequence[str]) -> Iterator[deque[str]]:
    if isinstance(instance, dict):
        for k, v in instance.items():
            if k in keywords:
                yield deque([k])
            for e in _descend(v, keywords):
                if e:
                    yield deque([k, *e])
    if isinstance(instance, list):
        for i, v in enumerate(instance):
            for e in _descend(v, keywords):
                if e:
                    yield deque([str(i), *e])

    return


def _create_subnet_ids_patch(type_name: str, ref: str, resolver: RefResolver):

    _, resolved = resolver.resolve(ref)
    if "$ref" in resolved:
        return _create_subnet_ids_patch(
            type_name=type_name,
            ref=resolved["$ref"],
            resolver=resolver,
        )
    items = resolved.get("items")
    if items:
        if "$ref" in items:
            items_path = items["$ref"]
        else:
            items_path = ref + "/items"

    return [
        Patch(
            values={"format": "AWS::EC2::Subnet.Ids"},
            path=ref[1:],
        ),
        _create_patch(
            {"format": "AWS::EC2::Subnet.Id"},
            items_path,
            resolver=resolver,
        ),
    ]


def _create_security_group_ids_patch(type_name: str, ref: str, resolver: RefResolver):
    if type_name in ["AWS::Pipes::Pipe", "AWS::EC2::NetworkInsightsAnalysis"]:
        return []

    _, resolved = resolver.resolve(ref)
    if "$ref" in resolved:
        return _create_security_group_ids_patch(
            type_name=type_name,
            ref=resolved["$ref"],
            resolver=resolver,
        )
    items = resolved.get("items")
    if items:
        if "$ref" in items:
            items_path = items["$ref"]
        else:
            items_path = ref + "/items"

    return [
        Patch(
            values={"format": "AWS::EC2::SecurityGroup.Ids"},
            path=ref[1:],
        ),
        _create_patch(
            {"format": "AWS::EC2::SecurityGroup.GroupId"},
            items_path,
            resolver=resolver,
        ),
    ]


def _create_security_group_id(type_name: str, ref: str, resolver: RefResolver):
    if type_name in ["AWS::Pipes::Pipe", "AWS::EC2::NetworkInsightsAnalysis"]:
        return []

    _, resolved = resolver.resolve(ref)
    if "$ref" in resolved:
        return _create_security_group_id(
            type_name=type_name,
            ref=resolved["$ref"],
            resolver=resolver,
        )

    return [
        _create_patch(
            {"format": "AWS::EC2::SecurityGroup.GroupId"},
            ref,
            resolver=resolver,
        )
    ]


def _create_security_group_name(type_name: str, ref: str, resolver: RefResolver):

    _, resolved = resolver.resolve(ref)
    if "$ref" in resolved:
        return _create_security_group_name(
            type_name=type_name,
            ref=resolved["$ref"],
            resolver=resolver,
        )

    return [
        _create_patch(
            {"format": "AWS::EC2::SecurityGroup.GroupName"},
            ref,
            resolver=resolver,
        )
    ]


def _create_patch(value: dict[str, str], ref: Sequence[str], resolver: RefResolver):
    _, resolved = resolver.resolve(ref)
    if "$ref" in resolved:
        return _create_patch(value, resolved["$ref"], resolver)

    return Patch(
        values=value,
        path=ref[1:],
    )


_manual_patches = {
    "AWS::EC2::SecurityGroup": [
        Patch(
            values={"format": "AWS::EC2::SecurityGroup.GroupId"},
            path="/properties/GroupId",
        ),
        Patch(
            values={"format": "AWS::EC2::SecurityGroup.GroupName"},
            path="/properties/GroupName",
        ),
    ],
    "AWS::EC2::SecurityGroupIngress": [
        Patch(
            values={"format": "AWS::EC2::SecurityGroup.GroupId"},
            path="/properties/GroupId",
        ),
    ],
    "AWS::EC2::SecurityGroupEgress": [
        Patch(
            values={"format": "AWS::EC2::SecurityGroup.GroupId"},
            path="/properties/GroupId",
        ),
    ],
}


def main():
    schema_dir = os.path.join("src/cfnlint/data/schemas/providers/us_east_1")
    patches = []
    for root, dirs, files in os.walk(schema_dir, topdown=False):
        for file in files:
            if file in [".DS_Store"]:
                continue

            if file.startswith("__init__"):
                continue

            obj = json.load(open(os.path.join(root, file)))

            resolver = RefResolver.from_schema(obj)
            resource_type = obj["typeName"]

            resource_patches = []
            if resource_type in _manual_patches:
                resource_patches.extend(_manual_patches[resource_type])

            for path in _descend(obj, ["VpcId", "VPCId"]):
                if path[-2] == "properties":
                    resource_patches.append(
                        _create_patch(
                            value={"format": "AWS::EC2::VPC.Id"},
                            ref="#/" + "/".join(path),
                            resolver=resolver,
                        )
                    )

            for path in _descend(obj, ["ImageId", "AmiId"]):
                if path[-2] == "properties":
                    resource_patches.append(
                        _create_patch(
                            value={"format": "AWS::EC2::Image.Id"},
                            ref="#/" + "/".join(path),
                            resolver=resolver,
                        )
                    )

            for path in _descend(obj, ["Subnets"]):
                if path[-2] == "properties":
                    resource_patches.extend(
                        _create_subnet_ids_patch(
                            resource_type, "#/" + "/".join(path), resolver
                        )
                    )

            for path in _descend(obj, ["SubnetId"]):
                if path[-2] == "properties":
                    resource_patches.append(
                        _create_patch(
                            value={"format": "AWS::EC2::Subnet.Id"},
                            ref="#/" + "/".join(path),
                            resolver=resolver,
                        )
                    )

            for path in _descend(obj, ["SecurityGroupIds", "SecurityGroups"]):
                if path[-2] == "properties":
                    resource_patches.extend(
                        _create_security_group_ids_patch(
                            resource_type, "#/" + "/".join(path), resolver
                        )
                    )

            for path in _descend(
                obj,
                [
                    "DefaultSecurityGroup",
                    "SourceSecurityGroupId",
                    "DestinationSecurityGroupId",
                    "SecurityGroup",
                    "SecurityGroupId",
                ],
            ):
                if path[-2] == "properties":
                    resource_patches.extend(
                        _create_security_group_id(
                            resource_type, "#/" + "/".join(path), resolver
                        )
                    )

            for path in _descend(
                obj,
                [
                    "SourceSecurityGroupName",
                ],
            ):
                if path[-2] == "properties":
                    resource_patches.extend(
                        _create_security_group_name(
                            resource_type, "#/" + "/".join(path), resolver
                        )
                    )

            if resource_patches:
                patches.append(
                    ResourcePatch(
                        resource_type=resource_type,
                        patches=resource_patches,
                    )
                )

    build_patches(patches, "format.json")
    # specs = read_specs()


if __name__ == "__main__":
    try:
        main()
    except (ValueError, TypeError) as e:
        print(e)
        LOGGER.error(ValueError)