Repository navigation
Expand file tree
/
Copy pathtest_c7nlib.py
More file actions
1582 lines (1362 loc) · 56.7 KB
/
Copy pathtest_c7nlib.py
File metadata and controls
1582 lines (1362 loc) · 56.7 KB
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-Copyright: Copyright (c) Capital One Services, LLC
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
"""
Test the functions for C7N Compatibility.
There are three collections of tests.
- Isolated Unit Tests without a dependency on the ``CELFilter`` class.
- Integration Tests which depend on the ``celfilter_instance`` fixture.
These tests are essential for making sure we have C7N compatibility.
"""
import datetime
import io
import zlib
from types import SimpleNamespace
from unittest.mock import Mock, call, sentinel
import pytest
import celpy
import celpy.adapter
import celpy.c7nlib
import celpy.celtypes
def test_key():
tags = celpy.json_to_cel(
[
{"Key": "Target", "Value": "First"},
{"Key": "Target", "Value": "Second"},
]
)
assert celpy.c7nlib.key(tags, celpy.celtypes.StringType("Target")) == "First"
assert celpy.c7nlib.key(tags, celpy.celtypes.StringType("NotFound")) is None
def test_glob():
assert celpy.c7nlib.glob("c7nlib.py", "*.py")
assert not celpy.c7nlib.glob("c7nlib.py", "*.pyc")
def test_difference():
assert celpy.c7nlib.difference(["a", "b"], ["b", "c"])
assert not celpy.c7nlib.difference(["b"], ["b", "c"])
def test_intersect():
assert celpy.c7nlib.intersect(["a", "b"], ["b", "c"])
assert not celpy.c7nlib.intersect(["a", "b"], ["c"])
def test_normalize():
assert celpy.c7nlib.normalize(" HeLlO WoRlD ") == "hello world"
assert celpy.c7nlib.normalize(" HeLlO WoRlD ") != "HeLlO WoRlD"
def test_unique_size():
assert celpy.c7nlib.unique_size(["a", "b", "b", "c"]) == 3
def test_parse_cidr():
assert len(list(celpy.c7nlib.parse_cidr("192.168.100.0/22").hosts())) == 1022
assert celpy.c7nlib.parse_cidr("192.168.100.0") in celpy.c7nlib.parse_cidr(
"192.168.100.0/22"
)
assert celpy.c7nlib.parse_cidr("192.168.100.0").packed == bytes([192, 168, 100, 0])
assert celpy.c7nlib.parse_cidr("localhost") is None
assert not celpy.c7nlib.parse_cidr("localhost") in celpy.c7nlib.parse_cidr(
"192.168.100.0/22"
)
assert celpy.c7nlib.parse_cidr("192.168.100.0/22") in celpy.c7nlib.parse_cidr(
"192.168.100.0/22"
)
def test_size_parse_cidr():
assert celpy.c7nlib.size_parse_cidr("192.168.100.0/22") == 22
assert celpy.c7nlib.size_parse_cidr("localhost") is None
def test_version():
assert celpy.c7nlib.version("2.7.18") < celpy.c7nlib.version("2.8")
assert celpy.c7nlib.version("2.6") < celpy.c7nlib.version("2.7.18")
assert celpy.c7nlib.version("2.7") == celpy.c7nlib.version("2.7")
assert not (celpy.c7nlib.version("2.7") == ">=2.6")
value_from_examples = [
(
".txt",
"text",
b"data\n",
celpy.celtypes.ListType([celpy.celtypes.StringType("data")]),
),
(
".txt",
"gzip",
zlib.compress(b"data\n"),
celpy.celtypes.ListType([celpy.celtypes.StringType("data")]),
),
(
".json",
"text",
b'{"key": "data"}\n',
celpy.celtypes.MapType(
{celpy.celtypes.StringType("key"): celpy.celtypes.StringType("data")}
),
),
(
".ldjson",
"text",
b'{"row": 1}\n{"row": 2}\n',
celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{celpy.celtypes.StringType("row"): celpy.celtypes.IntType(1)}
),
celpy.celtypes.MapType(
{celpy.celtypes.StringType("row"): celpy.celtypes.IntType(2)}
),
]
),
),
(
".csv",
"text",
(b"row,value\r\n1,42\r\n"),
celpy.celtypes.ListType(
[
celpy.celtypes.ListType(
[
celpy.celtypes.StringType("row"),
celpy.celtypes.StringType("value"),
]
),
celpy.celtypes.ListType(
[
celpy.celtypes.StringType("1"),
celpy.celtypes.StringType("42"),
]
),
]
),
),
(
".csv2dict",
"text",
(b"row,value\r\n1,42\r\n"),
celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("row"): celpy.celtypes.StringType(
"1"
),
celpy.celtypes.StringType("value"): celpy.celtypes.StringType(
"42"
),
}
),
]
),
),
]
@pytest.fixture(params=value_from_examples)
def mock_urllib_request(monkeypatch, request):
suffix, encoding, raw_bytes, expected = request.param
urllib_request = Mock(
Request=Mock(return_value=Mock()),
urlopen=Mock(
return_value=Mock(
info=Mock(return_value=Mock(get=Mock(return_value=encoding))),
read=Mock(return_value=raw_bytes),
)
),
)
monkeypatch.setattr(celpy.c7nlib.urllib, "request", urllib_request)
mock_os = Mock(splitext=Mock(return_value=("path", suffix)))
monkeypatch.setattr(celpy.c7nlib.os, "path", mock_os)
return urllib_request, expected
def test_value_from(mock_urllib_request):
urllib_request, expected = mock_urllib_request
data = celpy.c7nlib.value_from(sentinel.URL)
assert urllib_request.Request.mock_calls == [
call(sentinel.URL, headers={"Accept-Encoding": "gzip"})
]
assert expected == data
def test_value_from_bad_format():
with pytest.raises(ValueError):
celpy.c7nlib.value_from(sentinel.URL, format="nope")
jmes_path_examples = [
({"foo": {"bar": "baz"}}, "foo.bar", "baz"),
({"foo": {"bar": ["one", "two"]}}, "foo.bar[0]", "one"),
(
{"foo": {"bar": [{"name": "one"}, {"name": "two"}]}},
"foo.bar[*].name",
["one", "two"],
),
]
@pytest.fixture(params=jmes_path_examples)
def doc_path_expected(request):
json_doc, path, expected = request.param
return (
celpy.adapter.json_to_cel(json_doc),
celpy.celtypes.StringType(path),
expected,
)
def test_jmes_path(doc_path_expected):
doc, path, expected = doc_path_expected
actual = celpy.c7nlib.jmes_path(doc, path)
assert expected == actual
@pytest.fixture(params=jmes_path_examples)
def doclist_path_expected(request):
json_doc, path, expected = request.param
return (
celpy.celtypes.ListType([celpy.adapter.json_to_cel(json_doc)]),
celpy.celtypes.StringType(path),
[expected],
)
def test_jmes_path_map(doclist_path_expected):
doclist, path, expected_list = doclist_path_expected
actual_list = celpy.c7nlib.jmes_path_map(doclist, path)
assert expected_list == actual_list
def test_present():
assert celpy.c7nlib.present(celpy.celtypes.StringType("yes"))
assert not celpy.c7nlib.present(celpy.celtypes.StringType(""))
assert not celpy.c7nlib.present(None)
def test_absent():
assert not celpy.c7nlib.absent(celpy.celtypes.StringType("no"))
assert celpy.c7nlib.absent(celpy.celtypes.StringType(""))
assert celpy.c7nlib.absent(None)
def test_marked_key_good():
tags_good = celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("Key"): celpy.celtypes.StringType(
"c7n-tag-compliance"
),
celpy.celtypes.StringType("Value"): celpy.celtypes.StringType(
"hello:stop@2020-09-10"
),
}
),
]
)
doc = celpy.c7nlib.marked_key(
tags_good, celpy.celtypes.StringType("c7n-tag-compliance")
)
assert doc.get(celpy.celtypes.StringType("message")) == celpy.celtypes.StringType(
"hello"
)
assert doc.get(celpy.celtypes.StringType("action")) == celpy.celtypes.StringType(
"stop"
)
assert doc.get(
celpy.celtypes.StringType("action_date")
) == celpy.celtypes.TimestampType("2020-09-10")
def test_marked_key_missing():
tags_good = celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("Key"): celpy.celtypes.StringType(
"ASSET"
),
celpy.celtypes.StringType("Value"): celpy.celtypes.StringType(
"hello:stop@2020-09-10"
),
}
),
]
)
doc = celpy.c7nlib.marked_key(
tags_good, celpy.celtypes.StringType("c7n-tag-compliance")
)
assert doc is None
def test_marked_key_wrong_format():
tags_good = celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("Key"): celpy.celtypes.StringType(
"c7n-tag-compliance"
),
celpy.celtypes.StringType("Value"): celpy.celtypes.StringType(
"nope:"
),
}
),
]
)
doc = celpy.c7nlib.marked_key(
tags_good, celpy.celtypes.StringType("c7n-tag-compliance")
)
assert doc is None
def test_arn_split():
f1 = "arn:partition-1:service-1:region-1:account-id-1:resource-id-1"
assert celpy.c7nlib.arn_split(f1, "partition") == "partition-1"
assert celpy.c7nlib.arn_split(f1, "service") == "service-1"
assert celpy.c7nlib.arn_split(f1, "region") == "region-1"
assert celpy.c7nlib.arn_split(f1, "account-id") == "account-id-1"
assert celpy.c7nlib.arn_split(f1, "resource-id") == "resource-id-1"
f2 = "arn:partition-2:service-2:region-2:account-id-2:resource-type-2/resource-id-2"
assert celpy.c7nlib.arn_split(f2, "partition") == "partition-2"
assert celpy.c7nlib.arn_split(f2, "service") == "service-2"
assert celpy.c7nlib.arn_split(f2, "region") == "region-2"
assert celpy.c7nlib.arn_split(f2, "account-id") == "account-id-2"
assert celpy.c7nlib.arn_split(f2, "resource-id") == "resource-type-2/resource-id-2"
f3 = "arn:partition-3:service-3:region-3:account-id-3:resource-type-3:resource-id-3"
assert celpy.c7nlib.arn_split(f3, "partition") == "partition-3"
assert celpy.c7nlib.arn_split(f3, "service") == "service-3"
assert celpy.c7nlib.arn_split(f3, "region") == "region-3"
assert celpy.c7nlib.arn_split(f3, "account-id") == "account-id-3"
assert celpy.c7nlib.arn_split(f3, "resource-type") == "resource-type-3"
assert celpy.c7nlib.arn_split(f3, "resource-id") == "resource-id-3"
with pytest.raises(ValueError):
celpy.c7nlib.arn_split("http://server.name:port/path/to/resource", "partition")
@pytest.fixture
def mock_manager():
datapoints = [{"Average": str(sentinel.average)}]
health_events = [
{
"category": "issue",
"code": "AWS_EC2_SYSTEM_MAINTENANCE_EVENT",
"service": "EC2",
}
]
cloudwatch_client = Mock(
name="cloudwatch_client",
get_metric_statistics=Mock(return_value={"Datapoints": datapoints}),
)
ec2_client = Mock(
name="ec2_client",
describe_flow_logs=Mock(
return_value={"FlowLogs": [{"ResourceId": "i-123456789"}]}
),
describe_snapshot_attribute=Mock(
return_value=[str(sentinel.snashot_permission)]
),
)
elb_client = Mock(
name="elb_client",
describe_load_balancer_attributes=Mock(
return_value={"LoadBalancerAttributes": [{"Enabled": True}]}
),
)
elbv2_client = Mock(
name="elbv2_client",
describe_load_balancer_attributes=Mock(
return_value={
"Attributes": [
{"Key": "access_logs.s3.enabled", "Value": "true"},
{"Key": "boolean", "Value": "false"},
{"Key": "integer", "Value": "42"},
{"Key": "string", "Value": "other"},
]
}
),
)
health_client = Mock(
name="health_client",
describe_events=Mock(return_value={"events": health_events}),
)
kms_client = Mock(
name="kms_client",
get_key_policy=Mock(return_value={"Policy": str(sentinel.policy)}),
)
logs_client = Mock(
name="logs_cient",
describe_subscription_filters=Mock(
return_value={"subscriptionFilters": [str(sentinel.subscription_filter)]}
),
)
shield_client = Mock(
name="shield_client",
describe_subscription=Mock(return_value={"Subscription": str(sentinel.shield)}),
)
clients = {
"ec2": ec2_client,
"cloudwatch": cloudwatch_client,
"elb": elb_client,
"elbv2": elbv2_client,
"health": health_client,
"kms": kms_client,
"logs": logs_client,
"shield": shield_client,
}
mock_session = Mock(
name="mock_session instance",
client=Mock(side_effect=lambda name, region_name=None: clients.get(name)),
)
asg_resource_manager = Mock(
name="asg_resource_manager",
resources=Mock(
return_value=[
{
"LaunchConfigurationName": str(sentinel.asg_launch_config_name),
"AutoScalingGroupName": str(sentinel.asg_name),
},
]
),
)
rds_resource_manager = Mock(
name="rds_resource_manager",
resources=Mock(
return_value=[
{
"DBSubnetGroupName": str(sentinel.rds_subnet_group_name),
"DBInstanceIdentifier": str(sentinel.rds_instance_identifier),
},
]
),
)
waf_resource_manager = Mock(
name="waf_resource_manager",
resources=Mock(
return_value=[
{"Name": str(sentinel.waf_name), "WebACLId": str(sentinel.waf_acl_id)}
]
),
)
resource_managers = {
"asg": asg_resource_manager,
"rds": rds_resource_manager,
"waf": waf_resource_manager,
}
manager = Mock(
name="mock_manager",
session_factory=Mock(return_value=mock_session),
get_model=Mock(
return_value=Mock(dimension="InstanceId", id="InstanceId", service="ec2")
),
get_resource_manager=Mock(side_effect=lambda name: resource_managers.get(name)),
retry=Mock(side_effect=lambda f, **kwargs: f(**kwargs)),
resource_type="ec2",
config=Mock(
account_id="123456789012",
region="us-east-1",
),
data={"resource": "ec2"},
)
return locals()
@pytest.fixture
def mock_filter_class():
"""
This CELFilter class demonstrates *all* the features required for the refactored C7N.
"""
mock_parser = Mock(
name="Mock c7n.filters.offhours.ScheduleParser instance",
parse=Mock(
return_value={
"off": [
{"days": [1, 2, 3, 4, 5], "hour": 21},
{"days": [0], "hour": 18},
],
"on": [{"days": [1, 2, 3, 4, 5], "hour": 6}, {"days": [0], "hour": 10}],
"tz": "pt",
}
),
)
def get_related_results(resources):
result = []
for r in resources:
if r.get("ResourceType") == "ec2":
result.append(str(sentinel.sg_id))
elif r.get("ResourceType") == "ebs":
result.append({"AliasName": str(sentinel.alias_name)})
else:
raise NotImplementedError(f"No get_related() for {resources}")
return result
# Class foundation from C7n.
class Filter:
"""Mock of c7n.filters.core.Filter"""
def __init__(self, data, manager):
self.data = data
self.manager = manager
# Mixins from C7N.
class InstanceImageMixin:
get_instance_image = Mock(
return_value={
"CreationDate": "2020-09-10T11:12:13Z",
"Name": str(sentinel.name),
}
)
class RelatedResourceMixin:
get_related_ids = Mock(return_value=[str(sentinel.sg_id)])
get_related_sgs = Mock(return_value=[str(sentinel.sg)])
get_related_subnets = Mock(return_value=[str(sentinel.subnet)])
get_related_nat_gateways = Mock(return_value=[str(sentinel.nat_gateway)])
get_related_igws = Mock(return_value=[str(sentinel.igw)])
get_related_security_configs = Mock(return_value=[str(sentinel.sec_config)])
get_related_vpc = Mock(return_value=[str(sentinel.vpc)])
get_related_kms_keys = Mock(return_value=[str(sentinel.kms_key)])
get_related = Mock(side_effect=get_related_results)
class CredentialReportMixin:
get_credential_report = Mock(return_value=str(sentinel.credential))
class ResourceKmsKeyAliasMixin:
get_matching_aliases = Mock(return_value=[str(sentinel.kms_alias)])
class CrossAccountAccessMixin:
get_accounts = Mock(return_value=[str(sentinel.account)])
get_vpcs = Mock(return_value=[str(sentinel.vpc)])
get_vpces = Mock(return_value=[str(sentinel.vpce)])
get_orgids = Mock(return_value=[str(sentinel.orgid)])
get_resource_policy = Mock(return_value=[str(sentinel.policy)])
class SNSCrossAccountMixin:
get_endpoints = Mock(return_value=[str(sentinel.endpoint)])
get_protocols = Mock(return_value=[str(sentinel.protocol)])
class ImagesUnusedMixin:
_pull_ec2_images = Mock(return_value=set([str(sentinel.ec2_image_id)]))
_pull_asg_images = Mock(return_value=set())
class SnapshotUnusedMixin:
_pull_asg_snapshots = Mock(return_value=set([str(sentinel.asg_snapshot_id)]))
_pull_ami_snapshots = Mock(return_value=set())
class IamRoleUsageMixin:
service_role_usage = Mock(return_value=[str(sentinel.iam_role)])
instance_profile_usage = Mock(return_value=[str(sentinel.iam_profile)])
class SGUsageMixin:
scan_groups = Mock(return_value=[str(sentinel.scan_group)])
class IsShieldProtectedMixin:
get_type_protections = Mock(
return_value=[{"ResourceArn": str(sentinel.shield)}]
)
class ShieldEnabledMixin:
account_shield_subscriptions = Mock(return_value=[str(sentinel.shield)])
class CELFilter(
InstanceImageMixin,
RelatedResourceMixin,
CredentialReportMixin,
ResourceKmsKeyAliasMixin,
CrossAccountAccessMixin,
SNSCrossAccountMixin,
ImagesUnusedMixin,
SnapshotUnusedMixin,
IamRoleUsageMixin,
SGUsageMixin,
IsShieldProtectedMixin,
ShieldEnabledMixin,
Filter,
):
"""Mocked subclass of c7n.filters.core.Filter with Mocked mixins."""
def __init__(self, data, manager):
super().__init__(data, manager)
assert self.data["type"].lower() == "cel"
self.expr = self.data["expr"]
self.parser = mock_parser
return CELFilter
@pytest.fixture
def celfilter_instance(mock_filter_class, mock_manager):
"""
The mocked CELFilter instance for all of the c7nlib integration tests.
"""
# A place-holder used only for initialization.
mock_policy_filter_source = {"type": "cel", "expr": "1+1==2"}
# The mock for the ``CELFilter`` instance C7N must provide.
the_filter = mock_filter_class(mock_policy_filter_source, mock_manager["manager"])
return locals()
def test_image_age_good(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
resource = celpy.celtypes.MapType({})
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc = celpy.c7nlib.image(resource)
assert doc.get(
celpy.celtypes.StringType("CreationDate")
) == celpy.celtypes.TimestampType("2020-09-10T11:12:13Z")
def test_image_age_missing(celfilter_instance, mock_manager):
mock_filter = celfilter_instance["the_filter"]
mock_filter.get_instance_image = Mock(return_value=None)
resource = celpy.celtypes.MapType({})
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc = celpy.c7nlib.image(resource)
assert doc.get(
celpy.celtypes.StringType("CreationDate")
) == celpy.celtypes.TimestampType("2000-01-01T01:01:01.000Z")
def test_get_raw_metrics(celfilter_instance, mock_manager):
mock_filter = celfilter_instance["the_filter"]
datapoints = mock_manager["datapoints"]
now = celpy.celtypes.TimestampType("2000-01-01T01:01:01.000Z")
resource = celpy.celtypes.MapType({})
request = celpy.celtypes.MapType(
{
celpy.celtypes.StringType("Namespace"): celpy.celtypes.StringType(
"AWS/EC2"
),
celpy.celtypes.StringType("MetricName"): celpy.celtypes.StringType(
"CPUUtilization"
),
celpy.celtypes.StringType("Dimensions"): celpy.celtypes.MapType(
{
celpy.celtypes.StringType("Name"): celpy.celtypes.StringType(
"InstanceId"
),
celpy.celtypes.StringType("Value"): celpy.celtypes.StringType(
"i-1234567890abcdef0"
),
}
),
celpy.celtypes.StringType("Statistics"): celpy.celtypes.ListType(
[celpy.celtypes.StringType("Average")]
),
celpy.celtypes.StringType("StartTime"): now
- celpy.celtypes.DurationType("4d"),
celpy.celtypes.StringType("EndTime"): now,
celpy.celtypes.StringType("Period"): celpy.celtypes.DurationType("86400s"),
}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc = celpy.c7nlib.get_raw_metrics(request)
assert doc == celpy.json_to_cel(datapoints)
def test_get_metrics(celfilter_instance, mock_manager):
"""
Two approaches possible. (1) mock :func:`get_raw_metrics`. (2) provide mocks to support
:func:`get_raw_metrics`. We use approach 2 in case the implmentation of `get_metrics`
is changed.
"""
mock_filter = celfilter_instance["the_filter"]
datapoints = mock_manager["datapoints"]
now = celpy.celtypes.TimestampType("2000-01-01T01:01:01.000Z")
resource = celpy.celtypes.MapType({"InstanceId": "i-123456789012"})
request = celpy.celtypes.MapType(
{
celpy.celtypes.StringType("MetricName"): celpy.celtypes.StringType(
"CPUUtilization"
),
celpy.celtypes.StringType("Statistic"): celpy.celtypes.StringType(
"Average"
),
celpy.celtypes.StringType("StartTime"): now
- celpy.celtypes.DurationType("4d"),
celpy.celtypes.StringType("EndTime"): now,
celpy.celtypes.StringType("Period"): celpy.celtypes.DurationType("86400s"),
}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc = celpy.c7nlib.get_metrics(resource, request)
assert doc == celpy.celtypes.ListType(
[celpy.celtypes.StringType("sentinel.average")]
)
def test_get_related_ids(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
resource = celpy.celtypes.MapType({})
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc = celpy.c7nlib.get_related_ids(resource)
assert doc == celpy.celtypes.ListType(
[
celpy.celtypes.StringType("sentinel.sg_id"),
]
)
def test_security_group(celfilter_instance):
mock_sg_1 = dict(
SecurityGroupId="sg-12345678",
SecurityGroupName="SomeName",
)
mock_sg_2 = dict(
SecurityGroupId="sg-23456789",
SecurityGroupName="AnotherName",
)
mock_filter = celfilter_instance["the_filter"]
mock_filter.get_related = Mock(return_value=[mock_sg_1, mock_sg_2])
resource = celpy.celtypes.MapType(
{celpy.celtypes.StringType("ResourceType"): celpy.celtypes.StringType("sg")}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc = celpy.c7nlib.security_group(resource)
assert doc == celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{
celpy.celtypes.StringType(
"SecurityGroupId"
): celpy.celtypes.StringType("sg-12345678"),
celpy.celtypes.StringType(
"SecurityGroupName"
): celpy.celtypes.StringType("SomeName"),
}
),
celpy.celtypes.MapType(
{
celpy.celtypes.StringType(
"SecurityGroupId"
): celpy.celtypes.StringType("sg-23456789"),
celpy.celtypes.StringType(
"SecurityGroupName"
): celpy.celtypes.StringType("AnotherName"),
}
),
]
)
def test_subnet(celfilter_instance):
mock_subnet = dict(
SubnetID="subnet-12345678",
SubnetArn="arn:aws:asg:us-east-1:123456789012:subnet-12345678",
)
mock_filter = celfilter_instance["the_filter"]
mock_filter.get_related = Mock(return_value=mock_subnet)
resource = celpy.celtypes.MapType({})
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc = celpy.c7nlib.subnet(resource)
assert doc.get(celpy.celtypes.StringType("SubnetID")) == celpy.celtypes.StringType(
"subnet-12345678"
)
def test_flow_logs(celfilter_instance):
"""
Test :func:`c7nlib.flow_logs`.
.. todo:: Refactor :func:`c7nlib.flow_logs` -- it exposes too much implementation detail.
"""
mock_filter = celfilter_instance["the_filter"]
resource_1 = celpy.celtypes.MapType(
{
celpy.celtypes.StringType("InstanceId"): celpy.celtypes.StringType(
"i-123456789"
)
}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc_1 = celpy.c7nlib.flow_logs(resource_1)
assert doc_1 == [{"ResourceId": "i-123456789"}]
resource_2 = celpy.celtypes.MapType(
{
celpy.celtypes.StringType("InstanceId"): celpy.celtypes.StringType(
"i-111111111"
)
}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc_2 = celpy.c7nlib.flow_logs(resource_2)
assert doc_2 == []
def test_vpc(celfilter_instance):
vpc_1 = {"ResourceId": "vpc-123456789", "More": "Details"}
mock_filter = celfilter_instance["the_filter"]
mock_filter.get_related = Mock(return_value=vpc_1)
resource_1 = celpy.celtypes.MapType(
{
celpy.celtypes.StringType("InstanceId"): celpy.celtypes.StringType(
"vpc-123456789"
)
}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc_1 = celpy.c7nlib.vpc(resource_1)
assert doc_1 == vpc_1
def test_subst(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
with celpy.c7nlib.C7NContext(filter=mock_filter):
assert celpy.c7nlib.subst("this") == "this"
assert celpy.c7nlib.subst("this {account_id}") == "this 123456789012"
def test_credentials(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
resource_1 = celpy.celtypes.MapType(
{
celpy.celtypes.StringType("ResourceType"): celpy.celtypes.StringType(
"iam-user"
)
}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc_1 = celpy.c7nlib.credentials(resource_1)
assert doc_1 == celpy.adapter.json_to_cel(str(sentinel.credential))
def test_kms_alias(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
resource_1 = celpy.celtypes.MapType(
{celpy.celtypes.StringType("ResourceType"): celpy.celtypes.StringType("rds")}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc_1 = celpy.c7nlib.kms_alias(resource_1)
assert doc_1 == celpy.adapter.json_to_cel([str(sentinel.kms_alias)])
def test_kms_key(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
resource_1 = celpy.celtypes.MapType(
{celpy.celtypes.StringType("ResourceType"): celpy.celtypes.StringType("ebs")}
)
with celpy.c7nlib.C7NContext(filter=mock_filter):
doc_1 = celpy.c7nlib.kms_key(resource_1)
assert doc_1 == celpy.adapter.json_to_cel([{"AliasName": str(sentinel.alias_name)}])
def test_C7N_resource_schedule(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
ec2_doc = {
"ResourceType": "ec2",
"Tags": [
{
"key": "maid_offhours",
"value": "off=[(M-F,21),(U,18)];on=[(M-F,6),(U,10)];tz=pt",
}
],
}
with celpy.c7nlib.C7NContext(filter=mock_filter):
other_tz_names = {
"et": "US/Eastern",
"pt": "US/Pacific",
}
celpy.celtypes.TimestampType.TZ_ALIASES.update(other_tz_names)
schedule = celpy.c7nlib.resource_schedule(ec2_doc)
assert schedule == {
celpy.celtypes.StringType("off"): celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("days"): celpy.celtypes.ListType(
[
celpy.celtypes.IntType(1),
celpy.celtypes.IntType(2),
celpy.celtypes.IntType(3),
celpy.celtypes.IntType(4),
celpy.celtypes.IntType(5),
]
),
celpy.celtypes.StringType("hour"): celpy.celtypes.IntType(21),
celpy.celtypes.StringType("tz"): celpy.celtypes.StringType(
"pt"
),
}
),
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("days"): celpy.celtypes.ListType(
[celpy.celtypes.IntType(0)]
),
celpy.celtypes.StringType("hour"): celpy.celtypes.IntType(18),
celpy.celtypes.StringType("tz"): celpy.celtypes.StringType(
"pt"
),
}
),
]
),
celpy.celtypes.StringType("on"): celpy.celtypes.ListType(
[
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("days"): celpy.celtypes.ListType(
[
celpy.celtypes.IntType(1),
celpy.celtypes.IntType(2),
celpy.celtypes.IntType(3),
celpy.celtypes.IntType(4),
celpy.celtypes.IntType(5),
]
),
celpy.celtypes.StringType("hour"): celpy.celtypes.IntType(6),
celpy.celtypes.StringType("tz"): celpy.celtypes.StringType(
"pt"
),
}
),
celpy.celtypes.MapType(
{
celpy.celtypes.StringType("days"): celpy.celtypes.ListType(
[celpy.celtypes.IntType(0)]
),
celpy.celtypes.StringType("hour"): celpy.celtypes.IntType(10),
celpy.celtypes.StringType("tz"): celpy.celtypes.StringType(
"pt"
),
}
),
]
),
}
def test_get_accounts(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
ami_doc = {"ResourceType": "ami"}
with celpy.c7nlib.C7NContext(filter=mock_filter):
accounts = celpy.c7nlib.get_accounts(ami_doc)
assert accounts == [str(sentinel.account)]
def test_get_vpcs(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
ami_doc = {"ResourceType": "ami"}
with celpy.c7nlib.C7NContext(filter=mock_filter):
vpcs = celpy.c7nlib.get_vpcs(ami_doc)
assert vpcs == [str(sentinel.vpc)]
def test_get_vpces(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
ami_doc = {"ResourceType": "ami"}
with celpy.c7nlib.C7NContext(filter=mock_filter):
vpces = celpy.c7nlib.get_vpces(ami_doc)
assert vpces == [str(sentinel.vpce)]
def test_get_orgids(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]
ami_doc = {"ResourceType": "ami"}
with celpy.c7nlib.C7NContext(filter=mock_filter):
orgids = celpy.c7nlib.get_orgids(ami_doc)
assert orgids == [str(sentinel.orgid)]
def test_get_endpoints(celfilter_instance):
mock_filter = celfilter_instance["the_filter"]