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
|
import json
import re
from typing import Any, Optional
from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel
from moto.utilities.utils import ARN_PARTITION_REGEX, get_partition
from .exceptions import BadRequestException, NotFoundException
class FakeResourceGroup(BaseModel):
def __init__(
self,
account_id: str,
region_name: str,
name: str,
resource_query: dict[str, str],
description: Optional[str] = None,
tags: Optional[dict[str, str]] = None,
configuration: Optional[list[dict[str, Any]]] = None,
):
self.errors: list[str] = []
description = description or ""
tags = tags or {}
if self._validate_description(value=description):
self._description = description
if self._validate_name(value=name):
self._name = name
if self._validate_resource_query(value=resource_query):
self._resource_query = resource_query
if self._validate_tags(value=tags):
self._tags = tags
self._raise_errors()
self.arn = f"arn:{get_partition(region_name)}:resource-groups:us-west-1:{account_id}:{name}"
self.configuration = configuration
@staticmethod
def _format_error(key: str, value: Any, constraint: str) -> str: # type: ignore[misc]
return f"Value '{value}' at '{key}' failed to satisfy constraint: {constraint}"
def _raise_errors(self) -> None:
if self.errors:
errors_len = len(self.errors)
plural = "s" if len(self.errors) > 1 else ""
errors = "; ".join(self.errors)
raise BadRequestException(
f"{errors_len} validation error{plural} detected: {errors}"
)
def _validate_description(self, value: str) -> bool:
errors = []
if len(value) > 511:
errors.append(
self._format_error(
key="description",
value=value,
constraint="Member must have length less than or equal to 512",
)
)
if not re.match(r"^[\sa-zA-Z0-9_.-]*$", value):
errors.append(
self._format_error(
key="name",
value=value,
constraint=r"Member must satisfy regular expression pattern: [\sa-zA-Z0-9_\.-]*",
)
)
if errors:
self.errors += errors
return False
return True
def _validate_name(self, value: str) -> bool:
errors = []
if len(value) > 128:
errors.append(
self._format_error(
key="name",
value=value,
constraint="Member must have length less than or equal to 128",
)
)
# Note \ is a character to match not an escape.
if not re.match(r"^[a-zA-Z0-9_\\.-]+$", value):
errors.append(
self._format_error(
key="name",
value=value,
constraint=r"Member must satisfy regular expression pattern: [a-zA-Z0-9_\.-]+",
)
)
if errors:
self.errors += errors
return False
return True
def _validate_resource_query(self, value: dict[str, str]) -> bool:
if not value:
return True
errors = []
if value["Type"] not in {"CLOUDFORMATION_STACK_1_0", "TAG_FILTERS_1_0"}:
errors.append(
self._format_error(
key="resourceQuery.type",
value=value,
constraint="Member must satisfy enum value set: [CLOUDFORMATION_STACK_1_0, TAG_FILTERS_1_0]",
)
)
if len(value["Query"]) > 2048:
errors.append(
self._format_error(
key="resourceQuery.query",
value=value,
constraint="Member must have length less than or equal to 2048",
)
)
if errors:
self.errors += errors
return False
return True
def _validate_tags(self, value: dict[str, str]) -> bool:
errors = []
# AWS only outputs one error for all keys and one for all values.
error_keys = None
error_values = None
regex = re.compile(r"^([\\p{L}\\p{Z}\\p{N}_.:/=+\-@]*)$")
for tag_key, tag_value in value.items():
# Validation for len(tag_key) >= 1 is done by botocore.
if len(tag_key) > 128 or re.match(regex, tag_key):
error_keys = self._format_error(
key="tags",
value=value,
constraint=(
"Map value must satisfy constraint: ["
"Member must have length less than or equal to 128, "
"Member must have length greater than or equal to 1, "
r"Member must satisfy regular expression pattern: ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$"
"]"
),
)
# Validation for len(tag_value) >= 0 is nonsensical.
if len(tag_value) > 256 or re.match(regex, tag_key):
error_values = self._format_error(
key="tags",
value=value,
constraint=(
"Map value must satisfy constraint: ["
"Member must have length less than or equal to 256, "
"Member must have length greater than or equal to 0, "
r"Member must satisfy regular expression pattern: ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$"
"]"
),
)
if error_keys:
errors.append(error_keys)
if error_values:
errors.append(error_values)
if errors:
self.errors += errors
return False
return True
@property
def description(self) -> str:
return self._description
@description.setter
def description(self, value: str) -> None:
if not self._validate_description(value=value):
self._raise_errors()
self._description = value
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, value: str) -> None:
if not self._validate_name(value=value):
self._raise_errors()
self._name = value
@property
def resource_query(self) -> dict[str, str]:
return self._resource_query
@resource_query.setter
def resource_query(self, value: dict[str, str]) -> None:
if not self._validate_resource_query(value=value):
self._raise_errors()
self._resource_query = value
@property
def tags(self) -> dict[str, str]:
return self._tags
@tags.setter
def tags(self, value: dict[str, str]) -> None:
if not self._validate_tags(value=value):
self._raise_errors()
self._tags = value
class ResourceGroups:
def __init__(self) -> None:
self.by_name: dict[str, FakeResourceGroup] = {}
self.by_arn: dict[str, FakeResourceGroup] = {}
def __contains__(self, item: str) -> bool:
return item in self.by_name or item in self.by_arn
def __getitem__(self, item: str) -> FakeResourceGroup:
if item in self.by_name:
return self.by_name[item]
if item in self.by_arn:
return self.by_arn[item]
raise KeyError(f"Resource group '{item}' not found")
def append(self, resource_group: FakeResourceGroup) -> None:
self.by_name[resource_group.name] = resource_group
self.by_arn[resource_group.arn] = resource_group
def delete(self, name: str) -> FakeResourceGroup:
group = self[name]
del self.by_name[group.name]
del self.by_arn[group.arn]
return group
class ResourceGroupsBackend(BaseBackend):
def __init__(self, region_name: str, account_id: str):
super().__init__(region_name, account_id)
self.groups = ResourceGroups()
@staticmethod
def _validate_resource_query(resource_query: dict[str, str]) -> None:
if not resource_query:
return
query_type = resource_query["Type"]
query = json.loads(resource_query["Query"])
query_keys = set(query.keys())
invalid_json_exception = BadRequestException(
"Invalid query: Invalid query format: check JSON syntax"
)
if not isinstance(query["ResourceTypeFilters"], list):
raise invalid_json_exception
if query_type == "CLOUDFORMATION_STACK_1_0":
if query_keys != {"ResourceTypeFilters", "StackIdentifier"}:
raise invalid_json_exception
stack_identifier = query["StackIdentifier"]
if not isinstance(stack_identifier, str):
raise invalid_json_exception
if not re.match(
rf"{ARN_PARTITION_REGEX}:cloudformation:[a-z]{{2}}-[a-z]+-[0-9]+:[0-9]+:stack/[-0-9A-z]+/[-0-9a-f]+$",
stack_identifier,
):
raise BadRequestException(
"Invalid query: Verify that the specified ARN is formatted correctly."
)
# Once checking other resources is implemented.
# if stack_identifier not in self.cloudformation_backend.stacks:
# raise BadRequestException("Invalid query: The specified CloudFormation stack doesn't exist.")
if query_type == "TAG_FILTERS_1_0":
if query_keys != {"ResourceTypeFilters", "TagFilters"}:
raise invalid_json_exception
tag_filters = query["TagFilters"]
if not isinstance(tag_filters, list):
raise invalid_json_exception
if not tag_filters or len(tag_filters) > 50:
raise BadRequestException(
"Invalid query: The TagFilters list must contain between 1 and 50 elements"
)
for tag_filter in tag_filters:
if not isinstance(tag_filter, dict):
raise invalid_json_exception
if set(tag_filter.keys()) != {"Key", "Values"}:
raise invalid_json_exception
key = tag_filter["Key"]
if not isinstance(key, str):
raise invalid_json_exception
if not key:
raise BadRequestException(
"Invalid query: The TagFilter element cannot have empty or null Key field"
)
if len(key) > 128:
raise BadRequestException(
"Invalid query: The maximum length for a tag Key is 128"
)
values = tag_filter["Values"]
if not isinstance(values, list):
raise invalid_json_exception
if len(values) > 20:
raise BadRequestException(
"Invalid query: The TagFilter Values list must contain between 0 and 20 elements"
)
for value in values:
if not isinstance(value, str):
raise invalid_json_exception
if len(value) > 256:
raise BadRequestException(
"Invalid query: The maximum length for a tag Value is 256"
)
@staticmethod
def _validate_tags(tags: dict[str, str]) -> None:
for tag in tags:
if tag.lower().startswith("aws:"):
raise BadRequestException("Tag keys must not start with 'aws:'")
def create_group(
self,
name: str,
resource_query: dict[str, str],
description: Optional[str] = None,
tags: Optional[dict[str, str]] = None,
configuration: Optional[list[dict[str, Any]]] = None,
) -> FakeResourceGroup:
tags = tags or {}
group = FakeResourceGroup(
account_id=self.account_id,
region_name=self.region_name,
name=name,
resource_query=resource_query,
description=description,
tags=tags,
configuration=configuration,
)
if name in self.groups:
raise BadRequestException("Cannot create group: group already exists")
if name.upper().startswith("AWS"):
raise BadRequestException("Group name must not start with 'AWS'")
self._validate_tags(tags)
self._validate_resource_query(resource_query)
self.groups.append(group)
return group
def delete_group(self, group_name: str) -> FakeResourceGroup:
group = self.get_group(group_name)
return self.groups.delete(name=group.name)
def get_group(self, group_name: str) -> FakeResourceGroup:
try:
group = self.groups[group_name]
except KeyError:
raise NotFoundException()
return group
def get_tags(self, arn: str) -> dict[str, str]:
return self.groups.by_arn[arn].tags
def list_groups(self) -> dict[str, FakeResourceGroup]:
"""
Pagination or the Filters-parameter is not yet implemented
"""
return self.groups.by_name
def tag(self, arn: str, tags: dict[str, str]) -> None:
all_tags = self.groups.by_arn[arn].tags
all_tags.update(tags)
self._validate_tags(all_tags)
self.groups.by_arn[arn].tags = all_tags
def untag(self, arn: str, keys: list[str]) -> None:
group = self.groups.by_arn[arn]
for key in keys:
del group.tags[key]
def update_group(
self, group_name: str, description: Optional[str] = None
) -> FakeResourceGroup:
if description:
self.groups.by_name[group_name].description = description
return self.groups.by_name[group_name]
def update_group_query(
self, group_name: str, resource_query: dict[str, str]
) -> FakeResourceGroup:
self._validate_resource_query(resource_query)
self.groups.by_name[group_name].resource_query = resource_query
return self.groups.by_name[group_name]
def get_group_configuration(
self, group_name: str
) -> Optional[list[dict[str, Any]]]:
group = self.groups.by_name[group_name]
return group.configuration
def put_group_configuration(
self, group_name: str, configuration: list[dict[str, Any]]
) -> FakeResourceGroup:
self.groups.by_name[group_name].configuration = configuration
return self.groups.by_name[group_name]
resourcegroups_backends = BackendDict(ResourceGroupsBackend, "resource-groups")
|