forked from cloud-custodian/cloud-custodian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_policy.py
2225 lines (2002 loc) · 79.9 KB
/
test_policy.py
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
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from copy import deepcopy
from datetime import datetime, timedelta
import json
import logging
import os
import shutil
import tempfile
from unittest import mock
from c7n import policy, manager
from c7n.config import Config
from c7n.provider import clouds
from c7n.exceptions import ResourceLimitExceeded, PolicyValidationError
from c7n.resources import aws, load_available
from c7n.resources.aws import AWS, Arn, fake_session
from c7n.resources.ec2 import EC2
from c7n.resources.kinesis import KinesisStream
from c7n.policy import execution, ConfigPollRuleMode, Policy, PullMode
from c7n.schema import generate, JsonSchemaValidator
from c7n.utils import dumps
from c7n.query import ConfigSource, TypeInfo
from c7n.version import version
from .common import BaseTest, event_data, Bag, load_data
class DummyResource(manager.ResourceManager):
def resources(self):
return [{"abc": 123}, {"def": 456}]
@property
def actions(self):
class _a:
def name(self):
return self.f.__name__
def __init__(self, f):
self.f = f
def process(self, resources):
return self.f(resources)
def p1(resources):
return [{"abc": 456}, {"def": 321}]
def p2(resources):
return resources
return [_a(p1), _a(p2)]
class PolicyMetaLint(BaseTest):
def setUp(self):
# we need to load all resources for the linting meta tests.
load_available()
def test_policy_missing_provider_session(self):
self.assertRaises(
RuntimeError,
policy.get_session_factory,
'nosuchthing', Bag())
def test_policy_detail_spec_permissions(self):
policy = self.load_policy(
{"name": "kinesis-delete", "resource": "kinesis", "actions": ["delete"]}
)
perms = policy.get_permissions()
self.assertEqual(
perms,
{
"kinesis:DescribeStream",
"kinesis:ListStreams",
"kinesis:DeleteStream",
"kinesis:ListTagsForStream",
"tag:GetResources"
},
)
def test_resource_type_repr_with_arn_type(self):
policy = self.load_policy({'name': 'ecr', 'resource': 'aws.ops-item'})
# check the repr absent a config type and cfn type but with an arn type
assert policy.resource_manager.resource_type.config_type is None
assert policy.resource_manager.resource_type.cfn_type is None
assert str(policy.resource_manager.resource_type) == '<TypeInfo AWS::Ssm::Opsitem>'
def test_resource_type_repr(self):
policy = self.load_policy({'name': 'airflow', 'resource': 'aws.airflow'})
# check the repr absent a config type but with a cfn type
assert policy.resource_manager.resource_type.config_type is None
assert str(policy.resource_manager.resource_type) == '<TypeInfo AWS::MWAA::Environment>'
def test_schema_plugin_name_mismatch(self):
# todo iterate over all clouds not just aws resources
for k, v in manager.resources.items():
for fname, f in v.filter_registry.items():
if fname in ("or", "and", "not"):
continue
self.assertIn(fname, f.schema["properties"]["type"]["enum"])
for aname, a in v.action_registry.items():
self.assertIn(aname, a.schema["properties"]["type"]["enum"])
def test_schema(self):
try:
schema = generate()
JsonSchemaValidator.check_schema(schema)
except Exception:
self.fail("Invalid schema")
def test_schema_serialization(self):
try:
dumps(generate())
except Exception:
self.fail("Failed to serialize schema")
def test_detail_spec_format(self):
failed = []
for k, v in manager.resources.items():
detail_spec = getattr(v.resource_type, 'detail_spec', None)
if not detail_spec:
continue
if not len(detail_spec) == 4:
failed.append(k)
if failed:
self.fail(
"%s resources have invalid detail_specs" % ", ".join(failed))
def test_resource_augment_universal_mask(self):
# universal tag had a potential bad patterm of masking
# resource augmentation, scan resources to ensure
missing = []
for k, v in manager.resources.items():
if not getattr(v.resource_type, "universal_taggable", None):
continue
if (
v.augment.__name__ == "universal_augment" and
getattr(v.resource_type, "detail_spec", None)
):
missing.append(k)
if missing:
self.fail(
"%s resource has universal augment masking resource augment" % (
', '.join(missing))
)
def test_resource_universal_taggable_arn_type(self):
missing = []
for k, v in manager.resources.items():
if not getattr(v, 'augment', None):
continue
if (
v.augment.__name__ == "universal_augment" and
v.resource_type.arn_type is None
):
missing.append(k)
if missing:
self.fail("%s universal taggable resource missing arn_type" % (
', '.join(missing)))
def test_resource_shadow_source_augment(self):
shadowed = []
bad = []
cfg = Config.empty()
for k, v in manager.resources.items():
if not getattr(v.resource_type, "config_type", None):
continue
p = Bag({"name": "permcheck", "resource": k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
source = mgr.get_source("config")
if not isinstance(source, ConfigSource):
bad.append(k)
if v.__dict__.get("augment"):
shadowed.append(k)
if shadowed:
self.fail(
"%s have resource managers shadowing source augments"
% (", ".join(shadowed))
)
if bad:
self.fail("%s have config types but no config source" % (", ".join(bad)))
def test_resource_arn_override_generator(self):
overrides = set()
for k, v in manager.resources.items():
arn_gen = bool(v.__dict__.get('get_arns') or v.__dict__.get('generate_arn'))
if arn_gen:
overrides.add(k)
overrides = overrides.difference(
{'account', 's3', 'hostedzone', 'log-group', 'rest-api', 'redshift-snapshot',
'rest-stage', 'codedeploy-app', 'codedeploy-group', 'fis-template', 'dlm-policy',
'apigwv2', 'apigwv2-stage', 'apigw-domain-name', 'fis-experiment',
'launch-template-version', 'glue-table'})
if overrides:
raise ValueError("unknown arn overrides in %s" % (", ".join(overrides)))
def test_resource_name(self):
names = []
for k, v in manager.resources.items():
if not getattr(v.resource_type, "name", None):
names.append(k)
if names:
self.fail("%s dont have resource name for reporting" % (", ".join(names)))
def test_filter_spec(self):
missing_fspec = []
for k, v in manager.resources.items():
if v.resource_type.filter_name is None:
continue
if not v.resource_type.filter_type:
missing_fspec.append(k)
if missing_fspec:
self.fail('aws resources missing filter specs: %s' % (
', '.join(missing_fspec)))
def test_ec2_id_prefix(self):
missing_prefix = []
for k, v in manager.resources.items():
if v.resource_type.service != 'ec2':
continue
if v.resource_type.id_prefix is None:
missing_prefix.append(k)
if missing_prefix:
self.fail('ec2 resources missing id prefix %s' % (', '.join(missing_prefix)))
def test_cfn_resource_validity(self):
# for resources which are annotated with cfn_type ensure that it is
# a valid type.
resource_cfn_types = set()
for k, v in manager.resources.items():
rtype = v.resource_type.cfn_type
if rtype is not None:
resource_cfn_types.add(rtype)
cfn_types = set(load_data('cfn-types.json'))
missing = set()
for rtype in resource_cfn_types:
if rtype not in cfn_types:
missing.add(rtype)
if missing:
raise AssertionError("Bad cfn types:\n %s" % (
"\n".join(sorted(missing))))
def test_securityhub_resource_support(self):
session = fake_session()._session
model = session.get_service_model('securityhub')
shape = model.shape_for('ResourceDetails')
mangled_hub_types = set(shape.members.keys())
resource_hub_types = set()
whitelist = set(('AwsS3Object', 'Container'))
todo = set((
# q4 2023,
'AwsEc2ClientVpnEndpoint',
'AwsS3AccessPoint',
'AwsMskCluster',
'AwsEventsEventbus',
'AwsEventsEndpoint',
'AwsDmsReplicationTask',
'AwsRoute53HostedZone',
'AwsDmsEndpoint',
'AwsDmsReplicationInstance',
# q2 2023
'AwsAthenaWorkGroup',
'AwsStepFunctionStateMachine',
'AwsGuardDutyDetector',
'AwsAmazonMqBroker',
'AwsAppSyncGraphQlApi',
'AwsEventSchemasRegistry',
"AwsEc2RouteTable",
# q1 2023
'AwsWafv2RuleGroup',
'AwsWafv2WebAcl',
'AwsEc2LaunchTemplate',
'AwsSageMakerNotebookInstance',
# q3 2022
'AwsBackupBackupPlan',
'AwsBackupBackupVault',
'AwsBackupRecoveryPoint',
'AwsCloudFormationStack',
'AwsWafRegionalRule',
'AwsWafRule',
'AwsWafRuleGroup',
'AwsKinesisStream',
'AwsWafRegionalRuleGroup',
'AwsEc2VpcPeeringConnection',
'AwsWafRegionalWebAcl',
'AwsCloudWatchAlarm',
'AwsEfsAccessPoint',
'AwsEc2TransitGateway',
'AwsEcsContainer',
'AwsEcsTask',
'AwsBackupRecoveryPoint',
# https://github.com/cloud-custodian/cloud-custodian/issues/7775
'AwsBackupBackupPlan',
'AwsBackupBackupVault',
# q2 2022
'AwsRdsDbSecurityGroup',
# q1 2022
'AwsNetworkFirewallRuleGroup',
'AwsNetworkFirewallFirewall',
'AwsNetworkFirewallFirewallPolicy',
# q4 2021 - second wave
'AwsXrayEncryptionConfig',
'AwsOpenSearchServiceDomain',
'AwsEc2VpcEndpointService',
'AwsWafRateBasedRule',
'AwsWafRegionalRateBasedRule',
'AwsEcrRepository',
'AwsEksCluster',
# q4 2021
'AwsEcrContainerImage',
'AwsEc2VpnConnection',
'AwsAutoScalingLaunchConfiguration',
# q3 2021
'AwsEcsService',
'AwsRdsEventSubscription',
# q2 2021
'AwsEcsTaskDefinition',
'AwsEcsCluster',
'AwsEc2Subnet',
'AwsElasticBeanstalkEnvironment',
'AwsEc2NetworkAcl',
# newer wave q1 2021,
'AwsS3AccountPublicAccessBlock',
'AwsSsmPatchCompliance',
# newer wave q4 2020
'AwsApiGatewayRestApi',
'AwsApiGatewayStage',
'AwsApiGatewayV2Api',
'AwsApiGatewayV2Stage',
'AwsCertificateManagerCertificate',
'AwsCloudTrailTrail',
'AwsElbLoadBalancer',
'AwsIamGroup',
'AwsRedshiftCluster',
# newer wave q3 2020
'AwsDynamoDbTable',
'AwsEc2Eip',
'AwsIamPolicy',
'AwsIamUser',
'AwsRdsDbCluster',
'AwsRdsDbClusterSnapshot',
'AwsRdsDbSnapshot',
'AwsSecretsManagerSecret',
# older wave
'AwsElbv2LoadBalancer',
'AwsEc2SecurityGroup',
'AwsIamAccessKey',
'AwsEc2NetworkInterface',
'AwsWafWebAcl'))
mangled_hub_types = mangled_hub_types.difference(whitelist).difference(todo)
for k, v in manager.resources.items():
finding = v.action_registry.get('post-finding')
if finding:
resource_hub_types.add(finding.resource_type)
assert mangled_hub_types.difference(resource_hub_types) == set()
def test_config_resource_support(self):
# for several of these we express support as filter or action instead
# of a resource.
whitelist = {
# q1 2024
"AWS::Cognito::UserPoolClient",
"AWS::Cognito::UserPoolGroup",
"AWS::EC2::NetworkInsightsAccessScope",
"AWS::EC2::NetworkInsightsAnalysis",
"AWS::Grafana::Workspace",
"AWS::GroundStation::DataflowEndpointGroup",
"AWS::ImageBuilder::ImageRecipe",
"AWS::M2::Environment",
"AWS::QuickSight::DataSource",
"AWS::QuickSight::Template",
"AWS::QuickSight::Theme",
"AWS::RDS::OptionGroup",
"AWS::Redshift::EndpointAccess",
"AWS::Route53Resolver::FirewallRuleGroup",
# q4 2023 wave 2 (aka reinvent)
"AWS::ACMPCA::CertificateAuthorityActivation",
"AWS::AppMesh::GatewayRoute",
"AWS::Connect::Instance",
"AWS::Connect::QuickConnect",
"AWS::EC2::CarrierGateway",
"AWS::EC2::IPAMPool",
"AWS::EC2::TransitGatewayConnect",
"AWS::EC2::TransitGatewayMulticastDomain",
"AWS::ECS::CapacityProvider",
"AWS::IAM::InstanceProfile",
"AWS::IoT::CACertificate",
"AWS::IoTTwinMaker::SyncJob",
"AWS::KafkaConnect::Connector",
"AWS::Lambda::CodeSigningConfig",
"AWS::NetworkManager::ConnectPeer",
"AWS::ResourceExplorer2::Index",
# q4 2023
"AWS::APS::RuleGroupsNamespace",
"AWS::Batch::SchedulingPolicy",
"AWS::CodeBuild::ReportGroup",
"AWS::CodeGuruProfiler::ProfilingGroup",
"AWS::InspectorV2::Filter",
"AWS::IoT::JobTemplate",
"AWS::IoT::ProvisioningTemplate",
"AWS::IoTTwinMaker::ComponentType",
"AWS::IoTWireless::FuotaTask",
"AWS::IoTWireless::MulticastGroup",
"AWS::MSK::BatchScramSecret",
"AWS::MediaConnect::FlowSource",
"AWS::Personalize::DatasetGroup",
"AWS::Route53Resolver::ResolverQueryLoggingConfig",
"AWS::Route53Resolver::ResolverQueryLoggingConfigAssociation",
"AWS::SageMaker::FeatureGroup",
"AWS::ServiceDiscovery::Instance",
"AWS::Transfer::Certificate",
# q3 2023
"AWS::ACMPCA::CertificateAuthority",
"AWS::Amplify::Branch",
"AWS::AppConfig::HostedConfigurationVersion",
"AWS::AppIntegrations::EventIntegration",
"AWS::AppMesh::Route",
"AWS::AppMesh::VirtualRouter",
"AWS::AppRunner::Service",
"AWS::Athena::PreparedStatement",
"AWS::CustomerProfiles::ObjectType",
"AWS::EC2::CapacityReservation",
"AWS::EC2::ClientVpnEndpoint",
"AWS::EC2::IPAMScope",
"AWS::Evidently::Launch",
"AWS::Forecast::DatasetGroup",
"AWS::GreengrassV2::ComponentVersion",
"AWS::GroundStation::MissionProfile",
"AWS::Kendra::Index",
"AWS::KinesisVideo::Stream",
"AWS::Logs::Destination",
"AWS::MSK::Configuration",
"AWS::MediaConnect::FlowEntitlement",
"AWS::MediaConnect::FlowVpcInterface",
"AWS::MediaTailor::PlaybackConfiguration",
"AWS::NetworkManager::CustomerGatewayAssociation",
"AWS::NetworkManager::LinkAssociation",
"AWS::Personalize::Dataset",
"AWS::Personalize::Schema",
"AWS::Personalize::Solution",
"AWS::Pinpoint::EmailChannel",
"AWS::Pinpoint::EmailTemplate",
"AWS::Pinpoint::EventStream",
"AWS::ResilienceHub::App",
# q2 2023 wave 3
"AWS::Amplify::App",
"AWS::AppMesh::VirtualService",
"AWS::AppRunner::VpcConnector",
"AWS::AppStream::Application",
"AWS::Cassandra::Keyspace",
"AWS::ECS::TaskSet",
"AWS::Evidently::Project",
"AWS::Forecast::Dataset",
"AWS::Pinpoint::Campaign",
"AWS::Pinpoint::InAppTemplate",
"AWS::SageMaker::Domain",
"AWS::Signer::SigningProfile",
"AWS::Transfer::Agreement",
"AWS::Transfer::Connector",
# q2 2023 wave 2
"AWS::AppConfig::DeploymentStrategy",
"AWS::AuditManager::Assessment",
"AWS::CloudWatch::MetricStream",
"AWS::DeviceFarm::InstanceProfile",
"AWS::EC2::EC2Fleet",
"AWS::EC2::SubnetRouteTableAssociation",
"AWS::ECR::PullThroughCacheRule",
"AWS::GroundStation::Config",
"AWS::ImageBuilder::ImagePipeline",
"AWS::IoT::FleetMetric",
"AWS::IoTWireless::ServiceProfile",
"AWS::Panorama::Package",
"AWS::Pinpoint::App",
"AWS::Redshift::ScheduledAction",
"AWS::Route53Resolver::FirewallRuleGroupAssociation",
"AWS::SageMaker::AppImageConfig",
"AWS::SageMaker::Image",
# q2 2023 wave 1
"AWS::AppStream::DirectoryConfig",
"AWS::AutoScaling::WarmPool",
"AWS::Connect::PhoneNumber",
"AWS::CustomerProfiles::Domain",
"AWS::EC2::DHCPOptions",
"AWS::EC2::IPAM",
"AWS::EC2::NetworkInsightsPath",
"AWS::EC2::TrafficMirrorFilter",
"AWS::HealthLake::FHIRDatastore",
"AWS::IoTTwinMaker::Scene",
"AWS::KinesisVideo::SignalingChannel",
"AWS::LookoutVision::Project",
"AWS::NetworkManager::TransitGatewayRegistration",
"AWS::Pinpoint::ApplicationSettings",
"AWS::Pinpoint::Segment",
"AWS::RoboMaker::RobotApplication",
"AWS::RoboMaker::SimulationApplication",
"AWS::Route53RecoveryReadiness::ResourceSet",
"AWS::Route53RecoveryControl::RoutingControl",
"AWS::Route53RecoveryControl::SafetyRule",
# q1 2023
'AWS::AppConfig::ConfigurationProfile',
'AWS::AppConfig::Environment',
'AWS::Backup::ReportPlan',
'AWS::Budgets::BudgetsAction',
'AWS::Cloud9::EnvironmentEC2',
'AWS::CodeGuruReviewer::RepositoryAssociation',
'AWS::DataSync::LocationFSxWindows',
'AWS::DataSync::LocationHDFS',
'AWS::DataSync::LocationObjectStorage',
'AWS::DeviceFarm::TestGridProject',
'AWS::ECR::RegistryPolicy',
'AWS::EKS::Addon',
'AWS::EKS::IdentityProviderConfig',
'AWS::EventSchemas::Discoverer',
'AWS::EventSchemas::Registry',
'AWS::EventSchemas::RegistryPolicy',
'AWS::EventSchemas::Schema',
'AWS::Events::ApiDestination',
'AWS::Events::Archive',
'AWS::Events::Connection',
'AWS::Events::Endpoint',
'AWS::FraudDetector::EntityType',
'AWS::FraudDetector::Label',
'AWS::FraudDetector::Outcome',
'AWS::FraudDetector::Variable',
'AWS::GuardDuty::Filter',
'AWS::IVS::Channel',
'AWS::IVS::PlaybackKeyPair',
'AWS::IVS::RecordingConfiguration',
'AWS::ImageBuilder::ContainerRecipe',
'AWS::ImageBuilder::DistributionConfiguration',
'AWS::ImageBuilder::InfrastructureConfiguration',
'AWS::IoT::AccountAuditConfiguration',
'AWS::IoT::Authorizer',
'AWS::IoT::CustomMetric',
'AWS::IoT::Dimension',
'AWS::IoT::MitigationAction',
'AWS::IoT::Policy',
'AWS::IoT::RoleAlias',
'AWS::IoT::ScheduledAudit',
'AWS::IoT::SecurityProfile',
'AWS::IoTAnalytics::Channel',
'AWS::IoTAnalytics::Dataset',
'AWS::IoTAnalytics::Datastore',
'AWS::IoTAnalytics::Pipeline',
'AWS::IoTEvents::AlarmModel',
'AWS::IoTEvents::DetectorModel',
'AWS::IoTEvents::Input',
'AWS::IoTSiteWise::AssetModel',
'AWS::IoTSiteWise::Dashboard',
'AWS::IoTSiteWise::Gateway',
'AWS::IoTSiteWise::Portal',
'AWS::IoTSiteWise::Project',
'AWS::IoTTwinMaker::Entity',
'AWS::IoTTwinMaker::Workspace',
'AWS::Lex::BotAlias',
'AWS::Lightsail::Bucket',
'AWS::Lightsail::Certificate',
'AWS::Lightsail::Disk',
'AWS::Lightsail::StaticIp',
'AWS::LookoutMetrics::Alert',
'AWS::MediaPackage::PackagingConfiguration',
'AWS::MediaPackage::PackagingGroup',
'AWS::RDS::GlobalCluster',
'AWS::RUM::AppMonitor',
'AWS::ResilienceHub::ResiliencyPolicy',
'AWS::RoboMaker::RobotApplicationVersion',
'AWS::Route53RecoveryReadiness::Cell',
'AWS::Route53RecoveryReadiness::RecoveryGroup',
'AWS::Route53Resolver::FirewallDomainList',
'AWS::S3::StorageLens',
'AWS::SES::ReceiptFilter',
'AWS::SES::ReceiptRuleSet',
'AWS::SES::Template',
'AWS::ServiceDiscovery::HttpNamespace',
'AWS::Transfer::Workflow',
#
# 'AWS::ApiGatewayV2::Stage',
'AWS::AutoScaling::ScheduledAction',
'AWS::Backup::BackupSelection',
'AWS::Backup::RecoveryPoint',
'AWS::CodeDeploy::DeploymentConfig',
'AWS::Config::ConformancePackCompliance',
'AWS::Config::ResourceCompliance',
'AWS::Detective::Graph',
'AWS::DMS::Certificate',
'AWS::EC2::EgressOnlyInternetGateway',
'AWS::EC2::LaunchTemplate',
'AWS::EC2::RegisteredHAInstance',
'AWS::EC2::TransitGatewayAttachment',
'AWS::EC2::TransitGatewayRouteTable',
'AWS::EC2::VPCEndpointService',
'AWS::ECR::PublicRepository',
'AWS::EFS::AccessPoint',
'AWS::EMR::SecurityConfiguration',
'AWS::ElasticBeanstalk::ApplicationVersion',
'AWS::GlobalAccelerator::Accelerator',
'AWS::GlobalAccelerator::Listener',
'AWS::GlobalAccelerator::EndpointGroup',
'AWS::GuardDuty::Detector',
'AWS::Kinesis::StreamConsumer',
'AWS::NetworkFirewall::FirewallPolicy',
'AWS::NetworkFirewall::RuleGroup',
'AWS::OpenSearch::Domain', # this is effectively an alias
'AWS::RDS::DBSecurityGroup',
'AWS::RDS::EventSubscription',
'AWS::Redshift::ClusterParameterGroup',
'AWS::Redshift::ClusterSecurityGroup',
'AWS::Redshift::EventSubscription',
'AWS::S3::AccountPublicAccessBlock',
'AWS::SSM::AssociationCompliance',
'AWS::SSM::FileData',
'AWS::SSM::ManagedInstanceInventory',
'AWS::SSM::PatchCompliance',
'AWS::SageMaker::CodeRepository',
'AWS::ServiceCatalog::CloudFormationProvisionedProduct',
'AWS::ShieldRegional::Protection',
'AWS::WAF::RateBasedRule',
'AWS::WAF::Rule',
'AWS::WAF::RuleGroup',
'AWS::WAFRegional::RateBasedRule',
'AWS::WAFRegional::Rule',
'AWS::WAFRegional::RuleGroup',
'AWS::WAFv2::IPSet',
'AWS::WAFv2::ManagedRuleSet',
'AWS::WAFv2::RegexPatternSet',
'AWS::WAFv2::RuleGroup',
# 'AWS::WAFv2::WebACL',
'AWS::XRay::EncryptionConfig',
'AWS::ElasticLoadBalancingV2::Listener',
'AWS::AccessAnalyzer::Analyzer',
'AWS::WorkSpaces::ConnectionAlias',
'AWS::DMS::ReplicationSubnetGroup',
'AWS::Route53Resolver::ResolverEndpoint',
'AWS::Route53Resolver::ResolverRule',
'AWS::Route53Resolver::ResolverRuleAssociation',
'AWS::DMS::EventSubscription',
'AWS::GlobalAccelerator::Accelerator',
'AWS::EC2::TransitGatewayAttachment',
'AWS::GlobalAccelerator::EndpointGroup',
'AWS::GlobalAccelerator::Listener',
'AWS::DMS::Certificate',
'AWS::Detective::Graph',
'AWS::EC2::TransitGatewayRouteTable',
'AWS::Glue::Job',
'AWS::SageMaker::NotebookInstanceLifecycleConfig',
'AWS::SES::ContactList',
'AWS::SageMaker::Workteam',
'AWS::EKS::FargateProfile',
'AWS::DataSync::LocationFSxLustre',
'AWS::AppConfig::Application',
'AWS::DataSync::LocationS3',
'AWS::ServiceDiscovery::PublicDnsNamespace',
'AWS::EC2::NetworkInsightsAccessScopeAnalysis',
'AWS::Route53::HostedZone',
'AWS::GuardDuty::IPSet',
'AWS::GuardDuty::ThreatIntelSet',
'AWS::DataSync::LocationNFS',
'AWS::DataSync::LocationEFS',
'AWS::ServiceDiscovery::Service',
'AWS::DataSync::LocationSMB',
}
resource_map = {}
for k, v in manager.resources.items():
if not v.resource_type.config_type:
continue
resource_map[v.resource_type.config_type] = v
resource_config_types = set(resource_map)
session = fake_session()._session
model = session.get_service_model('config')
shape = model.shape_for('ResourceType')
present = resource_config_types.intersection(whitelist)
if present:
raise AssertionError(
"Supported config types \n %s" % ('\n'.join(sorted(present))))
config_types = set(shape.enum).difference(whitelist)
missing = config_types.difference(resource_config_types)
if missing:
raise AssertionError(
"Missing config types \n %s" % ('\n'.join(sorted(missing))))
# config service can't be bothered to update their sdk correctly
invalid_ignore = {
'AWS::Config::ConfigurationRecorder',
'AWS::SageMaker::NotebookInstance',
'AWS::SageMaker::EndpointConfig',
'AWS::DMS::ReplicationInstance',
'AWS::DMS::ReplicationTask',
'AWS::SES::MailManagerIngressPoint',
}
bad_types = resource_config_types.difference(config_types)
bad_types = bad_types.difference(invalid_ignore)
if bad_types:
raise AssertionError(
"Invalid config types \n %s" % ('\n'.join(bad_types)))
def test_resource_meta_with_class(self):
missing = set()
for k, v in manager.resources.items():
if k in ('rest-account', 'account', 'quicksight-account'):
continue
if not issubclass(v.resource_type, TypeInfo):
missing.add(k)
if missing:
raise SyntaxError("missing type info class %s" % (', '.join(missing)))
def test_resource_type_empty_metadata(self):
empty = set()
for k, v in manager.resources.items():
if k in ('rest-account', 'account', 'codedeploy-deployment', 'sagemaker-cluster',
'networkmanager-core', 'quicksight-account', 'ses-dedicated-ip-pool'):
continue
for rk, rv in v.resource_type.__dict__.items():
if rk[0].isalnum() and rv is None:
empty.add(k)
if empty:
raise ValueError("Empty Resource Metadata %s" % (', '.join(empty)))
def test_valid_arn_type(self):
arn_db = load_data('arn-types.json')
invalid = {}
overrides = {'wafv2': set(('webacl',))}
# we have a few resources where we have synthetic arns
# or they aren't in the iam ref docs.
allow_list = set((
# bug in the arnref script or test logic below.
'glue-catalog',
# these are valid, but v1 & v2 arns get mangled into the
# same top level prefix
'emr-serverless-app',
# api gateway resources trip up these checks because they
# have leading slashes in the resource type section
'rest-api',
'rest-stage',
'apigw-domain-name',
# our check doesn't handle nested resource types in the arn
'guardduty-finding',
# synthetics ~ ie. c7n introduced since non exist.
# or in some cases where it exists but not usable in iam.
'scaling-policy',
'glue-classifier',
'glue-security-configuration',
'event-rule-target',
'rrset',
'redshift-reserved',
'elasticsearch-reserved',
'ses-receipt-rule-set'
))
for k, v in manager.resources.items():
if k in allow_list:
continue
svc = v.resource_type.service
if not v.resource_type.arn_type:
continue
svc_arn_map = arn_db.get(svc, {})
if not svc_arn_map:
continue
svc_arns = list(svc_arn_map.values())
svc_arn_types = set()
for sa in svc_arns:
sa_arn = Arn.parse(sa)
sa_type = sa_arn.resource_type
if sa_type is None:
sa_type = ''
# wafv2
if sa_type.startswith('{') and sa_type.endswith('}'):
sa_type = sa_arn.resource
if ':' in sa_type:
sa_type = sa_type.split(':', 1)[0]
svc_arn_types.add(sa_type)
svc_arn_types = overrides.get(svc, svc_arn_types)
if v.resource_type.arn_type not in svc_arn_types:
invalid[k] = {'valid': sorted(svc_arn_types),
'service': svc,
'resource': v.resource_type.arn_type}
# s3 directory has bucket in the arn, but its not in the iam ref docs
# we source arn types from.
for ignore in ('s3-directory',):
invalid.pop(ignore)
if invalid:
raise ValueError("%d %s have invalid arn types in metadata" % (
len(invalid), ", ".join(invalid)))
def test_resource_legacy_type(self):
legacy = set()
marker = object()
for k, v in manager.resources.items():
if getattr(v.resource_type, 'type', marker) is not marker:
legacy.add(k)
if legacy:
raise SyntaxError("legacy arn type info %s" % (', '.join(legacy)))
def _visit_filters_and_actions(self, visitor):
names = []
for cloud_name, cloud in clouds.items():
for resource_name, resource in cloud.resources.items():
for fname, f in resource.filter_registry.items():
if fname in ('and', 'or', 'not'):
continue
if visitor(f):
names.append("%s.%s.filters.%s" % (
cloud_name, resource_name, fname))
for aname, a in resource.action_registry.items():
if visitor(a):
names.append('%s.%s.actions.%s' % (
cloud_name, resource_name, aname))
return names
def test_filter_action_additional(self):
def visitor(e):
if e.type == 'notify':
return
return e.schema.get('additionalProperties', True) is True
names = self._visit_filters_and_actions(visitor)
if names:
self.fail(
"missing additionalProperties: False on actions/filters\n %s" % (
" \n".join(names)))
def test_filter_action_type(self):
def visitor(e):
return 'type' not in e.schema['properties']
names = self._visit_filters_and_actions(visitor)
if names:
self.fail("missing type on actions/filters\n %s" % (" \n".join(names)))
def test_resource_arn_info(self):
missing = []
whitelist_missing = {
'rest-stage', 'rest-resource', 'rest-vpclink', 'rest-client-certificate'}
explicit = []
whitelist_explicit = {
'securityhub-finding', 'ssm-patch-group',
'appdiscovery-agent', 'athena-named-query',
'rest-account', 'shield-protection', 'shield-attack',
'dlm-policy', 'efs', 'efs-mount-target', 'gamelift-build',
'glue-connection', 'glue-dev-endpoint', 'cloudhsm-cluster',
'snowball-cluster', 'snowball', 'ssm-activation',
'healthcheck', 'event-rule-target', 'log-metric',
'support-case', 'transit-attachment', 'config-recorder',
'apigw-domain-name', 'backup-job', 'quicksight-account'}
missing_method = []
for k, v in manager.resources.items():
rtype = getattr(v, 'resource_type', None)
if not v.has_arn():
missing_method.append(k)
if rtype is None:
continue
if v.__dict__.get('get_arns'):
continue
if getattr(rtype, 'arn', None) is False:
explicit.append(k)
if getattr(rtype, 'arn', None) is not None:
continue
if getattr(rtype, 'type', None) is not None:
continue
if getattr(rtype, 'arn_type', None) is not None:
continue
missing.append(k)
self.assertEqual(
set(missing).union(explicit),
set(missing_method))
missing = set(missing).difference(whitelist_missing)
if missing:
self.fail(
"%d resources %s are missing arn type info" % (
len(missing), ", ".join(missing)))
explicit = set(explicit).difference(whitelist_explicit)
if explicit:
self.fail(
"%d resources %s dont have arn type info exempted" % (
len(explicit), ", ".join(explicit)))
def test_resource_permissions(self):
self.capture_logging("c7n.cache")
missing = []
cfg = Config.empty()
for k, v in list(manager.resources.items()):
p = Bag({"name": "permcheck", "resource": k, 'provider_name': 'aws'})
ctx = self.get_context(config=cfg, policy=p)
mgr = v(ctx, p)
perms = mgr.get_permissions()
if not perms:
missing.append(k)
for n, a in list(v.action_registry.items()):
p["actions"] = [n]
perms = a({}, mgr).get_permissions()
found = bool(perms)
if not isinstance(perms, (list, tuple, set)):
found = False
if "webhook" == n:
continue
if not found:
missing.append("%s.actions.%s" % (k, n))
for n, f in list(v.filter_registry.items()):
if n in ("and", "or", "not", "missing", "reduce"):
continue
p["filters"] = [n]
perms = f({}, mgr).get_permissions()
if not isinstance(perms, (tuple, list, set)):
missing.append("%s.filters.%s" % (k, n))
# in memory filters
if n in (
"event",
"value",
"tag-count",
"marked-for-op",
"offhour",
"onhour",
"age",
"state-age",
"egress",
"ingress",
"capacity-delta",
"is-ssl",
"global-grants",
"missing-policy-statement",
"missing-statement",
"healthcheck-protocol-mismatch",
"image-age",
"has-statement",
"no-access",
"instance-age",
"ephemeral",
"instance-uptime",
"dead-letter",
"list-item",
"ip-address-usage",
):
continue
qk = "%s.filters.%s" % (k, n)
if qk in ("route-table.filters.route",):
continue
if not perms:
missing.append(qk)
if missing:
self.fail(
"Missing permissions %d on \n\t%s"
% (len(missing), "\n\t".join(sorted(missing)))
)
def test_deprecation_dates(self):
def check_deprecations(source):
issues = set()
for dep in getattr(source, 'deprecations', ()):
when = dep.removed_after
if when is not None:
name = f"{source.__module__}.{source.__name__}"
if not isinstance(when, str):
issues.add(f"{name}: \"{dep}\", removed_after attribute must be a string")
continue
try:
datetime.strptime(when, "%Y-%m-%d")
except ValueError:
issues.add(f"{name}: \"{dep}\", removed_after must be a valid date"
f" in the format 'YYYY-MM-DD', got '{when}'")
return issues
issues = check_deprecations(Policy)
for name, cloud in clouds.items():