moto/moto/core/responses.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1128 lines
40 KiB
Python
Raw Normal View History

import boto3
import functools
import datetime
import json
import logging
2022-08-13 09:49:43 +00:00
import os
import re
import requests
import xmltodict
from collections import defaultdict, OrderedDict
from moto import settings
2022-11-10 18:54:38 -01:00
from moto.core.common_types import TYPE_RESPONSE, TYPE_IF_NONE
from moto.core.exceptions import DryRunClientError
from moto.core.utils import (
camelcase_to_underscores,
method_names_from_class,
params_sort_function,
)
from moto.utilities.utils import load_resource
2022-10-19 20:56:24 +00:00
from jinja2 import Environment, DictLoader, Template
2022-11-10 18:54:38 -01:00
from typing import (
Dict,
Union,
Any,
Tuple,
Optional,
List,
Set,
ClassVar,
Callable,
)
2021-07-26 07:40:39 +01:00
from urllib.parse import parse_qs, parse_qsl, urlparse
from werkzeug.exceptions import HTTPException
from xml.dom.minidom import parseString as parseXML
log = logging.getLogger(__name__)
2022-11-10 18:54:38 -01:00
JINJA_ENVS: Dict[type, Environment] = {}
2022-10-16 18:14:15 +00:00
2022-11-10 18:54:38 -01:00
def _decode_dict(d: Dict[Any, Any]) -> Dict[str, Any]:
decoded: Dict[str, Any] = OrderedDict()
2014-08-26 13:25:50 -04:00
for key, value in d.items():
2021-07-26 07:40:39 +01:00
if isinstance(key, bytes):
2014-08-26 13:25:50 -04:00
newkey = key.decode("utf-8")
else:
newkey = key
2021-07-26 07:40:39 +01:00
if isinstance(value, bytes):
2022-11-10 18:54:38 -01:00
decoded[newkey] = value.decode("utf-8")
2014-08-26 13:25:50 -04:00
elif isinstance(value, (list, tuple)):
newvalue = []
for v in value:
2021-07-26 07:40:39 +01:00
if isinstance(v, bytes):
2014-08-26 13:25:50 -04:00
newvalue.append(v.decode("utf-8"))
else:
newvalue.append(v)
2022-11-10 18:54:38 -01:00
decoded[newkey] = newvalue
2014-08-26 13:25:50 -04:00
else:
2022-11-10 18:54:38 -01:00
decoded[newkey] = value
2014-08-26 13:25:50 -04:00
return decoded
class DynamicDictLoader(DictLoader):
2022-11-10 18:54:38 -01:00
def update(self, mapping: Dict[str, str]) -> None:
self.mapping.update(mapping) # type: ignore[attr-defined]
2022-11-10 18:54:38 -01:00
def contains(self, template: str) -> bool:
return bool(template in self.mapping)
class _TemplateEnvironmentMixin(object):
LEFT_PATTERN = re.compile(r"[\s\n]+<")
RIGHT_PATTERN = re.compile(r">[\s\n]+")
@property
2022-11-10 18:54:38 -01:00
def should_autoescape(self) -> bool:
# Allow for subclass to overwrite
return False
@property
2022-11-10 18:54:38 -01:00
def environment(self) -> Environment:
key = type(self)
try:
environment = JINJA_ENVS[key]
except KeyError:
loader = DynamicDictLoader({})
environment = Environment(
loader=loader,
autoescape=self.should_autoescape,
trim_blocks=True,
lstrip_blocks=True,
)
JINJA_ENVS[key] = environment
return environment
2022-11-10 18:54:38 -01:00
def contains_template(self, template_id: str) -> bool:
return self.environment.loader.contains(template_id) # type: ignore[union-attr]
@classmethod
2022-11-10 18:54:38 -01:00
def _make_template_id(cls, source: str) -> str:
"""
Return a numeric string that's unique for the lifetime of the source.
Jinja2 expects to template IDs to be strings.
"""
return str(id(source))
2022-10-19 20:56:24 +00:00
def response_template(self, source: str) -> Template:
template_id = self._make_template_id(source)
if not self.contains_template(template_id):
if settings.PRETTIFY_RESPONSES:
# pretty xml
xml = parseXML(source).toprettyxml()
else:
# collapsed xml
xml = re.sub(
self.RIGHT_PATTERN, ">", re.sub(self.LEFT_PATTERN, "<", source)
)
2022-11-10 18:54:38 -01:00
self.environment.loader.update({template_id: xml}) # type: ignore[union-attr]
return self.environment.get_template(template_id)
class ActionAuthenticatorMixin(object):
2022-11-10 18:54:38 -01:00
request_count: ClassVar[int] = 0
2022-11-10 18:54:38 -01:00
def _authenticate_and_authorize_action(self, iam_request_cls: type) -> None:
if (
ActionAuthenticatorMixin.request_count
>= settings.INITIAL_NO_AUTH_ACTION_COUNT
):
parsed_url = urlparse(self.uri) # type: ignore[attr-defined]
path = parsed_url.path
if parsed_url.query:
path += "?" + parsed_url.query
iam_request = iam_request_cls(
2022-11-10 18:54:38 -01:00
account_id=self.current_account, # type: ignore[attr-defined]
method=self.method, # type: ignore[attr-defined]
path=path,
2022-11-10 18:54:38 -01:00
data=self.data, # type: ignore[attr-defined]
headers=self.headers, # type: ignore[attr-defined]
)
iam_request.check_signature()
iam_request.check_action_permitted()
else:
ActionAuthenticatorMixin.request_count += 1
2022-11-10 18:54:38 -01:00
def _authenticate_and_authorize_normal_action(self) -> None:
2020-04-30 12:11:33 +01:00
from moto.iam.access_control import IAMRequest
self._authenticate_and_authorize_action(IAMRequest)
2022-11-10 18:54:38 -01:00
def _authenticate_and_authorize_s3_action(self) -> None:
2020-04-30 12:11:33 +01:00
from moto.iam.access_control import S3IAMRequest
self._authenticate_and_authorize_action(S3IAMRequest)
@staticmethod
2022-11-10 18:54:38 -01:00
def set_initial_no_auth_action_count(initial_no_auth_action_count: int) -> Callable[..., Callable[..., TYPE_RESPONSE]]: # type: ignore[misc]
_test_server_mode_endpoint = settings.test_server_mode_endpoint()
2022-11-10 18:54:38 -01:00
def decorator(
function: Callable[..., TYPE_RESPONSE]
) -> Callable[..., TYPE_RESPONSE]:
def wrapper(*args: Any, **kwargs: Any) -> TYPE_RESPONSE:
if settings.TEST_SERVER_MODE:
2019-07-28 22:23:33 +02:00
response = requests.post(
f"{_test_server_mode_endpoint}/moto-api/reset-auth",
data=str(initial_no_auth_action_count).encode("utf-8"),
2019-07-28 22:23:33 +02:00
)
original_initial_no_auth_action_count = response.json()[
"PREVIOUS_INITIAL_NO_AUTH_ACTION_COUNT"
]
else:
original_initial_no_auth_action_count = (
settings.INITIAL_NO_AUTH_ACTION_COUNT
2019-10-31 08:44:26 -07:00
)
original_request_count = ActionAuthenticatorMixin.request_count
settings.INITIAL_NO_AUTH_ACTION_COUNT = initial_no_auth_action_count
ActionAuthenticatorMixin.request_count = 0
try:
result = function(*args, **kwargs)
finally:
if settings.TEST_SERVER_MODE:
requests.post(
f"{_test_server_mode_endpoint}/moto-api/reset-auth",
data=str(original_initial_no_auth_action_count).encode(
"utf-8"
),
)
else:
ActionAuthenticatorMixin.request_count = original_request_count
settings.INITIAL_NO_AUTH_ACTION_COUNT = (
original_initial_no_auth_action_count
2019-10-31 08:44:26 -07:00
)
return result
functools.update_wrapper(wrapper, function)
2022-11-10 18:54:38 -01:00
wrapper.__wrapped__ = function # type: ignore[attr-defined]
return wrapper
return decorator
class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin):
2014-11-16 17:57:46 -05:00
default_region = "us-east-1"
# to extract region, use [^.]
# Note that the URL region can be anything, thanks to our MOTO_ALLOW_NONEXISTENT_REGION-config - so we can't have a very specific regex
region_regex = re.compile(r"\.(?P<region>[^.]+)\.amazonaws\.com")
2020-06-27 19:05:34 +01:00
region_from_useragent_regex = re.compile(
r"region/(?P<region>[a-z]{2}-[a-z]+-\d{1})"
)
# Note: technically, we could remove "member" from the regex below... (leaving it for clarity)
param_list_regex = re.compile(r"^(\.?[^.]*(\.member|\.[^.]+)?)\.(\d+)\.?")
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
param_regex = re.compile(r"([^\.]*)\.(\w+)(\..+)?")
access_key_regex = re.compile(
r"AWS.*(?P<access_key>(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9]))[:/]"
)
2023-03-03 18:42:11 -01:00
aws_service_spec: Optional["AWSServiceSpec"] = None
2022-11-10 18:54:38 -01:00
def __init__(self, service_name: Optional[str] = None):
2022-08-13 09:49:43 +00:00
super().__init__()
self.service_name = service_name
2015-03-16 13:13:40 +01:00
@classmethod
2022-11-10 18:54:38 -01:00
def dispatch(cls, *args: Any, **kwargs: Any) -> Any: # type: ignore[misc]
2015-03-16 13:13:40 +01:00
return cls()._dispatch(*args, **kwargs)
2022-10-10 13:05:56 +00:00
def setup_class(
self, request: Any, full_url: str, headers: Any, use_raw_body: bool = False
) -> None:
"""
use_raw_body: Use incoming bytes if True, encode to string otherwise
"""
self.is_werkzeug_request = "werkzeug" in str(type(request))
2022-11-10 18:54:38 -01:00
querystring: Dict[str, Any] = OrderedDict()
if hasattr(request, "body"):
# Boto
self.body = request.body
2013-02-25 23:48:17 -05:00
else:
# Flask server
# FIXME: At least in Flask==0.10.1, request.data is an empty string
# and the information we want is in request.form. Keeping self.body
# definition for back-compatibility
self.body = request.data
querystring = OrderedDict()
2014-08-26 13:25:50 -04:00
for key, value in request.form.items():
2013-12-28 20:15:37 -05:00
querystring[key] = [value]
raw_body = self.body
if isinstance(self.body, bytes) and not use_raw_body:
2017-02-16 22:51:04 -05:00
self.body = self.body.decode("utf-8")
2013-12-28 20:15:37 -05:00
if not querystring:
2017-02-23 21:37:43 -05:00
querystring.update(
parse_qs(urlparse(full_url).query, keep_blank_values=True)
2019-10-31 08:44:26 -07:00
)
2013-12-28 20:15:37 -05:00
if not querystring:
if (
"json" in request.headers.get("content-type", [])
and self.aws_service_spec
):
2017-02-16 22:51:04 -05:00
decoded = json.loads(self.body)
2017-02-23 21:37:43 -05:00
target = request.headers.get("x-amz-target") or request.headers.get(
"X-Amz-Target"
)
_, method = target.split(".")
input_spec = self.aws_service_spec.input_spec(method)
flat = flatten_json_request_body("", decoded, input_spec)
for key, value in flat.items():
querystring[key] = [value]
elif self.body and not use_raw_body:
try:
querystring.update(
OrderedDict(
(key, [value])
for key, value in parse_qsl(
raw_body, keep_blank_values=True
)
)
)
except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
pass # ignore encoding errors, as the body may not contain a legitimate querystring
2013-12-28 20:15:37 -05:00
if not querystring:
querystring.update(headers)
2013-02-25 23:48:17 -05:00
try:
querystring = _decode_dict(querystring)
except UnicodeDecodeError:
pass # ignore decoding errors, as the body may not contain a legitimate querystring
self.uri = full_url
self.path = urlparse(full_url).path
2013-02-25 23:48:17 -05:00
self.querystring = querystring
self.data = querystring
self.method = request.method
self.region = self.get_region_from_url(request, full_url)
2022-11-10 18:54:38 -01:00
self.uri_match: Optional[re.Match[str]] = None
2013-02-25 23:48:17 -05:00
self.headers = request.headers
2017-02-15 22:35:45 -05:00
if "host" not in self.headers:
self.headers["host"] = urlparse(full_url).netloc
self.response_headers = {
"server": "amazon.com",
"date": datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"),
}
2016-03-01 12:03:59 -05:00
2022-08-13 09:49:43 +00:00
# Register visit with IAM
from moto.iam.models import mark_account_as_visited
self.access_key = self.get_access_key()
self.current_account = self.get_current_account()
mark_account_as_visited(
account_id=self.current_account,
access_key=self.access_key,
2022-11-10 18:54:38 -01:00
service=self.service_name, # type: ignore[arg-type]
2022-08-13 09:49:43 +00:00
region=self.region,
)
2022-11-10 18:54:38 -01:00
def get_region_from_url(self, request: Any, full_url: str) -> str:
2020-06-27 15:11:41 +01:00
url_match = self.region_regex.search(full_url)
2020-06-27 19:05:34 +01:00
user_agent_match = self.region_from_useragent_regex.search(
request.headers.get("User-Agent", "")
)
2020-06-27 15:11:41 +01:00
if url_match:
region = url_match.group(1)
elif user_agent_match:
region = user_agent_match.group(1)
elif (
"Authorization" in request.headers
and "AWS4" in request.headers["Authorization"]
):
2017-02-23 21:37:43 -05:00
region = request.headers["Authorization"].split(",")[0].split("/")[2]
else:
region = self.default_region
return region
2022-11-10 18:54:38 -01:00
def get_access_key(self) -> str:
"""
Returns the access key id used in this request as the current user id
"""
if "Authorization" in self.headers:
match = self.access_key_regex.search(self.headers["Authorization"])
if match:
return match.group(1)
if self.querystring.get("AWSAccessKeyId"):
2022-11-10 18:54:38 -01:00
return self.querystring["AWSAccessKeyId"][0]
else:
2022-08-13 09:49:43 +00:00
return "AKIAEXAMPLE"
2022-11-10 18:54:38 -01:00
def get_current_account(self) -> str:
2022-08-13 09:49:43 +00:00
# PRIO 1: Check if we have a Environment Variable set
if "MOTO_ACCOUNT_ID" in os.environ:
return os.environ["MOTO_ACCOUNT_ID"]
# PRIO 2: Check if we have a specific request header that specifies the Account ID
if "x-moto-account-id" in self.headers:
return self.headers["x-moto-account-id"]
# PRIO 3: Use the access key to get the Account ID
# PRIO 4: This method will return the default Account ID as a last resort
from moto.iam.models import get_account_id_from
return get_account_id_from(self.get_access_key())
2022-11-10 18:54:38 -01:00
def _dispatch(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE:
2016-03-01 12:03:59 -05:00
self.setup_class(request, full_url, headers)
return self.call_action()
2013-02-25 23:48:17 -05:00
2022-11-10 18:54:38 -01:00
def uri_to_regexp(self, uri: str) -> str:
"""converts uri w/ placeholder to regexp
'/cars/{carName}/drivers/{DriverName}'
-> '^/cars/.*/drivers/[^/]*$'
'/cars/{carName}/drivers/{DriverName}/drive'
-> '^/cars/.*/drivers/.*/drive$'
"""
2019-10-31 08:44:26 -07:00
2022-11-10 18:54:38 -01:00
def _convert(elem: str, is_last: bool) -> str:
if not re.match("^{.*}$", elem):
return elem
name = (
elem.replace("{", "")
.replace("}", "")
.replace("+", "")
.replace("-", "_")
)
if is_last:
return f"(?P<{name}>[^/]+)"
return f"(?P<{name}>.*)"
elems = uri.split("/")
num_elems = len(elems)
regexp = "/".join(
[_convert(elem, (i == num_elems - 1)) for i, elem in enumerate(elems)]
2019-10-31 08:44:26 -07:00
)
return f"^{regexp}$"
2022-11-10 18:54:38 -01:00
def _get_action_from_method_and_request_uri(
self, method: str, request_uri: str
) -> str:
"""basically used for `rest-json` APIs
You can refer to example from link below
https://github.com/boto/botocore/blob/develop/botocore/data/iot/2015-05-28/service-2.json
"""
# service response class should have 'SERVICE_NAME' class member,
# if you want to get action from method and url
2022-08-13 09:49:43 +00:00
conn = boto3.client(self.service_name, region_name=self.region)
# make cache if it does not exist yet
if not hasattr(self, "method_urls"):
2022-11-10 18:54:38 -01:00
self.method_urls: Dict[str, Dict[str, str]] = defaultdict(
lambda: defaultdict(str)
)
op_names = conn._service_model.operation_names
for op_name in op_names:
op_model = conn._service_model.operation_model(op_name)
_method = op_model.http["method"]
uri_regexp = self.uri_to_regexp(op_model.http["requestUri"])
self.method_urls[_method][uri_regexp] = op_model.name
regexp_and_names = self.method_urls[method]
for regexp, name in regexp_and_names.items():
match = re.match(regexp, request_uri)
self.uri_match = match
if match:
return name
2022-11-10 18:54:38 -01:00
return None # type: ignore[return-value]
2022-11-10 18:54:38 -01:00
def _get_action(self) -> str:
action = self.querystring.get("Action", [""])[0]
2022-08-13 09:49:43 +00:00
if action:
return action
# Some services use a header for the action
# Headers are case-insensitive. Probably a better way to do this.
match = self.headers.get("x-amz-target") or self.headers.get("X-Amz-Target")
if match:
return match.split(".")[-1]
# get action from method and uri
2022-08-13 09:49:43 +00:00
return self._get_action_from_method_and_request_uri(self.method, self.path)
2017-09-23 11:02:25 +01:00
2022-11-10 18:54:38 -01:00
def call_action(self) -> TYPE_RESPONSE:
2017-09-23 11:02:25 +01:00
headers = self.response_headers
try:
self._authenticate_and_authorize_normal_action()
except HTTPException as http_error:
response = http_error.description, dict(status=http_error.code)
return self._send_response(headers, response)
2017-09-23 11:02:25 +01:00
action = camelcase_to_underscores(self._get_action())
2013-02-25 23:48:17 -05:00
method_names = method_names_from_class(self.__class__)
if action in method_names:
method = getattr(self, action)
try:
response = method()
except HTTPException as http_error:
2022-11-10 18:54:38 -01:00
response_headers: Dict[str, Union[str, int]] = dict(
http_error.get_headers() or []
)
response_headers["status"] = http_error.code # type: ignore[assignment]
response = http_error.description, response_headers # type: ignore[assignment]
2021-07-26 07:40:39 +01:00
if isinstance(response, str):
return 200, headers, response
else:
return self._send_response(headers, response)
2017-12-27 22:58:24 -05:00
if not action:
return 404, headers, ""
raise NotImplementedError(f"The {action} action has not been implemented")
@staticmethod
2022-11-10 18:54:38 -01:00
def _send_response(headers: Dict[str, str], response: Any) -> Tuple[int, Dict[str, str], str]: # type: ignore[misc]
if response is None:
response = "", {}
if len(response) == 2:
body, new_headers = response
else:
status, new_headers, body = response
status = new_headers.get("status", 200)
headers.update(new_headers)
# Cast status to string
if "status" in headers:
headers["status"] = str(headers["status"])
return status, headers, body
2022-11-10 18:54:38 -01:00
def _get_param(self, param_name: str, if_none: Any = None) -> Any:
val = self.querystring.get(param_name)
if val is not None:
return val[0]
# try to get json body parameter
if self.body is not None:
try:
return json.loads(self.body)[param_name]
except ValueError:
pass
except KeyError:
pass
# try to get path parameter
if self.uri_match:
try:
return self.uri_match.group(param_name)
except IndexError:
# do nothing if param is not found
pass
return if_none
2022-10-19 20:56:24 +00:00
def _get_int_param(
2022-11-10 18:54:38 -01:00
self, param_name: str, if_none: TYPE_IF_NONE = None # type: ignore[assignment]
2022-10-19 20:56:24 +00:00
) -> Union[int, TYPE_IF_NONE]:
2014-11-22 14:03:09 -05:00
val = self._get_param(param_name)
if val is not None:
return int(val)
return if_none
2014-11-22 14:03:09 -05:00
2022-10-19 20:56:24 +00:00
def _get_bool_param(
2022-11-10 18:54:38 -01:00
self, param_name: str, if_none: TYPE_IF_NONE = None # type: ignore[assignment]
2022-10-19 20:56:24 +00:00
) -> Union[bool, TYPE_IF_NONE]:
2014-11-22 14:03:09 -05:00
val = self._get_param(param_name)
if val is not None:
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
val = str(val)
2014-11-22 14:03:09 -05:00
if val.lower() == "true":
return True
elif val.lower() == "false":
return False
return if_none
2014-11-22 14:03:09 -05:00
2022-11-10 18:54:38 -01:00
def _get_multi_param_dict(self, param_prefix: str) -> Dict[str, Any]:
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
return self._get_multi_param_helper(param_prefix, skip_result_conversion=True)
def _get_multi_param_helper(
2022-11-10 18:54:38 -01:00
self,
param_prefix: str,
skip_result_conversion: bool = False,
tracked_prefixes: Optional[Set[str]] = None,
) -> Any:
value_dict = dict()
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
tracked_prefixes = (
tracked_prefixes or set()
) # prefixes which have already been processed
for name, value in self.querystring.items():
2022-01-06 22:09:16 -01:00
if not name.startswith(param_prefix):
continue
if len(name) > len(param_prefix) and not name[
len(param_prefix) :
].startswith("."):
continue
match = (
self.param_list_regex.search(name[len(param_prefix) :])
if len(name) > len(param_prefix)
else None
2019-10-31 08:44:26 -07:00
)
if match:
prefix = param_prefix + match.group(1)
value = self._get_multi_param(prefix)
tracked_prefixes.add(prefix)
name = prefix
value_dict[name] = value
else:
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
match = self.param_regex.search(name[len(param_prefix) :])
if match:
# enable access to params that are lists of dicts, e.g., "TagSpecification.1.ResourceType=.."
sub_attr = (
f"{name[: len(param_prefix)]}{match.group(1)}.{match.group(2)}"
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
)
if match.group(3):
value = self._get_multi_param_helper(
sub_attr,
tracked_prefixes=tracked_prefixes,
skip_result_conversion=skip_result_conversion,
)
else:
value = self._get_param(sub_attr)
tracked_prefixes.add(sub_attr)
value_dict[name] = value
else:
value_dict[name] = value[0]
if not value_dict:
return None
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
if skip_result_conversion or len(value_dict) > 1:
# strip off period prefix
value_dict = {
name[len(param_prefix) + 1 :]: value
for name, value in value_dict.items()
}
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
for k in list(value_dict.keys()):
parts = k.split(".")
if len(parts) != 2 or parts[1] != "member":
value_dict[parts[0]] = value_dict.pop(k)
else:
value_dict = list(value_dict.values())[0]
return value_dict
2022-11-10 18:54:38 -01:00
def _get_multi_param(
self, param_prefix: str, skip_result_conversion: bool = False
) -> List[Any]:
2014-12-31 13:23:08 -05:00
"""
Given a querystring of ?LaunchConfigurationNames.member.1=my-test-1&LaunchConfigurationNames.member.2=my-test-2
this will return ['my-test-1', 'my-test-2']
"""
if param_prefix.endswith("."):
prefix = param_prefix
else:
prefix = param_prefix + "."
2014-08-29 20:31:02 -04:00
values = []
index = 1
while True:
Merge LocalStack changes into upstream moto (#4082) * fix OPTIONS requests on non-existing API GW integrations * add cloudformation models for API Gateway deployments * bump version * add backdoor to return CloudWatch metrics * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * bump version * minor fixes * fix Number data_type for SQS message attribute * fix handling of encoding errors * bump version * make CF stack queryable before starting to initialize its resources * bump version * fix integration_method for API GW method integrations * fix undefined status in CF FakeStack * Fix apigateway issues with terraform v0.12.21 * resource_methods -> add handle for "DELETE" method * integrations -> fix issue that "httpMethod" wasn't included in body request (this value was set as the value from refer method resource) * bump version * Fix setting http method for API gateway integrations (#6) * bump version * remove duplicate methods * add storage class to S3 Key when completing multipart upload (#7) * fix SQS performance issues; bump version * add pagination to SecretsManager list-secrets (#9) * fix default parameter groups in RDS * fix adding S3 metadata headers with names containing dots (#13) * Updating implementation coverage * Updating implementation coverage * add cloudformation models for API Gateway deployments * Updating implementation coverage * Updating implementation coverage * Implemented get-caller-identity returning real data depending on the access key used. * make CF stack queryable before starting to initialize its resources * bump version * remove duplicate methods * fix adding S3 metadata headers with names containing dots (#13) * Update amis.json to support EKS AMI mocks (#15) * fix PascalCase for boolean value in ListMultipartUploads response (#17); fix _get_multi_param to parse nested list/dict query params * determine non-zero container exit code in Batch API * support filtering by dimensions in CW get_metric_statistics * fix storing attributes for ELBv2 Route entities; API GW refactorings for TF tests * add missing fields for API GW resources * fix error messages for Route53 (TF-compat) * various fixes for IAM resources (tf-compat) * minor fixes for API GW models (tf-compat) * minor fixes for API GW responses (tf-compat) * add s3 exception for bucket notification filter rule validation * change the way RESTErrors generate the response body and content-type header * fix lint errors and disable "black" syntax enforcement * remove return type hint in RESTError.get_body * add RESTError XML template for IAM exceptions * add support for API GW minimumCompressionSize * fix casing getting PrivateDnsEnabled API GW attribute * minor fixes for error responses * fix escaping special chars for IAM role descriptions (tf-compat) * minor fixes and tagging support for API GW and ELB v2 (tf-compat) * Merge branch 'master' into localstack * add "AlarmRule" attribute to enable support for composite CloudWatch metrics * fix recursive parsing of complex/nested query params * bump version * add API to delete S3 website configurations (#18) * use dict copy to allow parallelism and avoid concurrent modification exceptions in S3 * fix precondition check for etags in S3 (#19) * minor fix for user filtering in Cognito * fix API Gateway error response; avoid returning empty response templates (tf-compat) * support tags and tracingEnabled attribute for API GW stages * fix boolean value in S3 encryption response (#20) * fix connection arn structure * fix api destination arn structure * black format * release 2.0.3.37 * fix s3 exception tests see botocore/parsers.py:1002 where RequestId is removed from parsed * remove python 2 from build action * add test failure annotations in build action * fix events test arn comparisons * fix s3 encryption response test * return default value "0" if EC2 availableIpAddressCount is empty * fix extracting SecurityGroupIds for EC2 VPC endpoints * support deleting/updating API Gateway DomainNames * fix(events): Return empty string instead of null when no pattern is specified in EventPattern (tf-compat) (#22) * fix logic and revert CF changes to get tests running again (#21) * add support for EC2 customer gateway API (#25) * add support for EC2 Transit Gateway APIs (#24) * feat(logs): add `kmsKeyId` into `LogGroup` entity (#23) * minor change in ELBv2 logic to fix tests * feat(events): add APIs to describe and delete CloudWatch Events connections (#26) * add support for EC2 transit gateway route tables (#27) * pass transit gateway route table ID in Describe API, minor refactoring (#29) * add support for EC2 Transit Gateway Routes (#28) * fix region on ACM certificate import (#31) * add support for EC2 transit gateway attachments (#30) * add support for EC2 Transit Gateway VPN attachments (#32) * fix account ID for logs API * add support for DeleteOrganization API * feat(events): store raw filter representation for CloudWatch events patterns (tf-compat) (#36) * feat(events): add support to describe/update/delete CloudWatch API destinations (#35) * add Cognito UpdateIdentityPool, CW Logs PutResourcePolicy * feat(events): add support for tags in EventBus API (#38) * fix parameter validation for Batch compute environments (tf-compat) * revert merge conflicts in IMPLEMENTATION_COVERAGE.md * format code using black * restore original README; re-enable and fix CloudFormation tests * restore tests and old logic for CF stack parameters from SSM * parameterize RequestId/RequestID in response messages and revert related test changes * undo LocalStack-specific adaptations * minor fix * Update CodeCov config to reflect removal of Py2 * undo change related to CW metric filtering; add additional test for CW metric statistics with dimensions * Terraform - Extend whitelist of running tests Co-authored-by: acsbendi <acsbendi28@gmail.com> Co-authored-by: Phan Duong <duongpv@outlook.com> Co-authored-by: Thomas Rausch <thomas@thrau.at> Co-authored-by: Macwan Nevil <macnev2013@gmail.com> Co-authored-by: Dominik Schubert <dominik.schubert91@gmail.com> Co-authored-by: Gonzalo Saad <saad.gonzalo.ale@gmail.com> Co-authored-by: Mohit Alonja <monty16597@users.noreply.github.com> Co-authored-by: Miguel Gagliardo <migag9@gmail.com> Co-authored-by: Bert Blommers <info@bertblommers.nl>
2021-07-26 16:21:17 +02:00
value_dict = self._get_multi_param_helper(
prefix + str(index), skip_result_conversion=skip_result_conversion
)
if not value_dict and value_dict != "":
2014-08-29 20:31:02 -04:00
break
values.append(value_dict)
index += 1
2014-08-29 20:31:02 -04:00
return values
2022-11-10 18:54:38 -01:00
def _get_dict_param(self, param_prefix: str) -> Dict[str, Any]:
2014-12-31 13:23:08 -05:00
"""
Given a parameter dict of
{
'Instances.SlaveInstanceType': ['m1.small'],
'Instances.InstanceCount': ['1']
}
returns
{
"slave_instance_type": "m1.small",
"instance_count": "1",
2014-12-31 13:23:08 -05:00
}
"""
2022-11-10 18:54:38 -01:00
params: Dict[str, Any] = {}
2014-12-31 13:23:08 -05:00
for key, value in self.querystring.items():
if key.startswith(param_prefix):
2017-02-23 21:37:43 -05:00
params[camelcase_to_underscores(key.replace(param_prefix, ""))] = value[
2019-10-31 08:44:26 -07:00
0
2017-02-23 21:37:43 -05:00
]
2014-12-31 13:23:08 -05:00
return params
2022-11-10 18:54:38 -01:00
def _get_params(self) -> Dict[str, Any]:
"""
Given a querystring of
{
'Action': ['CreatRule'],
'Conditions.member.1.Field': ['http-header'],
'Conditions.member.1.HttpHeaderConfig.HttpHeaderName': ['User-Agent'],
'Conditions.member.1.HttpHeaderConfig.Values.member.1': ['curl'],
'Actions.member.1.FixedResponseConfig.StatusCode': ['200'],
'Actions.member.1.FixedResponseConfig.ContentType': ['text/plain'],
'Actions.member.1.Type': ['fixed-response']
}
returns
{
'Action': 'CreatRule',
'Conditions': [
{
'Field': 'http-header',
'HttpHeaderConfig': {
'HttpHeaderName': 'User-Agent',
'Values': ['curl']
}
}
],
'Actions': [
{
'Type': 'fixed-response',
'FixedResponseConfig': {
'StatusCode': '200',
'ContentType': 'text/plain'
}
}
]
}
"""
2022-11-10 18:54:38 -01:00
params: Dict[str, Any] = {}
for k, v in sorted(self.querystring.items(), key=params_sort_function):
self._parse_param(k, v[0], params)
return params
2022-11-10 18:54:38 -01:00
def _parse_param(self, key: str, value: str, params: Any) -> None:
keylist = key.split(".")
obj = params
for i, key in enumerate(keylist[:-1]):
if key in obj:
# step into
parent = obj
obj = obj[key]
else:
if key == "member":
if not isinstance(obj, list):
# initialize list
# reset parent
obj = []
parent[keylist[i - 1]] = obj
2022-01-25 09:27:02 -01:00
elif isinstance(obj, dict):
# initialize dict
obj[key] = {}
# step into
parent = obj
obj = obj[key]
elif key.isdigit():
index = int(key) - 1
if len(obj) <= index:
# initialize list element
obj.insert(index, {})
# step into
parent = obj
obj = obj[index]
if isinstance(obj, list):
obj.append(value)
else:
obj[keylist[-1]] = value
2022-11-10 18:54:38 -01:00
def _get_list_prefix(self, param_prefix: str) -> List[Dict[str, Any]]:
2014-12-31 13:23:08 -05:00
"""
Given a query dict like
{
'Steps.member.1.Name': ['example1'],
'Steps.member.1.ActionOnFailure': ['TERMINATE_JOB_FLOW'],
'Steps.member.1.HadoopJarStep.Jar': ['streaming1.jar'],
'Steps.member.2.Name': ['example2'],
'Steps.member.2.ActionOnFailure': ['TERMINATE_JOB_FLOW'],
'Steps.member.2.HadoopJarStep.Jar': ['streaming2.jar'],
}
returns
[{
'name': u'example1',
'action_on_failure': u'TERMINATE_JOB_FLOW',
'hadoop_jar_step._jar': u'streaming1.jar',
}, {
'name': u'example2',
'action_on_failure': u'TERMINATE_JOB_FLOW',
'hadoop_jar_step._jar': u'streaming2.jar',
}]
"""
results = []
param_index = 1
while True:
index_prefix = f"{param_prefix}.{param_index}."
2014-12-31 13:23:08 -05:00
new_items = {}
for key, value in self.querystring.items():
if key.startswith(index_prefix):
2017-02-23 21:37:43 -05:00
new_items[
camelcase_to_underscores(key.replace(index_prefix, ""))
] = value[0]
2014-12-31 13:23:08 -05:00
if not new_items:
break
results.append(new_items)
param_index += 1
return results
2022-11-10 18:54:38 -01:00
def _get_map_prefix(
self, param_prefix: str, key_end: str = ".key", value_end: str = ".value"
) -> Dict[str, Any]:
results = {}
param_index = 1
while 1:
index_prefix = f"{param_prefix}.{param_index}."
k, v = None, None
for key, value in self.querystring.items():
if key.startswith(index_prefix):
2017-09-22 20:08:20 +01:00
if key.endswith(key_end):
k = value[0]
2017-09-22 20:08:20 +01:00
elif key.endswith(value_end):
v = value[0]
if not (k and v is not None):
break
results[k] = v
param_index += 1
return results
2022-11-10 18:54:38 -01:00
def _get_object_map(
self, prefix: str, name: str = "Name", value: str = "Value"
) -> Dict[str, Any]:
"""
Given a query dict like
{
Prefix.1.Name: [u'event'],
Prefix.1.Value.StringValue: [u'order_cancelled'],
Prefix.1.Value.DataType: [u'String'],
Prefix.2.Name: [u'store'],
Prefix.2.Value.StringValue: [u'example_corp'],
Prefix.2.Value.DataType [u'String'],
}
returns
{
'event': {
'DataType': 'String',
'StringValue': 'example_corp'
},
'store': {
'DataType': 'String',
'StringValue': 'order_cancelled'
}
}
"""
object_map = {}
index = 1
while True:
# Loop through looking for keys representing object name
name_key = f"{prefix}.{index}.{name}"
obj_name = self.querystring.get(name_key)
if not obj_name:
# Found all keys
break
obj = {}
value_key_prefix = f"{prefix}.{index}.{value}."
for k, v in self.querystring.items():
if k.startswith(value_key_prefix):
_, value_key = k.split(value_key_prefix, 1)
obj[value_key] = v[0]
object_map[obj_name[0]] = obj
index += 1
return object_map
@property
2022-11-10 18:54:38 -01:00
def request_json(self) -> bool:
return "JSON" in self.querystring.get("ContentType", [])
2022-11-10 18:54:38 -01:00
def error_on_dryrun(self) -> None:
if "true" in self.querystring.get("DryRun", ["false"]):
2023-02-14 12:43:28 -01:00
a = self._get_param("Action")
2022-11-10 18:54:38 -01:00
message = f"An error occurred (DryRunOperation) when calling the {a} operation: Request would have succeeded, but DryRun flag is set"
2017-02-23 21:37:43 -05:00
raise DryRunClientError(error_type="DryRunOperation", message=message)
class _RecursiveDictRef(object):
"""Store a recursive reference to dict."""
2017-02-23 21:37:43 -05:00
2022-11-10 18:54:38 -01:00
def __init__(self) -> None:
self.key: Optional[str] = None
self.dic: Dict[str, Any] = {}
2022-11-10 18:54:38 -01:00
def __repr__(self) -> str:
return f"{self.dic}"
2022-11-10 18:54:38 -01:00
def __getattr__(self, key: str) -> Any:
return self.dic.__getattr__(key) # type: ignore[attr-defined]
2022-11-10 18:54:38 -01:00
def __getitem__(self, key: str) -> Any:
return self.dic.__getitem__(key)
2022-11-10 18:54:38 -01:00
def set_reference(self, key: str, dic: Dict[str, Any]) -> None:
"""Set the RecursiveDictRef object to keep reference to dict object
(dic) at the key.
"""
self.key = key
self.dic = dic
class AWSServiceSpec(object):
"""Parse data model from botocore. This is used to recover type info
for fields in AWS API XML response.
"""
2022-11-03 18:32:00 -01:00
def __init__(self, path: str):
2021-08-05 17:59:25 +01:00
spec = load_resource("botocore", path)
self.metadata = spec["metadata"]
self.operations = spec["operations"]
self.shapes = spec["shapes"]
2022-11-10 18:54:38 -01:00
def input_spec(self, operation: str) -> Dict[str, Any]:
try:
op = self.operations[operation]
except KeyError:
raise ValueError(f"Invalid operation: {operation}")
if "input" not in op:
return {}
shape = self.shapes[op["input"]["shape"]]
return self._expand(shape)
2022-11-10 18:54:38 -01:00
def output_spec(self, operation: str) -> Dict[str, Any]:
"""Produce a JSON with a valid API response syntax for operation, but
with type information. Each node represented by a key has the
value containing field type, e.g.,
output_spec["SomeBooleanNode"] => {"type": "boolean"}
"""
try:
op = self.operations[operation]
except KeyError:
raise ValueError(f"Invalid operation: {operation}")
if "output" not in op:
return {}
shape = self.shapes[op["output"]["shape"]]
return self._expand(shape)
2022-11-10 18:54:38 -01:00
def _expand(self, shape: Dict[str, Any]) -> Dict[str, Any]:
def expand(
dic: Dict[str, Any], seen: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
seen = seen or {}
if dic["type"] == "structure":
2022-11-10 18:54:38 -01:00
nodes: Dict[str, Any] = {}
for k, v in dic["members"].items():
seen_till_here = dict(seen)
if k in seen_till_here:
nodes[k] = seen_till_here[k]
continue
seen_till_here[k] = _RecursiveDictRef()
nodes[k] = expand(self.shapes[v["shape"]], seen_till_here)
seen_till_here[k].set_reference(k, nodes[k])
nodes["type"] = "structure"
return nodes
elif dic["type"] == "list":
seen_till_here = dict(seen)
shape = dic["member"]["shape"]
if shape in seen_till_here:
return seen_till_here[shape]
seen_till_here[shape] = _RecursiveDictRef()
expanded = expand(self.shapes[shape], seen_till_here)
seen_till_here[shape].set_reference(shape, expanded)
return {"type": "list", "member": expanded}
elif dic["type"] == "map":
seen_till_here = dict(seen)
2022-11-10 18:54:38 -01:00
node: Dict[str, Any] = {"type": "map"}
if "shape" in dic["key"]:
shape = dic["key"]["shape"]
seen_till_here[shape] = _RecursiveDictRef()
node["key"] = expand(self.shapes[shape], seen_till_here)
seen_till_here[shape].set_reference(shape, node["key"])
else:
node["key"] = dic["key"]["type"]
if "shape" in dic["value"]:
shape = dic["value"]["shape"]
seen_till_here[shape] = _RecursiveDictRef()
node["value"] = expand(self.shapes[shape], seen_till_here)
seen_till_here[shape].set_reference(shape, node["value"])
else:
node["value"] = dic["value"]["type"]
return node
else:
return {"type": dic["type"]}
return expand(shape)
2022-11-10 18:54:38 -01:00
def to_str(value: Any, spec: Dict[str, Any]) -> str:
vtype = spec["type"]
if vtype == "boolean":
return "true" if value else "false"
elif vtype == "long":
2022-11-10 18:54:38 -01:00
return int(value) # type: ignore[return-value]
elif vtype == "integer":
return str(value)
elif vtype == "float":
return str(value)
elif vtype == "double":
return str(value)
elif vtype == "timestamp":
return (
datetime.datetime.utcfromtimestamp(value)
2022-12-10 00:56:08 +01:00
.replace(tzinfo=datetime.timezone.utc)
.isoformat()
2019-10-31 08:44:26 -07:00
)
elif vtype == "string":
return str(value)
elif value is None:
return "null"
else:
raise TypeError(f"Unknown type {vtype}")
2022-11-10 18:54:38 -01:00
def from_str(value: str, spec: Dict[str, Any]) -> Any:
vtype = spec["type"]
if vtype == "boolean":
return True if value == "true" else False
elif vtype == "integer":
return int(value)
elif vtype == "float":
return float(value)
elif vtype == "double":
return float(value)
elif vtype == "timestamp":
return value
elif vtype == "string":
return value
raise TypeError(f"Unknown type {vtype}")
2022-11-10 18:54:38 -01:00
def flatten_json_request_body(
prefix: str, dict_body: Dict[str, Any], spec: Dict[str, Any]
) -> Dict[str, Any]:
"""Convert a JSON request body into query params."""
if len(spec) == 1 and "type" in spec:
return {prefix: to_str(dict_body, spec)}
flat = {}
for key, value in dict_body.items():
node_type = spec[key]["type"]
if node_type == "list":
for idx, v in enumerate(value, 1):
pref = key + ".member." + str(idx)
2017-02-23 21:37:43 -05:00
flat.update(flatten_json_request_body(pref, v, spec[key]["member"]))
elif node_type == "map":
for idx, (k, v) in enumerate(value.items(), 1):
pref = key + ".entry." + str(idx)
2017-02-23 21:37:43 -05:00
flat.update(
flatten_json_request_body(pref + ".key", k, spec[key]["key"])
2019-10-31 08:44:26 -07:00
)
2017-02-23 21:37:43 -05:00
flat.update(
flatten_json_request_body(pref + ".value", v, spec[key]["value"])
2019-10-31 08:44:26 -07:00
)
else:
flat.update(flatten_json_request_body(key, value, spec[key]))
if prefix:
prefix = prefix + "."
return dict((prefix + k, v) for k, v in flat.items())
2022-11-10 18:54:38 -01:00
def xml_to_json_response(
service_spec: Any, operation: str, xml: str, result_node: Any = None
) -> Dict[str, Any]:
"""Convert rendered XML response to JSON for use with boto3."""
2022-11-10 18:54:38 -01:00
def transform(value: Any, spec: Dict[str, Any]) -> Any:
"""Apply transformations to make the output JSON comply with the
expected form. This function applies:
(1) Type cast to nodes with "type" property (e.g., 'true' to
True). XML field values are all in text so this step is
necessary to convert it to valid JSON objects.
(2) Squashes "member" nodes to lists.
"""
if len(spec) == 1:
return from_str(value, spec)
2022-11-10 18:54:38 -01:00
od: Dict[str, Any] = OrderedDict()
for k, v in value.items():
if k.startswith("@"):
continue
if k not in spec:
# this can happen when with an older version of
# botocore for which the node in XML template is not
# defined in service spec.
2017-02-23 21:37:43 -05:00
log.warning("Field %s is not defined by the botocore version in use", k)
continue
if spec[k]["type"] == "list":
if v is None:
od[k] = []
elif len(spec[k]["member"]) == 1:
if isinstance(v["member"], list):
od[k] = transform(v["member"], spec[k]["member"])
else:
od[k] = [transform(v["member"], spec[k]["member"])]
elif isinstance(v["member"], list):
2017-02-23 21:37:43 -05:00
od[k] = [transform(o, spec[k]["member"]) for o in v["member"]]
elif isinstance(v["member"], (OrderedDict, dict)):
od[k] = [transform(v["member"], spec[k]["member"])]
else:
raise ValueError("Malformatted input")
elif spec[k]["type"] == "map":
if v is None:
od[k] = {}
else:
items = (
[v["entry"]] if not isinstance(v["entry"], list) else v["entry"]
)
for item in items:
key = from_str(item["key"], spec[k]["key"])
val = from_str(item["value"], spec[k]["value"])
if k not in od:
od[k] = {}
od[k][key] = val
else:
if v is None:
od[k] = None
else:
od[k] = transform(v, spec[k])
return od
dic = xmltodict.parse(xml)
output_spec = service_spec.output_spec(operation)
try:
for k in result_node or (operation + "Response", operation + "Result"):
dic = dic[k]
except KeyError:
2022-11-10 18:54:38 -01:00
return None # type: ignore[return-value]
else:
return transform(dic, output_spec)
return None