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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
|
"""Route53ResolverBackend class with methods for supported APIs."""
import re
from collections import defaultdict
from datetime import datetime, timezone
from ipaddress import IPv4Address, ip_address, ip_network
from typing import Any, Optional
from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel
from moto.ec2 import ec2_backends
from moto.ec2.exceptions import InvalidSecurityGroupNotFoundError, InvalidSubnetIdError
from moto.moto_api._internal import mock_random
from moto.route53resolver.exceptions import (
InvalidParameterException,
InvalidRequestException,
LimitExceededException,
ResourceExistsException,
ResourceInUseException,
ResourceNotFoundException,
TagValidationException,
)
from moto.route53resolver.utils import PAGINATION_MODEL
from moto.route53resolver.validations import validate_args
from moto.utilities.paginator import paginate
from moto.utilities.tagging_service import TaggingService
from moto.utilities.utils import get_partition
CAMEL_TO_SNAKE_PATTERN = re.compile(r"(?<!^)(?=[A-Z])")
class ResolverRuleAssociation(BaseModel):
"""Representation of a fake Route53 Resolver Rules Association."""
MAX_TAGS_PER_RESOLVER_ENDPOINT = 200
MAX_RULE_ASSOCIATIONS_PER_REGION = 2000
# There are two styles of filter names and either will be transformed
# into lowercase snake.
FILTER_NAMES = [
"name",
"resolver_rule_id",
"status",
"vpc_id",
]
def __init__(
self,
region: str,
resolver_rule_association_id: str,
resolver_rule_id: str,
vpc_id: str,
name: str,
):
self.region = region
self.resolver_rule_id = resolver_rule_id
self.name = name
self.vpc_id = vpc_id
# Constructed members.
self.id = resolver_rule_association_id
self.status = "COMPLETE"
self.status_message = ""
def description(self) -> dict[str, Any]:
"""Return dictionary of relevant info for resolver rule association."""
return {
"Id": self.id,
"ResolverRuleId": self.resolver_rule_id,
"Name": self.name,
"VPCId": self.vpc_id,
"Status": self.status,
"StatusMessage": self.status_message,
}
class ResolverRule(BaseModel):
"""Representation of a fake Route53 Resolver Rule."""
MAX_TAGS_PER_RESOLVER_RULE = 200
MAX_RULES_PER_REGION = 1000
# There are two styles of filter names and either will be transformed
# into lowercase snake.
FILTER_NAMES = [
"creator_request_id",
"domain_name",
"name",
"resolver_endpoint_id",
"status",
"rule_type", # actual filter is "Type"
]
def __init__(
self,
account_id: str,
region: str,
rule_id: str,
creator_request_id: str,
rule_type: str,
domain_name: str,
target_ips: Optional[list[dict[str, Any]]],
resolver_endpoint_id: Optional[str],
name: str,
):
self.account_id = account_id
self.region = region
self.creator_request_id = creator_request_id
self.name = name
self.rule_id = rule_id
self.rule_type = rule_type
self.domain_name = domain_name + "."
self.target_ips = target_ips
self.resolver_endpoint_id = resolver_endpoint_id
# Constructed members.
self.id = rule_id
self.status = "COMPLETE"
# The status message should contain a trace Id which is the value
# of X-Amzn-Trace-Id. We don't have that info, so a random number
# of similar format and length will be used.
self.status_message = (
f"[Trace id: 1-{mock_random.get_random_hex(8)}-{mock_random.get_random_hex(24)}] "
f"Successfully created Resolver Rule"
)
self.share_status = "NOT_SHARED"
self.creation_time = datetime.now(timezone.utc).isoformat()
self.modification_time = datetime.now(timezone.utc).isoformat()
@property
def arn(self) -> str:
return f"arn:{get_partition(self.region)}:route53resolver:{self.region}:{self.account_id}:resolver-rule/{self.id}"
def description(self) -> dict[str, Any]:
"""Return a dictionary of relevant info for this resolver rule."""
return {
"Id": self.id,
"CreatorRequestId": self.creator_request_id,
"Arn": self.arn,
"DomainName": self.domain_name,
"Status": self.status,
"StatusMessage": self.status_message,
"RuleType": self.rule_type,
"Name": self.name,
"TargetIps": self.target_ips,
"ResolverEndpointId": self.resolver_endpoint_id,
"OwnerId": self.account_id,
"ShareStatus": self.share_status,
"CreationTime": self.creation_time,
"ModificationTime": self.modification_time,
}
class ResolverEndpoint(BaseModel):
"""Representation of a fake Route53 Resolver Endpoint."""
MAX_TAGS_PER_RESOLVER_ENDPOINT = 200
MAX_ENDPOINTS_PER_REGION = 4
# There are two styles of filter names and either will be transformed
# into lowercase snake.
FILTER_NAMES = [
"creator_request_id",
"direction",
"host_vpc_id",
"ip_address_count",
"name",
"security_group_ids",
"status",
]
def __init__(
self,
account_id: str,
region: str,
endpoint_id: str,
creator_request_id: str,
security_group_ids: list[str],
direction: str,
ip_addresses: list[dict[str, Any]],
name: str,
):
self.account_id = account_id
self.region = region
self.creator_request_id = creator_request_id
self.name = name
self.security_group_ids = security_group_ids
self.direction = direction
self.ip_addresses = ip_addresses
self.ec2_backend = ec2_backends[self.account_id][self.region]
# Constructed members.
self.id = endpoint_id
# NOTE; This currently doesn't reflect IPv6 addresses.
self.subnets = self._build_subnet_info()
self.eni_ids = self.create_eni()
self.ip_address_count = len(ip_addresses)
self.host_vpc_id = self._vpc_id_from_subnet()
self.status = "OPERATIONAL"
# The status message should contain a trace Id which is the value
# of X-Amzn-Trace-Id. We don't have that info, so a random number
# of similar format and length will be used.
self.status_message = (
f"[Trace id: 1-{mock_random.get_random_hex(8)}-{mock_random.get_random_hex(24)}] "
f"Successfully created Resolver Endpoint"
)
self.creation_time = datetime.now(timezone.utc).isoformat()
self.modification_time = datetime.now(timezone.utc).isoformat()
@property
def arn(self) -> str:
return f"arn:{get_partition(self.region)}:route53resolver:{self.region}:{self.account_id}:resolver-endpoint/{self.id}"
def _vpc_id_from_subnet(self) -> str:
"""Return VPC Id associated with the subnet.
The assumption is that all of the subnets are associated with the
same VPC. We don't check that assumption, but otherwise the existence
of the subnets has already been checked.
"""
first_subnet_id = self.ip_addresses[0]["SubnetId"]
subnet_info = self.ec2_backend.describe_subnets(subnet_ids=[first_subnet_id])[0]
return subnet_info.vpc_id
def _build_subnet_info(self) -> dict[str, Any]:
"""Create a dict of subnet info, including ip addrs and ENI ids.
self.subnets[subnet_id][ip_addr1] = eni-id1 ...
"""
subnets: dict[str, Any] = defaultdict(dict)
for entry in self.ip_addresses:
subnets[entry["SubnetId"]][entry["Ip"]] = (
f"rni-{mock_random.get_random_hex(17)}"
)
return subnets
def create_eni(self) -> list[str]:
"""Create a VPC ENI for each combo of AZ, subnet and IP."""
eni_ids = []
for subnet, ip_info in self.subnets.items():
for ip_addr, eni_id in ip_info.items():
eni_info = self.ec2_backend.create_network_interface(
description=f"Route 53 Resolver: {self.id}:{eni_id}",
group_ids=self.security_group_ids,
interface_type="interface",
private_ip_address=ip_addr,
private_ip_addresses=[
{"Primary": True, "PrivateIpAddress": ip_addr}
],
subnet=subnet,
)
eni_ids.append(eni_info.id)
return eni_ids
def delete_eni(self) -> None:
"""Delete the VPC ENI created for the subnet and IP combos."""
for eni_id in self.eni_ids:
self.ec2_backend.delete_network_interface(eni_id)
def description(self) -> dict[str, Any]:
"""Return a dictionary of relevant info for this resolver endpoint."""
return {
"Id": self.id,
"CreatorRequestId": self.creator_request_id,
"Arn": self.arn,
"Name": self.name,
"SecurityGroupIds": self.security_group_ids,
"Direction": self.direction,
"IpAddressCount": self.ip_address_count,
"HostVPCId": self.host_vpc_id,
"Status": self.status,
"StatusMessage": self.status_message,
"CreationTime": self.creation_time,
"ModificationTime": self.modification_time,
}
def ip_descriptions(self) -> list[dict[str, str]]:
"""Return a list of dicts describing resolver endpoint IP addresses."""
description = []
for subnet_id, ip_info in self.subnets.items():
for ip_addr, eni_id in ip_info.items():
description.append(
{
"IpId": eni_id,
"SubnetId": subnet_id,
"Ip": ip_addr,
"Status": "ATTACHED",
"StatusMessage": "This IP address is operational.",
"CreationTime": self.creation_time,
"ModificationTime": self.modification_time,
}
)
return description
def update_name(self, name: str) -> None:
"""Replace existing name with new name."""
self.name = name
self.modification_time = datetime.now(timezone.utc).isoformat()
def associate_ip_address(self, value: dict[str, Any]) -> None:
self.ip_addresses.append(value)
self.ip_address_count = len(self.ip_addresses)
eni_id = f"rni-{mock_random.get_random_hex(17)}"
self.subnets[value["SubnetId"]][value["Ip"]] = eni_id
eni_info = self.ec2_backend.create_network_interface(
description=f"Route 53 Resolver: {self.id}:{eni_id}",
group_ids=self.security_group_ids,
interface_type="interface",
private_ip_address=value.get("Ip"), # type: ignore[arg-type]
private_ip_addresses=[
{"Primary": True, "PrivateIpAddress": value.get("Ip")}
],
subnet=value.get("SubnetId"),
)
self.eni_ids.append(eni_info.id)
def disassociate_ip_address(self, value: dict[str, Any]) -> None:
if not value.get("Ip") and value.get("IpId"):
for ip_addr, eni_id in self.subnets[value.get("SubnetId")].items(): # type: ignore
if value.get("IpId") == eni_id:
value["Ip"] = ip_addr
if value.get("Ip"):
self.ip_addresses = list(
filter(lambda i: i["Ip"] != value.get("Ip"), self.ip_addresses)
)
if len(self.subnets[value["SubnetId"]]) == 1:
self.subnets.pop(value["SubnetId"])
else:
self.subnets[value["SubnetId"]].pop(value["Ip"])
for eni_id in self.eni_ids:
eni_info = self.ec2_backend.get_network_interface(eni_id)
if eni_info.private_ip_address == value.get("Ip"):
self.ec2_backend.delete_network_interface(eni_id)
self.eni_ids.remove(eni_id)
self.ip_address_count = len(self.ip_addresses)
class ResolverQueryLogConfig(BaseModel):
"""Representation of a fake Route53 Resolver Query Log Config."""
MAX_TAGS_PER_QUERY_LOG_CONFIG = 50
MAX_QUERY_LOG_CONFIGS_PER_REGION = 100
def __init__(
self,
account_id: str,
region: str,
config_id: str,
name: str,
destination_arn: str,
creator_request_id: str,
):
self.account_id = account_id
self.region = region
self.id = config_id
self.name = name
self.destination_arn = destination_arn
self.creator_request_id = creator_request_id
self.status = "CREATED"
self.share_status = "NOT_SHARED"
self.association_count = 0
self.creation_time = datetime.now(timezone.utc).isoformat()
@property
def arn(self) -> str:
return f"arn:{get_partition(self.region)}:route53resolver:{self.region}:{self.account_id}:resolver-query-log-config/{self.id}"
def description(self) -> dict[str, Any]:
"""Return a dictionary of relevant info for this query log config."""
return {
"Id": self.id,
"OwnerId": self.account_id,
"Status": self.status,
"ShareStatus": self.share_status,
"AssociationCount": self.association_count,
"Arn": self.arn,
"Name": self.name,
"DestinationArn": self.destination_arn,
"CreatorRequestId": self.creator_request_id,
"CreationTime": self.creation_time,
}
class ResolverQueryLogConfigAssociation(BaseModel):
"""Representation of an association between a VPC and a query logging configuration."""
def __init__(
self,
region: str,
association_id: str,
resolver_query_log_config_id: str,
resource_id: str,
):
self.region = region
self.id = association_id
self.resolver_query_log_config_id = resolver_query_log_config_id
self.resource_id = resource_id
self.status = "ACTIVE"
self.error = "NONE"
self.error_message = ""
self.creation_time = datetime.now(timezone.utc).isoformat()
def description(self) -> dict[str, Any]:
"""Return a dictionary of relevant info for this query log config association."""
return {
"Id": self.id,
"ResolverQueryLogConfigId": self.resolver_query_log_config_id,
"ResourceId": self.resource_id,
"Status": self.status,
"Error": self.error,
"ErrorMessage": self.error_message,
"CreationTime": self.creation_time,
}
class Route53ResolverBackend(BaseBackend):
"""Implementation of Route53Resolver APIs."""
def __init__(self, region_name: str, account_id: str):
super().__init__(region_name, account_id)
self.resolver_endpoints: dict[
str, ResolverEndpoint
] = {} # Key is self-generated ID (endpoint_id)
self.resolver_rules: dict[
str, ResolverRule
] = {} # Key is self-generated ID (rule_id)
self.resolver_rule_associations: dict[
str, ResolverRuleAssociation
] = {} # Key is resolver_rule_association_id)
self.resolver_query_log_configs: dict[
str, ResolverQueryLogConfig
] = {} # Key is resolver_query_log_config_id
self.resolver_query_log_config_associations: dict[
str, ResolverQueryLogConfigAssociation
] = {} # Key is resolver_query_log_config_association_id
self.tagger = TaggingService()
self.ec2_backend = ec2_backends[self.account_id][self.region_name]
@staticmethod
def default_vpc_endpoint_service(
service_region: str, zones: list[str]
) -> list[dict[str, str]]:
"""List of dicts representing default VPC endpoints for this service."""
return BaseBackend.default_vpc_endpoint_service_factory(
service_region, zones, "route53resolver"
)
def associate_resolver_rule(
self, resolver_rule_id: str, name: str, vpc_id: str
) -> ResolverRuleAssociation:
validate_args(
[("resolverRuleId", resolver_rule_id), ("name", name), ("vPCId", vpc_id)]
)
associations = [
x
for x in self.resolver_rule_associations.values()
if x.region == self.region_name
]
if len(associations) > ResolverRuleAssociation.MAX_RULE_ASSOCIATIONS_PER_REGION:
# This error message was not verified to be the same for AWS.
raise LimitExceededException(
f"Account '{self.account_id}' has exceeded 'max-rule-association'"
)
if resolver_rule_id not in self.resolver_rules:
raise ResourceNotFoundException(
f"Resolver rule with ID '{resolver_rule_id}' does not exist."
)
vpcs = self.ec2_backend.describe_vpcs()
if vpc_id not in [x.id for x in vpcs]:
raise InvalidParameterException(f"The vpc ID '{vpc_id}' does not exist")
# Can't duplicate resolver rule, vpc id associations.
for association in self.resolver_rule_associations.values():
if (
resolver_rule_id == association.resolver_rule_id
and vpc_id == association.vpc_id
):
raise InvalidRequestException(
f"Cannot associate rules with same domain name with same "
f"VPC. Conflict with resolver rule '{resolver_rule_id}'"
)
rule_association_id = f"rslvr-rrassoc-{mock_random.get_random_hex(17)}"
rule_association = ResolverRuleAssociation(
self.region_name, rule_association_id, resolver_rule_id, vpc_id, name
)
self.resolver_rule_associations[rule_association_id] = rule_association
return rule_association
def _verify_subnet_ips(
self, ip_addresses: list[dict[str, Any]], initial: bool = True
) -> None:
"""
Perform additional checks on the IPAddresses.
NOTE: This does not include IPv6 addresses.
"""
# only initial endpoint creation requires atleast two ip addresses
if initial:
if len(ip_addresses) < 2:
raise InvalidRequestException(
"Resolver endpoint needs to have at least 2 IP addresses"
)
subnets: dict[str, set[str]] = defaultdict(set)
for subnet_id, ip_addr in [(x["SubnetId"], x["Ip"]) for x in ip_addresses]:
try:
subnet_info = self.ec2_backend.describe_subnets(subnet_ids=[subnet_id])[
0
]
except InvalidSubnetIdError as exc:
raise InvalidParameterException(
f"The subnet ID '{subnet_id}' does not exist"
) from exc
# IP in IPv4 CIDR range and not reserved?
if ip_address(ip_addr) in subnet_info.reserved_ips or ip_address(
ip_addr
) not in ip_network(subnet_info.cidr_block):
raise InvalidRequestException(
f"IP address '{ip_addr}' is either not in subnet "
f"'{subnet_id}' CIDR range or is reserved"
)
if ip_addr in subnets[subnet_id]:
raise ResourceExistsException(
f"The IP address '{ip_addr}' in subnet '{subnet_id}' is already in use"
)
subnets[subnet_id].add(ip_addr)
def _verify_security_group_ids(self, security_group_ids: list[str]) -> None:
"""Perform additional checks on the security groups."""
if len(security_group_ids) > 10:
raise InvalidParameterException("Maximum of 10 security groups are allowed")
for group_id in security_group_ids:
if not group_id.startswith("sg-"):
raise InvalidParameterException(
f"Malformed security group ID: Invalid id: '{group_id}' "
f"(expecting 'sg-...')"
)
try:
self.ec2_backend.describe_security_groups(group_ids=[group_id])
except InvalidSecurityGroupNotFoundError as exc:
raise ResourceNotFoundException(
f"The security group '{group_id}' does not exist"
) from exc
def create_resolver_endpoint(
self,
region: str,
creator_request_id: str,
name: str,
security_group_ids: list[str],
direction: str,
ip_addresses: list[dict[str, Any]],
tags: list[dict[str, str]],
) -> ResolverEndpoint:
"""
Return description for a newly created resolver endpoint.
NOTE: IPv6 IPs are currently not being filtered when
calculating the create_resolver_endpoint() IpAddresses.
"""
validate_args(
[
("creatorRequestId", creator_request_id),
("direction", direction),
("ipAddresses", ip_addresses),
("name", name),
("securityGroupIds", security_group_ids),
("ipAddresses.subnetId", ip_addresses),
]
)
errmsg = self.tagger.validate_tags(
tags or [], limit=ResolverEndpoint.MAX_TAGS_PER_RESOLVER_ENDPOINT
)
if errmsg:
raise TagValidationException(errmsg)
endpoints = [x for x in self.resolver_endpoints.values() if x.region == region]
if len(endpoints) > ResolverEndpoint.MAX_ENDPOINTS_PER_REGION:
raise LimitExceededException(
f"Account '{self.account_id}' has exceeded 'max-endpoints'"
)
for x in ip_addresses:
if not x.get("Ip"):
subnet_info = self.ec2_backend.describe_subnets(
subnet_ids=[x["SubnetId"]]
)[0]
x["Ip"] = subnet_info.get_available_subnet_ip(self) # type: ignore[arg-type]
self._verify_subnet_ips(ip_addresses)
self._verify_security_group_ids(security_group_ids)
if creator_request_id in [
x.creator_request_id for x in self.resolver_endpoints.values()
]:
raise ResourceExistsException(
f"Resolver endpoint with creator request ID "
f"'{creator_request_id}' already exists"
)
endpoint_id = f"rslvr-{'in' if direction == 'INBOUND' else 'out'}-{mock_random.get_random_hex(17)}"
resolver_endpoint = ResolverEndpoint(
self.account_id,
region,
endpoint_id,
creator_request_id,
security_group_ids,
direction,
ip_addresses,
name,
)
self.resolver_endpoints[endpoint_id] = resolver_endpoint
self.tagger.tag_resource(resolver_endpoint.arn, tags or [])
return resolver_endpoint
def create_resolver_rule(
self,
region: str,
creator_request_id: str,
name: str,
rule_type: str,
domain_name: str,
target_ips: list[dict[str, Any]],
resolver_endpoint_id: str,
tags: list[dict[str, str]],
) -> ResolverRule:
"""Return description for a newly created resolver rule."""
validate_args(
[
("creatorRequestId", creator_request_id),
("ruleType", rule_type),
("domainName", domain_name),
("name", name),
*[("targetIps.port", x) for x in target_ips],
("resolverEndpointId", resolver_endpoint_id),
]
)
errmsg = self.tagger.validate_tags(
tags or [], limit=ResolverRule.MAX_TAGS_PER_RESOLVER_RULE
)
if errmsg:
raise TagValidationException(errmsg)
rules = [x for x in self.resolver_rules.values() if x.region == region]
if len(rules) > ResolverRule.MAX_RULES_PER_REGION:
# Did not verify that this is the actual error message.
raise LimitExceededException(
f"Account '{self.account_id}' has exceeded 'max-rules'"
)
# Per the AWS documentation and as seen with the AWS console, target
# ips are only relevant when the value of Rule is FORWARD. However,
# boto3 ignores this condition and so shall we.
for ip_addr in [x["Ip"] for x in target_ips]:
try:
# boto3 fails with an InternalServiceException if IPv6
# addresses are used, which isn't helpful.
if not isinstance(ip_address(ip_addr), IPv4Address):
raise InvalidParameterException(
f"Only IPv4 addresses may be used: '{ip_addr}'"
)
except ValueError as exc:
raise InvalidParameterException(
f"Invalid IP address: '{ip_addr}'"
) from exc
# The boto3 documentation indicates that ResolverEndpoint is
# optional, as does the AWS documention. But if resolver_endpoint_id
# is set to None or an empty string, it results in boto3 raising
# a ParamValidationError either regarding the type or len of string.
if resolver_endpoint_id:
if resolver_endpoint_id not in [
x.id for x in self.resolver_endpoints.values()
]:
raise ResourceNotFoundException(
f"Resolver endpoint with ID '{resolver_endpoint_id}' does not exist."
)
if rule_type == "SYSTEM":
raise InvalidRequestException(
"Cannot specify resolver endpoint ID and target IP "
"for SYSTEM type resolver rule"
)
if creator_request_id in [
x.creator_request_id for x in self.resolver_rules.values()
]:
raise ResourceExistsException(
f"Resolver rule with creator request ID "
f"'{creator_request_id}' already exists"
)
rule_id = f"rslvr-rr-{mock_random.get_random_hex(17)}"
resolver_rule = ResolverRule(
account_id=self.account_id,
region=region,
rule_id=rule_id,
creator_request_id=creator_request_id,
rule_type=rule_type,
domain_name=domain_name,
target_ips=target_ips,
resolver_endpoint_id=resolver_endpoint_id,
name=name,
)
self.resolver_rules[rule_id] = resolver_rule
self.tagger.tag_resource(resolver_rule.arn, tags or [])
return resolver_rule
def _validate_resolver_endpoint_id(self, resolver_endpoint_id: str) -> None:
"""Raise an exception if the id is invalid or unknown."""
validate_args([("resolverEndpointId", resolver_endpoint_id)])
if resolver_endpoint_id not in self.resolver_endpoints:
raise ResourceNotFoundException(
f"Resolver endpoint with ID '{resolver_endpoint_id}' does not exist"
)
def delete_resolver_endpoint(self, resolver_endpoint_id: str) -> ResolverEndpoint:
self._validate_resolver_endpoint_id(resolver_endpoint_id)
# Can't delete an endpoint if there are rules associated with it.
rules = [
x.id
for x in self.resolver_rules.values()
if x.resolver_endpoint_id == resolver_endpoint_id
]
if rules:
raise InvalidRequestException(
f"Cannot delete resolver endpoint unless its related resolver "
f"rules are deleted. The following rules still exist for "
f"this resolver endpoint: {','.join(rules)}"
)
self.tagger.delete_all_tags_for_resource(resolver_endpoint_id)
resolver_endpoint = self.resolver_endpoints.pop(resolver_endpoint_id)
resolver_endpoint.delete_eni()
resolver_endpoint.status = "DELETING"
resolver_endpoint.status_message = resolver_endpoint.status_message.replace(
"Successfully created", "Deleting"
)
return resolver_endpoint
def _validate_resolver_rule_id(self, resolver_rule_id: str) -> None:
"""Raise an exception if the id is invalid or unknown."""
validate_args([("resolverRuleId", resolver_rule_id)])
if resolver_rule_id not in self.resolver_rules:
raise ResourceNotFoundException(
f"Resolver rule with ID '{resolver_rule_id}' does not exist"
)
def delete_resolver_rule(self, resolver_rule_id: str) -> ResolverRule:
self._validate_resolver_rule_id(resolver_rule_id)
# Can't delete an rule unless VPC's are disassociated.
associations = [
x.id
for x in self.resolver_rule_associations.values()
if x.resolver_rule_id == resolver_rule_id
]
if associations:
raise ResourceInUseException(
"Please disassociate this resolver rule from VPC first before deleting"
)
self.tagger.delete_all_tags_for_resource(resolver_rule_id)
resolver_rule = self.resolver_rules.pop(resolver_rule_id)
resolver_rule.status = "DELETING"
resolver_rule.status_message = resolver_rule.status_message.replace(
"Successfully created", "Deleting"
)
return resolver_rule
def disassociate_resolver_rule(
self, resolver_rule_id: str, vpc_id: str
) -> ResolverRuleAssociation:
validate_args([("resolverRuleId", resolver_rule_id), ("vPCId", vpc_id)])
# Non-existent rule or vpc ids?
if resolver_rule_id not in self.resolver_rules:
raise ResourceNotFoundException(
f"Resolver rule with ID '{resolver_rule_id}' does not exist"
)
# Find the matching association for this rule and vpc.
rule_association_id = None
for association in self.resolver_rule_associations.values():
if (
resolver_rule_id == association.resolver_rule_id
and vpc_id == association.vpc_id
):
rule_association_id = association.id
break
else:
raise ResourceNotFoundException(
f"Resolver Rule Association between Resolver Rule "
f"'{resolver_rule_id}' and VPC '{vpc_id}' does not exist"
)
rule_association = self.resolver_rule_associations.pop(rule_association_id)
rule_association.status = "DELETING"
rule_association.status_message = "Deleting Association"
return rule_association
def get_resolver_endpoint(self, resolver_endpoint_id: str) -> ResolverEndpoint:
self._validate_resolver_endpoint_id(resolver_endpoint_id)
return self.resolver_endpoints[resolver_endpoint_id]
def get_resolver_rule(self, resolver_rule_id: str) -> ResolverRule:
"""Return info for specified resolver rule."""
self._validate_resolver_rule_id(resolver_rule_id)
return self.resolver_rules[resolver_rule_id]
def get_resolver_rule_association(
self, resolver_rule_association_id: str
) -> ResolverRuleAssociation:
validate_args([("resolverRuleAssociationId", resolver_rule_association_id)])
if resolver_rule_association_id not in self.resolver_rule_associations:
raise ResourceNotFoundException(
f"ResolverRuleAssociation '{resolver_rule_association_id}' does not Exist"
)
return self.resolver_rule_associations[resolver_rule_association_id]
@paginate(pagination_model=PAGINATION_MODEL) # type: ignore[misc]
def list_resolver_endpoint_ip_addresses(
self, resolver_endpoint_id: str
) -> list[dict[str, str]]:
self._validate_resolver_endpoint_id(resolver_endpoint_id)
endpoint = self.resolver_endpoints[resolver_endpoint_id]
return endpoint.ip_descriptions()
@staticmethod
def _add_field_name_to_filter(filters: list[dict[str, Any]]) -> None: # type: ignore[misc]
"""Convert both styles of filter names to lowercase snake format.
"IP_ADDRESS_COUNT" or "IpAddressCount" will become "ip_address_count".
However, "HostVPCId" doesn't fit the pattern, so that's treated
special.
"""
for rr_filter in filters:
filter_name = rr_filter["Name"]
if "_" not in filter_name:
if "Vpc" in filter_name:
filter_name = "WRONG"
elif filter_name == "HostVPCId":
filter_name = "host_vpc_id"
elif filter_name == "VPCId":
filter_name = "vpc_id"
elif filter_name in ["Type", "TYPE"]:
filter_name = "rule_type"
elif not filter_name.isupper():
filter_name = CAMEL_TO_SNAKE_PATTERN.sub("_", filter_name)
rr_filter["Field"] = filter_name.lower()
@staticmethod
def _validate_filters(filters: Any, allowed_filter_names: list[str]) -> None: # type: ignore[misc]
"""Raise exception if filter names are not as expected."""
for rr_filter in filters:
if rr_filter["Field"] not in allowed_filter_names:
raise InvalidParameterException(
f"The filter '{rr_filter['Name']}' is invalid"
)
if "Values" not in rr_filter:
raise InvalidParameterException(
f"No values specified for filter {rr_filter['Name']}"
)
@staticmethod
def _matches_all_filters(entity: Any, filters: Any) -> bool: # type: ignore[misc]
"""Return True if this entity has fields matching all the filters."""
for rr_filter in filters:
field_value = getattr(entity, rr_filter["Field"])
if isinstance(field_value, list):
if not set(field_value).intersection(rr_filter["Values"]):
return False
elif isinstance(field_value, int):
if str(field_value) not in rr_filter["Values"]:
return False
elif field_value not in rr_filter["Values"]:
return False
return True
@paginate(pagination_model=PAGINATION_MODEL)
def list_resolver_endpoints(self, filters: Any) -> list[ResolverEndpoint]:
if not filters:
filters = []
self._add_field_name_to_filter(filters)
self._validate_filters(filters, ResolverEndpoint.FILTER_NAMES)
endpoints = []
for endpoint in sorted(self.resolver_endpoints.values(), key=lambda x: x.name):
if self._matches_all_filters(endpoint, filters):
endpoints.append(endpoint)
return endpoints
@paginate(pagination_model=PAGINATION_MODEL)
def list_resolver_rules(self, filters: Any) -> list[ResolverRule]:
if not filters:
filters = []
self._add_field_name_to_filter(filters)
self._validate_filters(filters, ResolverRule.FILTER_NAMES)
rules = []
for rule in sorted(self.resolver_rules.values(), key=lambda x: x.name):
if self._matches_all_filters(rule, filters):
rules.append(rule)
return rules
@paginate(pagination_model=PAGINATION_MODEL)
def list_resolver_rule_associations(
self, filters: Any
) -> list[ResolverRuleAssociation]:
if not filters:
filters = []
self._add_field_name_to_filter(filters)
self._validate_filters(filters, ResolverRuleAssociation.FILTER_NAMES)
rules = []
for rule in sorted(
self.resolver_rule_associations.values(), key=lambda x: x.name
):
if self._matches_all_filters(rule, filters):
rules.append(rule)
return rules
def _matched_arn(self, resource_arn: str) -> None:
"""Given ARN, raise exception if there is no corresponding resource."""
for resolver_endpoint in self.resolver_endpoints.values():
if resolver_endpoint.arn == resource_arn:
return
for resolver_rule in self.resolver_rules.values():
if resolver_rule.arn == resource_arn:
return
raise ResourceNotFoundException(
f"Resolver endpoint with ID '{resource_arn}' does not exist"
)
@paginate(pagination_model=PAGINATION_MODEL)
def list_tags_for_resource(self, resource_arn: str) -> list[dict[str, str]]:
self._matched_arn(resource_arn)
return self.tagger.list_tags_for_resource(resource_arn)["Tags"]
def tag_resource(self, resource_arn: str, tags: list[dict[str, str]]) -> None:
self._matched_arn(resource_arn)
errmsg = self.tagger.validate_tags(
tags, limit=ResolverEndpoint.MAX_TAGS_PER_RESOLVER_ENDPOINT
)
if errmsg:
raise TagValidationException(errmsg)
self.tagger.tag_resource(resource_arn, tags)
def untag_resource(self, resource_arn: str, tag_keys: list[str]) -> None:
self._matched_arn(resource_arn)
self.tagger.untag_resource_using_names(resource_arn, tag_keys)
def update_resolver_endpoint(
self, resolver_endpoint_id: str, name: str
) -> ResolverEndpoint:
self._validate_resolver_endpoint_id(resolver_endpoint_id)
validate_args([("name", name)])
resolver_endpoint = self.resolver_endpoints[resolver_endpoint_id]
resolver_endpoint.update_name(name)
return resolver_endpoint
def associate_resolver_endpoint_ip_address(
self, resolver_endpoint_id: str, value: dict[str, Any]
) -> ResolverEndpoint:
self._validate_resolver_endpoint_id(resolver_endpoint_id)
resolver_endpoint = self.resolver_endpoints[resolver_endpoint_id]
if not value.get("Ip"):
subnet_info = self.ec2_backend.describe_subnets(
subnet_ids=[value.get("SubnetId")] # type: ignore[list-item]
)[0]
value["Ip"] = subnet_info.get_available_subnet_ip(self) # type: ignore[arg-type]
self._verify_subnet_ips([value], False)
resolver_endpoint.associate_ip_address(value)
return resolver_endpoint
def disassociate_resolver_endpoint_ip_address(
self, resolver_endpoint_id: str, value: dict[str, Any]
) -> ResolverEndpoint:
self._validate_resolver_endpoint_id(resolver_endpoint_id)
resolver_endpoint = self.resolver_endpoints[resolver_endpoint_id]
if not (value.get("Ip") or value.get("IpId")):
raise InvalidRequestException(
"[RSLVR-00503] Need to specify either the IP ID or both subnet and IP address in order to remove IP address."
)
resolver_endpoint.disassociate_ip_address(value)
return resolver_endpoint
def create_resolver_query_log_config(
self,
name: str,
destination_arn: str,
creator_request_id: str,
tags: Optional[list[dict[str, str]]] = None,
) -> ResolverQueryLogConfig:
if tags:
errmsg = self.tagger.validate_tags(
tags, limit=ResolverQueryLogConfig.MAX_TAGS_PER_QUERY_LOG_CONFIG
)
if errmsg:
raise TagValidationException(errmsg)
# Checks if we have reached the limit for the number of query log configs
configs = [
x
for x in self.resolver_query_log_configs.values()
if x.region == self.region_name
]
if len(configs) >= ResolverQueryLogConfig.MAX_QUERY_LOG_CONFIGS_PER_REGION:
raise LimitExceededException(
f"Account '{self.account_id}' has exceeded 'max-query-log-configs'"
)
if creator_request_id in [
x.creator_request_id for x in self.resolver_query_log_configs.values()
]:
raise ResourceExistsException(
f"Resolver query log config with creator request ID "
f"'{creator_request_id}' already exists"
)
config_id = f"rslvr-qlc-{mock_random.get_random_hex(17)}"
query_log_config = ResolverQueryLogConfig(
account_id=self.account_id,
region=self.region_name,
config_id=config_id,
name=name,
destination_arn=destination_arn,
creator_request_id=creator_request_id,
)
self.resolver_query_log_configs[config_id] = query_log_config
if tags:
self.tagger.tag_resource(query_log_config.arn, tags)
return query_log_config
def associate_resolver_query_log_config(
self, resolver_query_log_config_id: str, resource_id: str
) -> ResolverQueryLogConfigAssociation:
"""Associate a VPC with a resolver query log config."""
if resolver_query_log_config_id not in self.resolver_query_log_configs:
raise ResourceNotFoundException(
f"Resolver query log config with ID '{resolver_query_log_config_id}' does not exist"
)
vpcs = self.ec2_backend.describe_vpcs()
if resource_id not in [x.id for x in vpcs]:
raise InvalidParameterException(
f"The vpc ID '{resource_id}' does not exist"
)
for association in self.resolver_query_log_config_associations.values():
if (
association.resolver_query_log_config_id == resolver_query_log_config_id
and association.resource_id == resource_id
):
raise ResourceExistsException(
f"Resolver query log config '{resolver_query_log_config_id}' is already associated with VPC '{resource_id}'"
)
association_id = f"rslvr-qla-{mock_random.get_random_hex(17)}"
association = ResolverQueryLogConfigAssociation(
region=self.region_name,
association_id=association_id,
resolver_query_log_config_id=resolver_query_log_config_id,
resource_id=resource_id,
)
query_log_config = self.resolver_query_log_configs[resolver_query_log_config_id]
query_log_config.association_count += 1
self.resolver_query_log_config_associations[association_id] = association
return association
def get_resolver_query_log_config(
self, resolver_query_log_config_id: str
) -> ResolverQueryLogConfig:
"""Get information about a resolver query log config."""
if resolver_query_log_config_id not in self.resolver_query_log_configs:
raise ResourceNotFoundException(
f"Resolver query log config with ID '{resolver_query_log_config_id}' does not exist"
)
return self.resolver_query_log_configs[resolver_query_log_config_id]
route53resolver_backends = BackendDict(Route53ResolverBackend, "route53resolver")
|