File: models.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (336 lines) | stat: -rw-r--r-- 12,743 bytes parent folder | download
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"""ShieldBackend class with methods for supported APIs."""

import random
import string
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any, Optional

from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel
from moto.moto_api._internal import mock_random
from moto.shield.exceptions import (
    InvalidParameterException,
    InvalidResourceException,
    ResourceAlreadyExistsException,
    ResourceNotFoundException,
    ValidationException,
)
from moto.utilities.arns import parse_arn
from moto.utilities.tagging_service import TaggingService


@dataclass
class Limit:
    type: str
    max: int

    def to_dict(self) -> dict[str, Any]:  # type: ignore
        return {"Type": self.type, "Max": self.max}


@dataclass
class ArbitraryPatternLimits:
    max_members: int

    def to_dict(self) -> dict[str, Any]:  # type: ignore
        return {"MaxMembers": self.max_members}


@dataclass
class PatternTypeLimits:
    arbitrary_pattern_limits: ArbitraryPatternLimits

    def to_dict(self) -> dict[str, Any]:  # type: ignore
        return {"ArbitraryPatternLimits": self.arbitrary_pattern_limits.to_dict()}


@dataclass
class ProtectionGroupLimits:
    max_protection_groups: int
    pattern_type_limits: PatternTypeLimits

    def to_dict(self) -> dict[str, Any]:  # type: ignore
        return {
            "MaxProtectionGroups": self.max_protection_groups,
            "PatternTypeLimits": self.pattern_type_limits.to_dict(),
        }


@dataclass
class ProtectionLimits:
    protected_resource_type_limits: list[Limit]

    def to_dict(self) -> dict[str, Any]:  # type: ignore
        return {
            "ProtectedResourceTypeLimits": [
                limit.to_dict() for limit in self.protected_resource_type_limits
            ]
        }


@dataclass
class SubscriptionLimits:
    protection_limits: ProtectionLimits
    protection_group_limits: ProtectionGroupLimits

    def to_dict(self) -> dict[str, Any]:  # type: ignore
        return {
            "ProtectionLimits": self.protection_limits.to_dict(),
            "ProtectionGroupLimits": self.protection_group_limits.to_dict(),
        }


def default_subscription_limits() -> SubscriptionLimits:
    protection_limits = ProtectionLimits(
        protected_resource_type_limits=[
            Limit(type="ELASTIC_IP_ADDRESS", max=100),
            Limit(type="APPLICATION_LOAD_BALANCER", max=50),
        ]
    )
    protection_group_limits = ProtectionGroupLimits(
        max_protection_groups=20,
        pattern_type_limits=PatternTypeLimits(
            arbitrary_pattern_limits=ArbitraryPatternLimits(max_members=100)
        ),
    )
    return SubscriptionLimits(
        protection_limits=protection_limits,
        protection_group_limits=protection_group_limits,
    )


@dataclass
class Subscription:
    account_id: str
    start_time: datetime = field(default_factory=datetime.now)
    end_time: datetime = field(
        default_factory=lambda: datetime.now() + timedelta(days=365)
    )
    auto_renew: str = field(default="ENABLED")
    limits: list[Limit] = field(
        default_factory=lambda: [Limit(type="MitigationCapacityUnits", max=10000)]
    )
    proactive_engagement_status: str = field(default="ENABLED")
    subscription_limits: SubscriptionLimits = field(
        default_factory=default_subscription_limits
    )
    subscription_arn: str = field(default="")
    time_commitment_in_seconds: int = field(default=31536000)

    def __post_init__(self) -> None:
        if self.subscription_arn == "":
            subscription_id = "".join(random.choices(string.hexdigits[:16], k=12))
            subscription_id_formatted = "-".join(
                [subscription_id[i : i + 4] for i in range(0, 12, 4)]
            )
            self.subscription_arn = f"arn:aws:shield::{self.account_id}:subscription/{subscription_id_formatted}"
        return

    def to_dict(self) -> dict[str, Any]:  # type: ignore
        return {
            "StartTime": self.start_time.strftime("%d/%m/%Y, %H:%M:%S"),
            "EndTime": self.end_time.strftime("%d/%m/%Y, %H:%M:%S"),
            "TimeCommitmentInSeconds": self.time_commitment_in_seconds,
            "AutoRenew": self.auto_renew,
            "Limits": [limit.to_dict() for limit in self.limits],
            "ProactiveEngagementStatus": self.proactive_engagement_status,
            "SubscriptionLimits": self.subscription_limits.to_dict(),
            "SubscriptionArn": self.subscription_arn,
        }


class Protection(BaseModel):
    def __init__(
        self, account_id: str, name: str, resource_arn: str, tags: list[dict[str, str]]
    ):
        self.name = name
        self.resource_arn = resource_arn
        self.protection_id = str(mock_random.uuid4())
        # value is returned in associate_health_check method.
        self.health_check_ids: list[str] = []
        # value is returned in enable_application_layer_automatic_response and disable_application_layer_automatic_response methods.
        self.application_layer_automatic_response_configuration: dict[str, Any] = {}
        self.protection_arn = (
            f"arn:aws:shield::{account_id}:protection/{self.protection_id}"
        )

        resource_types = {
            "cloudfront": "CLOUDFRONT_DISTRIBUTION",
            "globalaccelerator": "GLOBAL_ACCELERATOR",
            "route53": "ROUTE_53_HOSTED_ZONE",
            "ec2": "ELASTIC_IP_ALLOCATION",
        }
        res_type = resource_arn.split(":")[2]
        if res_type == "elasticloadbalancing":
            if resource_arn.split(":")[-1].split("/")[1] == "app":
                self.resource_type = "APPLICATION_LOAD_BALANCER"
            else:
                self.resource_type = "CLASSIC_LOAD_BALANCER"
        else:
            self.resource_type = resource_types[res_type]

    def to_dict(self) -> dict[str, Any]:
        dct = {
            "Id": self.protection_id,
            "Name": self.name,
            "ResourceArn": self.resource_arn,
            "HealthCheckIds": self.health_check_ids,
            "ProtectionArn": self.protection_arn,
            "ApplicationLayerAutomaticResponseConfiguration": self.application_layer_automatic_response_configuration,
        }
        return {k: v for k, v in dct.items() if v}


class ShieldBackend(BaseBackend):
    """Implementation of Shield APIs."""

    def __init__(self, region_name: str, account_id: str):
        super().__init__(region_name, account_id)
        self.protections: dict[str, Protection] = {}
        self.subscription: Optional[Subscription] = None
        self.tagger = TaggingService()

    def validate_resource_arn(self, resource_arn: str) -> None:
        """Raise exception if the resource arn is invalid."""

        # Shield offers protection to only certain services.
        self.valid_resource_types = [
            ("elasticloadbalancing", "loadbalancer"),
            ("cloudfront", "distribution"),
            ("globalaccelerator", "accelerator"),
            ("route53", "hostedzone"),
            ("ec2", "eip-allocation"),
        ]
        arn_parts = parse_arn(resource_arn)
        resource_type = arn_parts.resource_type
        service = arn_parts.service
        if (service, resource_type) not in self.valid_resource_types:
            if resource_type:
                msg = f"Unrecognized resource '{resource_type}' of service '{service}'."
            else:
                msg = "Relative ID must be in the form '<resource>/<id>'."
            raise InvalidResourceException(msg)

    def create_protection(
        self, name: str, resource_arn: str, tags: list[dict[str, str]]
    ) -> str:
        for protection in self.protections.values():
            if protection.resource_arn == resource_arn:
                raise ResourceAlreadyExistsException(
                    "The referenced protection already exists."
                )
        self.validate_resource_arn(resource_arn)
        protection = Protection(
            account_id=self.account_id, name=name, resource_arn=resource_arn, tags=tags
        )
        self.protections[protection.protection_id] = protection
        self.tag_resource(protection.protection_arn, tags)
        return protection.protection_id

    def describe_protection(self, protection_id: str, resource_arn: str) -> Protection:  # type: ignore[return]
        if protection_id and resource_arn:
            msg = "Invalid parameter. You must provide one value, either protectionId or resourceArn, but not both."
            raise InvalidParameterException(msg)

        if resource_arn:
            for protection in self.protections.values():
                if protection.resource_arn == resource_arn:
                    return protection
            raise ResourceNotFoundException("The referenced protection does not exist.")

        if protection_id:
            if protection_id not in self.protections:
                raise ResourceNotFoundException(
                    "The referenced protection does not exist."
                )
            return self.protections[protection_id]

    def list_protections(self, inclusion_filters: dict[str, str]) -> list[Protection]:
        """
        Pagination has not yet been implemented
        """
        resource_protections = []
        name_protections = []
        type_protections = []

        if inclusion_filters:
            resource_arns = inclusion_filters.get("ResourceArns")
            if resource_arns:
                if len(resource_arns) > 1:
                    raise ValidationException(
                        "Error validating the following inputs: inclusionFilters.resourceArns"
                    )
                resource_protections = [
                    protection
                    for protection in self.protections.values()
                    if protection.resource_arn == resource_arns[0]
                ]
            protection_names = inclusion_filters.get("ProtectionNames")
            if protection_names:
                if len(protection_names) > 1:
                    raise ValidationException(
                        "Error validating the following inputs: inclusionFilters.protectionNames"
                    )
                name_protections = [
                    protection
                    for protection in self.protections.values()
                    if protection.name == protection_names[0]
                ]
            resource_types = inclusion_filters.get("ResourceTypes")
            if resource_types:
                if len(resource_types) > 1:
                    raise ValidationException(
                        "Error validating the following inputs: inclusionFilters.resourceTypes"
                    )
                type_protections = [
                    protection
                    for protection in self.protections.values()
                    if protection.resource_type == resource_types[0]
                ]
            try:
                protections = list(
                    set.intersection(
                        *(
                            set(x)
                            for x in [
                                resource_protections,
                                name_protections,
                                type_protections,
                            ]
                            if x
                        )
                    )
                )
            except TypeError:
                protections = []
        else:
            protections = list(self.protections.values())
        return protections

    def delete_protection(self, protection_id: str) -> None:
        if protection_id in self.protections:
            del self.protections[protection_id]
            return
        raise ResourceNotFoundException("The referenced protection does not exist.")

    def list_tags_for_resource(self, resource_arn: str) -> list[dict[str, str]]:
        return self.tagger.list_tags_for_resource(resource_arn)["Tags"]

    def tag_resource(self, resource_arn: str, tags: list[dict[str, str]]) -> None:
        self.tagger.tag_resource(resource_arn, tags)

    def untag_resource(self, resource_arn: str, tag_keys: list[str]) -> None:
        self.tagger.untag_resource_using_names(resource_arn, tag_keys)

    def create_subscription(self) -> None:
        self.subscription = Subscription(account_id=self.account_id)
        return

    def describe_subscription(self) -> Subscription:
        if self.subscription is None:
            raise ResourceNotFoundException("The subscription does not exist.")
        return self.subscription


shield_backends = BackendDict(ShieldBackend, "ec2")