def test_optional(self): input_str = "{}" field = ListField("People", EmbeddedScalarField(), alti_key="person", optional=True) expected_output_data = () input_data = json.loads(input_str) links = field.parse(data=input_data, context={}) output_data = [link.to_dict() for link in links] self.assertCountEqual(output_data, expected_output_data)
def test_optional(self): input_str = '{"Biota": {"Plants": ["tree", "fern"]}}' field = DictField( "Biota", AnonymousListField("Animals", EmbeddedScalarField(), optional=True) ) input_data = json.loads(input_str) link_collection = field.parse(data=input_data, context={}) expected_link_collection = LinkCollection( multi_links=(MultiLink(pred="biota", obj=LinkCollection()),), ) self.assertEqual(link_collection, expected_link_collection)
def test_valid_strings_input(self): input_str = '{"Animals": ["cow", "pig", "human"]}' field = ListField("Animals", EmbeddedScalarField()) input_data = json.loads(input_str) link_collection = field.parse(data=input_data, context={}) expected_link_collection = LinkCollection( simple_links=( SimpleLink(pred="animals", obj="cow"), SimpleLink(pred="animals", obj="pig"), SimpleLink(pred="animals", obj="human"), ), ) self.assertEqual(link_collection, expected_link_collection)
def test_allow_scalar(self): input_str = '{"People": "bob"}' field = ListField("People", EmbeddedScalarField(), alti_key="person", allow_scalar=True) expected_output_data = ({ "pred": "person", "obj": "bob", "type": "simple" }, ) input_data = json.loads(input_str) links = field.parse(data=input_data, context={}) output_data = [link.to_dict() for link in links] self.assertCountEqual(output_data, expected_output_data)
def test_allow_scalar(self): input_str = '{"Biota": {"Plants": "tree"}}' field = DictField( "Biota", AnonymousListField("Plants", EmbeddedScalarField(), allow_scalar=True) ) input_data = json.loads(input_str) link_collection = field.parse(data=input_data, context={}) expected_link_collection = LinkCollection( multi_links=( MultiLink( pred="biota", obj=LinkCollection(simple_links=(SimpleLink(pred="biota", obj="tree"),),), ), ) ) self.assertEqual(expected_link_collection, link_collection)
class VpcEndpointServiceResourceSpec(EC2ResourceSpec): """Resource for VPC Endpoint Services""" # type_name = "vpc-endpoint-service" type_name = "vpc_endpoint_service" schema = Schema( AnonymousListField("ServiceType", ScalarField("ServiceType")), ScalarField("ServiceName"), ScalarField("ServiceState"), ScalarField("AcceptanceRequired"), ListField("AvailabilityZones", EmbeddedScalarField()), TagsField(), ) @classmethod def list_from_aws( cls: Type["VpcEndpointServiceResourceSpec"], client: BaseClient, account_id: str, region: str, ) -> ListFromAWSResult: """Return a dict of dicts of the format: {'vpc_endpoint_svc_1_arn': {vpc_endpoint_svc_1_dict}, 'vpc_endpoint_svc_2_arn': {vpc_endpoint_svc_2_dict}, ...} Where the dicts represent results from describe_vpc_endpoint_service_configurations.""" services = {} paginator = client.get_paginator( "describe_vpc_endpoint_service_configurations") for resp in paginator.paginate(): for service in resp.get("ServiceConfigurations", []): resource_arn = cls.generate_arn( account_id=account_id, region=region, resource_id=service["ServiceId"]) services[resource_arn] = service return ListFromAWSResult(resources=services)
def test_valid_strings_input(self): input_str = '{"Biota": {"Animals": ["cow", "pig", "human"], "Plants": ["tree", "fern"]}}' field = DictField("Biota", AnonymousListField("Animals", EmbeddedScalarField())) input_data = json.loads(input_str) link_collection = field.parse(data=input_data, context={}) expected_link_collection = LinkCollection( multi_links=( MultiLink( pred="biota", obj=LinkCollection( simple_links=( SimpleLink(pred="biota", obj="cow"), SimpleLink(pred="biota", obj="pig"), SimpleLink(pred="biota", obj="human"), ) ), ), ) ) self.assertEqual(link_collection, expected_link_collection)
def test_allow_scalar(self): input_str = '{"Biota": {"Plants": "tree"}}' field = DictField( "Biota", AnonymousListField("Plants", EmbeddedScalarField(), allow_scalar=True)) expected_output_data = [{ "pred": "biota", "obj": [{ "pred": "biota", "obj": "tree", "type": "simple" }], "type": "multi", }] input_data = json.loads(input_str) links = field.parse(data=input_data, context={}) output_data = [link.to_dict() for link in links] self.assertCountEqual(output_data, expected_output_data)
class TransitGatewayVpcAttachmentResourceSpec(EC2ResourceSpec): """Resource for Transit Gateway VPC Attachments""" # type_name = "transit-gateway-vpc-attachment" type_name = "transit_gateway_vpc_attachment" schema = Schema( ScalarField("TransitGatewayAttachmentId"), ScalarField("TransitGatewayId"), ScalarField("VpcId"), ScalarField("VpcOwnerId"), ScalarField("State"), ScalarField("CreationTime"), ListField("SubnetIds", EmbeddedScalarField(), alti_key="subnet_id"), AnonymousDictField("Options", ScalarField("DnsSupport"), ScalarField("Ipv6Support")), ) @classmethod def list_from_aws( cls: Type["TransitGatewayVpcAttachmentResourceSpec"], client: BaseClient, account_id: str, region: str, ) -> ListFromAWSResult: paginator = client.get_paginator( "describe_transit_gateway_vpc_attachments") attachments = {} for resp in paginator.paginate(): for attachment in resp.get("TransitGatewayVpcAttachments", []): resource_arn = cls.generate_arn( account_id=account_id, region=region, resource_id=attachment["TransitGatewayAttachmentId"], ) attachments[resource_arn] = attachment return ListFromAWSResult(resources=attachments)
class IAMRoleResourceSpec(IAMResourceSpec): """Resource for IAM Roles""" type_name = "role" schema = Schema( ScalarField("RoleName", "name"), ScalarField("MaxSessionDuration"), AnonymousListField( "PolicyAttachments", AnonymousEmbeddedDictField( ResourceLinkField( "PolicyArn", IAMPolicyResourceSpec, optional=True, value_is_id=True, alti_key="attached_policy", )), ), DictField( "AssumeRolePolicyDocument", ScalarField("Version"), ListField( "Statement", EmbeddedDictField( ScalarField("Effect"), ScalarField("Action"), DictField( "Principal", ListField("AWS", EmbeddedScalarField(), optional=True, allow_scalar=True), ListField("Federated", EmbeddedScalarField(), optional=True, allow_scalar=True), ), ), ), ), ScalarField("AssumeRolePolicyDocumentText"), ) @classmethod def list_from_aws(cls: Type["IAMRoleResourceSpec"], client: BaseClient, account_id: str, region: str) -> ListFromAWSResult: """Return a dict of dicts of the format: {'role_1_arn': {role_1_dict}, 'role_2_arn': {role_2_dict}, ...} Where the dicts represent results from list_roles and additional info per role from list_targets_by_role.""" roles = {} paginator = client.get_paginator("list_roles") for resp in paginator.paginate(): for role in resp.get("Roles", []): role_name = role["RoleName"] assume_role_policy_document = copy.deepcopy( role["AssumeRolePolicyDocument"]) assume_role_policy_document_text = policy_doc_dict_to_sorted_str( assume_role_policy_document) role[ "AssumeRolePolicyDocumentText"] = assume_role_policy_document_text for statement in assume_role_policy_document.get( "Statement", []): for obj in statement.get("Condition", {}).values(): for obj_key in obj.keys(): if obj_key.lower() == "sts:externalid": obj[obj_key] = "REMOVED" policies_result = get_attached_role_policies(client, role_name) policies = policies_result role["PolicyAttachments"] = policies resource_arn = role["Arn"] roles[resource_arn] = role return ListFromAWSResult(resources=roles)
def test_missing_parent_alti_key_value(self): input_data = "foo" field = EmbeddedScalarField() with self.assertRaises(ParentKeyMissingException): field.parse(data=input_data, context={"parent_alti_key": None})
class ACMCertificateResourceSpec(ACMResourceSpec): """Resource for ACM Certificates""" type_name = "certificate" schema = Schema( ScalarField("DomainName", optional=True), ListField("SubjectAlternativeNames", EmbeddedScalarField(), optional=True), ScalarField("Serial", optional=True), ScalarField("Subject", optional=True), ScalarField("Issuer", optional=True), ScalarField("CreatedAt", optional=True), ScalarField("IssuedAt", optional=True), ScalarField("ImportedAt", optional=True), ScalarField("Status", optional=True), ScalarField("RevokedAt", optional=True), ScalarField("RevocationReason", optional=True), ScalarField("NotBefore", optional=True), ScalarField("NotAfter", optional=True), ScalarField("KeyAlgorithm", optional=True), ScalarField("SignatureAlgorithm", optional=True), ListField("InUseBy", EmbeddedScalarField(), optional=True), ScalarField("FailureReason", optional=True), ScalarField("Type", optional=True), ListField( "DomainValidationOptions", EmbeddedDictField( ScalarField("DomainName", optional=True), ListField("ValidationEmails", EmbeddedScalarField(), optional=True), ScalarField("ValidationDomain", optional=True), ScalarField("ValidationStatus", optional=True), DictField( "ResourceRecord", EmbeddedDictField( ScalarField("Name", optional=True), ScalarField("Type", optional=True), ScalarField("Value", optional=True), ), optional=True, ), ScalarField("ValidationMethod", optional=True), ), optional=True, ), ListField("KeyUsages", EmbeddedDictField(ScalarField("Name")), optional=True), ListField( "ExtendedKeyUsages", EmbeddedDictField(ScalarField("Name"), ScalarField("OID", optional=True)), optional=True, ), ScalarField("RenewalEligibility", optional=True), ) @classmethod def list_from_aws(cls: Type["ACMCertificateResourceSpec"], client: BaseClient, account_id: str, region: str) -> ListFromAWSResult: cert_arns: List[str] = [] paginator = client.get_paginator("list_certificates") for resp in paginator.paginate( Includes={ "keyTypes": [ "RSA_1024", "RSA_2048", "RSA_3072", "RSA_4096", "EC_prime256v1", "EC_secp384r1", "EC_secp521r1", ] }): cert_arns.extend([ cert_dict["CertificateArn"] for cert_dict in resp.get("CertificateSummaryList", []) ]) certs: Dict[str, Dict[str, Any]] = {} for cert_arn in cert_arns: try: cert_data = get_cert_data(client=client, cert_arn=cert_arn) certs[cert_arn] = cert_data except ClientError as c_e: error_code = getattr(c_e, "response", {}).get("Error", {}).get("Code", {}) if error_code not in ("ResourceNotFoundException", ): raise c_e return ListFromAWSResult(resources=certs)