File: test_shield.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 (448 lines) | stat: -rw-r--r-- 14,701 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
"""Unit tests for shield-supported APIs."""

import boto3
import pytest
from botocore.exceptions import ClientError

from moto import mock_aws
from tests import aws_verified

# See our Development Tips on writing tests for hints on how to write good tests:
# http://docs.getmoto.org/en/latest/docs/contributing/development_tips/tests.html


@mock_aws
def test_create_protection():
    client = boto3.client("shield", "us-east-1")
    resp = client.create_protection(
        Name="foobar",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
        Tags=[
            {"Key": "key1", "Value": "value1"},
        ],
    )
    assert "ProtectionId" in resp


@mock_aws
def test_create_protection_resource_already_exists():
    client = boto3.client("shield", "us-east-1")
    client.create_protection(
        Name="foobar",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    with pytest.raises(ClientError) as exc:
        client.create_protection(
            Name="foobar",
            ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceAlreadyExistsException"


@aws_verified
@pytest.mark.aws_verified
@pytest.mark.parametrize(
    "arn,error_msg",
    [
        (
            "arn:aws:dynamodb:us-east-1:123456789012:table/foobar",
            "Unrecognized resource 'table' of service 'dynamodb'.",
        ),
        (
            "arn:aws:sns:us-east-2:123456789012:MyTopic",
            "Relative ID must be in the form '<resource>/<id>'.",
        ),
        (
            "arn:aws:ec2:us-east-1:123456789012:security-group/somesg",
            "Unrecognized resource 'security-group' of service 'ec2'.",
        ),
    ],
)
def test_create_protection_invalid_resource(arn, error_msg):
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.create_protection(Name="foobar", ResourceArn=arn)
    err = exc.value.response["Error"]
    assert err["Code"] == "InvalidResourceException"
    assert err["Message"] == error_msg


@mock_aws
def test_protect_elastic_ip(account_id):
    ec2 = boto3.client("ec2", "us-east-1")
    eip = ec2.allocate_address(Domain="vpc")
    eip_allocation_id = eip["AllocationId"]
    eip_arn = f"arn:aws:ec2:us-east-1:{account_id}:eip-allocation/{eip_allocation_id}"

    # Validate that we can protect an EIP
    shield = boto3.client("shield", "us-east-1")
    shield.create_protection(Name="foobar", ResourceArn=eip_arn)


@mock_aws
def test_describe_protection_with_resource_arn():
    client = boto3.client("shield", "us-east-1")
    client.create_protection(
        Name="foobar",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    resp = client.describe_protection(
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar"
    )
    protection = resp["Protection"]
    assert "Id" in protection
    assert "Name" in protection
    assert "ResourceArn" in protection
    assert "ProtectionArn" in protection


@mock_aws
def test_describe_protection_with_protection_id():
    client = boto3.client("shield", "us-east-1")
    protection = client.create_protection(
        Name="foobar",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    protection_id = protection["ProtectionId"]
    resp = client.describe_protection(ProtectionId=protection_id)
    protection = resp["Protection"]
    assert "Id" in protection
    assert "Name" in protection
    assert "ResourceArn" in protection
    assert "ProtectionArn" in protection


@mock_aws
def test_describe_protection_with_both_resource_and_protection_id():
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.describe_protection(
            ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
            ProtectionId="aaaaaaaa-bbbb-cccc-dddd-aaa221177777",
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "InvalidParameterException"


@mock_aws
def test_describe_protection_resource_doesnot_exist():
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.describe_protection(
            ResourceArn="arn:aws:cloudfront::123456789012:distribution/donotexist"
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"


@mock_aws
def test_describe_protection_doesnot_exist():
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.describe_protection(ProtectionId="aaaaaaaa-bbbb-cccc-dddd-aaa221177777")
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"


@mock_aws
def test_list_protections():
    client = boto3.client("shield", "us-east-1")
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    client.create_protection(
        Name="shield2",
        ResourceArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/foobar",
    )
    resp = client.list_protections()
    assert "Protections" in resp
    assert len(resp["Protections"]) == 2


@mock_aws
def test_list_protections_with_only_resource_arn():
    client = boto3.client("shield", "us-east-1")
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    client.create_protection(
        Name="shield2",
        ResourceArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/foobar",
    )
    resp = client.list_protections(
        InclusionFilters={
            "ResourceArns": ["arn:aws:cloudfront::123456789012:distribution/foobar"],
        }
    )
    assert "Protections" in resp
    assert len(resp["Protections"]) == 1


@mock_aws
def test_list_protections_with_only_protection_name():
    client = boto3.client("shield", "us-east-1")
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/foobar",
    )
    resp = client.list_protections(
        InclusionFilters={
            "ProtectionNames": ["shield1"],
        }
    )
    assert "Protections" in resp
    assert len(resp["Protections"]) == 2


@mock_aws
def test_list_protections_with_only_resource_type():
    client = boto3.client("shield", "us-east-1")
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/foobar",
    )
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/my-load-balancer/1234567890123456",
    )
    resp_elb = client.list_protections(
        InclusionFilters={
            "ResourceTypes": ["CLASSIC_LOAD_BALANCER"],
        }
    )
    assert "Protections" in resp_elb
    assert len(resp_elb["Protections"]) == 1
    resp_alb = client.list_protections(
        InclusionFilters={
            "ResourceTypes": ["APPLICATION_LOAD_BALANCER"],
        }
    )
    assert len(resp_alb["Protections"]) == 1


@mock_aws
def test_list_protections_with_resource_arn_and_protection_name():
    client = boto3.client("shield", "us-east-1")
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/foobar",
    )
    resp = client.list_protections(
        InclusionFilters={
            "ResourceArns": ["arn:aws:cloudfront::123456789012:distribution/foobar"],
            "ProtectionNames": ["shield1"],
        }
    )
    assert "Protections" in resp
    assert len(resp["Protections"]) == 1


@mock_aws
def test_list_protections_invalid_resource_arn():
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.list_protections(
            InclusionFilters={
                "ResourceArns": [
                    "arn:aws:cloudfront::123456789012:distribution/foobar",
                    "arn:aws:cloudfront::123456789012:distribution/foobar2",
                ],
            }
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"


@mock_aws
def test_list_protections_invalid_protection_names():
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.list_protections(
            InclusionFilters={
                "ProtectionNames": ["shield1", "shield2"],
            }
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"


@mock_aws
def test_list_protections_invalid_resource_types():
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.list_protections(
            InclusionFilters={
                "ResourceTypes": ["CLOUDFRONT_DISTRIBUTION", "ROUTE_53_HOSTED_ZONE"],
            }
        )
    err = exc.value.response["Error"]
    assert err["Code"] == "ValidationException"


@mock_aws
def test_delete_protection():
    client = boto3.client("shield", "us-east-1")
    protection = client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/foobar",
    )
    client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
    )
    client.delete_protection(ProtectionId=protection["ProtectionId"])
    with pytest.raises(ClientError) as exc:
        client.describe_protection(ProtectionId=protection["ProtectionId"])
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"
    resp = client.list_protections()
    assert len(resp["Protections"]) == 1


@mock_aws
def test_delete_protection_invalid_protection_id():
    client = boto3.client("shield", "us-east-1")
    with pytest.raises(ClientError) as exc:
        client.delete_protection(ProtectionId="aaaaaaaa-bbbb-cccc-dddd-aaa221177777")
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"


@mock_aws
def test_list_tags_for_resource():
    client = boto3.client("shield", "us-east-1")
    protection = client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
        Tags=[
            {"Key": "key1", "Value": "value1"},
            {"Key": "key2", "Value": "value2"},
        ],
    )
    desc_protection = client.describe_protection(
        ProtectionId=protection["ProtectionId"]
    )
    resp = client.list_tags_for_resource(
        ResourceARN=desc_protection["Protection"]["ProtectionArn"]
    )
    assert len(resp["Tags"]) == 2


@mock_aws
def test_tag_resource():
    client = boto3.client("shield", "us-east-1")
    protection = client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
        Tags=[{"Key": "key1", "Value": "value1"}],
    )
    desc_protection = client.describe_protection(
        ProtectionId=protection["ProtectionId"]
    )
    protection_arn = desc_protection["Protection"]["ProtectionArn"]
    client.tag_resource(
        ResourceARN=protection_arn,
        Tags=[
            {"Key": "key2", "Value": "value2"},
        ],
    )
    resp = client.list_tags_for_resource(ResourceARN=protection_arn)
    assert len(resp["Tags"]) == 2


@mock_aws
def test_untag_resource():
    client = boto3.client("shield", "us-east-1")
    protection = client.create_protection(
        Name="shield1",
        ResourceArn="arn:aws:cloudfront::123456789012:distribution/foobar",
        Tags=[
            {"Key": "key1", "Value": "value1"},
            {"Key": "key2", "Value": "value2"},
        ],
    )
    desc_protection = client.describe_protection(
        ProtectionId=protection["ProtectionId"]
    )
    protection_arn = desc_protection["Protection"]["ProtectionArn"]
    client.untag_resource(
        ResourceARN=protection_arn,
        TagKeys=[
            "key1",
        ],
    )
    resp = client.list_tags_for_resource(ResourceARN=protection_arn)
    assert len(resp["Tags"]) == 1
    assert "key2" == resp["Tags"][0]["Key"]


@mock_aws
def test_create_and_describe_subscription():
    client = boto3.client("shield", region_name="eu-west-1")

    # Check exception when subscription does not exist
    with pytest.raises(ClientError) as exc:
        connection = client.describe_subscription()
    err = exc.value.response["Error"]
    assert err["Code"] == "ResourceNotFoundException"
    assert err["Message"] == "The subscription does not exist."

    client.create_subscription()
    connection = client.describe_subscription()
    subscription = connection["Subscription"]
    assert subscription["AutoRenew"] == "ENABLED"
    assert subscription["Limits"][0]["Type"] == "MitigationCapacityUnits"
    assert subscription["Limits"][0]["Max"] == 10000
    assert subscription["ProactiveEngagementStatus"] == "ENABLED"
    assert (
        subscription["SubscriptionLimits"]["ProtectionLimits"][
            "ProtectedResourceTypeLimits"
        ][0]["Type"]
        == "ELASTIC_IP_ADDRESS"
    )
    assert (
        subscription["SubscriptionLimits"]["ProtectionLimits"][
            "ProtectedResourceTypeLimits"
        ][0]["Max"]
        == 100
    )
    assert (
        subscription["SubscriptionLimits"]["ProtectionLimits"][
            "ProtectedResourceTypeLimits"
        ][1]["Type"]
        == "APPLICATION_LOAD_BALANCER"
    )
    assert (
        subscription["SubscriptionLimits"]["ProtectionLimits"][
            "ProtectedResourceTypeLimits"
        ][1]["Max"]
        == 50
    )
    assert (
        subscription["SubscriptionLimits"]["ProtectionGroupLimits"][
            "MaxProtectionGroups"
        ]
        == 20
    )
    assert (
        subscription["SubscriptionLimits"]["ProtectionGroupLimits"][
            "PatternTypeLimits"
        ]["ArbitraryPatternLimits"]["MaxMembers"]
        == 100
    )
    assert subscription["TimeCommitmentInSeconds"] == 31536000