From 1f1e0caca3302094f6b3745e39055c0bc9e3e7b5 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Sun, 14 Jan 2024 13:01:30 +0000 Subject: [PATCH] Core: Add RequestId-header to all responses (#7210) --- moto/autoscaling/responses.py | 31 +++---------- moto/awslambda/responses.py | 8 ++-- moto/batch/responses.py | 39 ----------------- moto/cloudformation/responses.py | 3 -- moto/cloudwatch/responses.py | 20 --------- moto/core/responses.py | 45 ++++++++++++++++--- moto/databrew/responses.py | 17 -------- moto/dynamodb/responses.py | 22 +++------- moto/elbv2/responses.py | 35 --------------- moto/forecast/responses.py | 6 --- moto/s3/responses.py | 3 -- moto/s3control/responses.py | 2 - moto/sagemaker/responses.py | 53 ----------------------- moto/sqs/responses.py | 3 +- moto/stepfunctions/responses.py | 16 ------- moto/transcribe/responses.py | 17 -------- moto/utilities/aws_headers.py | 38 ++-------------- moto/wafv2/responses.py | 13 ------ tests/test_apigateway/test_apigateway.py | 23 +++++++++- tests/test_awslambda/test_lambda.py | 3 ++ tests/test_cognitoidp/test_cognitoidp.py | 2 + tests/test_config/test_config.py | 1 + tests/test_moto_api/seeder/test_seeder.py | 2 +- 23 files changed, 85 insertions(+), 317 deletions(-) diff --git a/moto/autoscaling/responses.py b/moto/autoscaling/responses.py index ceaa2eb9f..f977ca4b5 100644 --- a/moto/autoscaling/responses.py +++ b/moto/autoscaling/responses.py @@ -1,6 +1,7 @@ +from moto.core.common_types import TYPE_RESPONSE from moto.core.responses import BaseResponse from moto.core.utils import iso_8601_datetime_with_milliseconds -from moto.utilities.aws_headers import amz_crc32, amzn_request_id +from moto.utilities.aws_headers import amz_crc32 from .models import AutoScalingBackend, autoscaling_backends @@ -13,6 +14,10 @@ class AutoScalingResponse(BaseResponse): def autoscaling_backend(self) -> AutoScalingBackend: return autoscaling_backends[self.current_account][self.region] + @amz_crc32 + def call_action(self) -> TYPE_RESPONSE: + return super().call_action() + def create_launch_configuration(self) -> str: instance_monitoring_string = self._get_param("InstanceMonitoring.Enabled") if instance_monitoring_string == "true": @@ -139,8 +144,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(DESCRIBE_SCALING_ACTIVITIES_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def attach_instances(self) -> str: group_name = self._get_param("AutoScalingGroupName") instance_ids = self._get_multi_param("InstanceIds.member") @@ -148,8 +151,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(ATTACH_INSTANCES_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def set_instance_health(self) -> str: instance_id = self._get_param("InstanceId") health_status = self._get_param("HealthStatus") @@ -159,8 +160,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(SET_INSTANCE_HEALTH_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def detach_instances(self) -> str: group_name = self._get_param("AutoScalingGroupName") instance_ids = self._get_multi_param("InstanceIds.member") @@ -175,8 +174,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(DETACH_INSTANCES_TEMPLATE) return template.render(detached_instances=detached_instances) - @amz_crc32 - @amzn_request_id def attach_load_balancer_target_groups(self) -> str: group_name = self._get_param("AutoScalingGroupName") target_group_arns = self._get_multi_param("TargetGroupARNs.member") @@ -187,8 +184,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(ATTACH_LOAD_BALANCER_TARGET_GROUPS_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def describe_load_balancer_target_groups(self) -> str: group_name = self._get_param("AutoScalingGroupName") target_group_arns = ( @@ -197,8 +192,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(DESCRIBE_LOAD_BALANCER_TARGET_GROUPS) return template.render(target_group_arns=target_group_arns) - @amz_crc32 - @amzn_request_id def detach_load_balancer_target_groups(self) -> str: group_name = self._get_param("AutoScalingGroupName") target_group_arns = self._get_multi_param("TargetGroupARNs.member") @@ -347,8 +340,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(EXECUTE_POLICY_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def attach_load_balancers(self) -> str: group_name = self._get_param("AutoScalingGroupName") load_balancer_names = self._get_multi_param("LoadBalancerNames.member") @@ -356,16 +347,12 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(ATTACH_LOAD_BALANCERS_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def describe_load_balancers(self) -> str: group_name = self._get_param("AutoScalingGroupName") load_balancers = self.autoscaling_backend.describe_load_balancers(group_name) template = self.response_template(DESCRIBE_LOAD_BALANCERS_TEMPLATE) return template.render(load_balancers=load_balancers) - @amz_crc32 - @amzn_request_id def detach_load_balancers(self) -> str: group_name = self._get_param("AutoScalingGroupName") load_balancer_names = self._get_multi_param("LoadBalancerNames.member") @@ -373,8 +360,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(DETACH_LOAD_BALANCERS_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def enter_standby(self) -> str: group_name = self._get_param("AutoScalingGroupName") instance_ids = self._get_multi_param("InstanceIds.member") @@ -399,8 +384,6 @@ class AutoScalingResponse(BaseResponse): timestamp=iso_8601_datetime_with_milliseconds(), ) - @amz_crc32 - @amzn_request_id def exit_standby(self) -> str: group_name = self._get_param("AutoScalingGroupName") instance_ids = self._get_multi_param("InstanceIds.member") @@ -445,8 +428,6 @@ class AutoScalingResponse(BaseResponse): template = self.response_template(SET_INSTANCE_PROTECTION_TEMPLATE) return template.render() - @amz_crc32 - @amzn_request_id def terminate_instance_in_auto_scaling_group(self) -> str: instance_id = self._get_param("InstanceId") should_decrement_string = self._get_param("ShouldDecrementDesiredCapacity") diff --git a/moto/awslambda/responses.py b/moto/awslambda/responses.py index 43d7257da..ac5544bb3 100644 --- a/moto/awslambda/responses.py +++ b/moto/awslambda/responses.py @@ -5,7 +5,7 @@ from urllib.parse import unquote from moto.core.responses import TYPE_RESPONSE, BaseResponse from moto.core.utils import path_url -from moto.utilities.aws_headers import amz_crc32, amzn_request_id +from moto.utilities.aws_headers import amz_crc32 from .exceptions import ( FunctionAlreadyExists, @@ -129,9 +129,8 @@ class LambdaResponse(BaseResponse): raise ValueError("Cannot handle request") @amz_crc32 - @amzn_request_id - def invoke( # type: ignore - self, request=None, full_url="", headers=None + def invoke( + self, request: Any, full_url: str, headers: Any ) -> Tuple[int, Dict[str, str], Union[str, bytes]]: self.setup_class(request, full_url, headers) if request.method == "POST": @@ -140,7 +139,6 @@ class LambdaResponse(BaseResponse): raise ValueError("Cannot handle request") @amz_crc32 - @amzn_request_id def invoke_async( self, request: Any, full_url: str, headers: Any ) -> Tuple[int, Dict[str, str], Union[str, bytes]]: diff --git a/moto/batch/responses.py b/moto/batch/responses.py index b3e4f173b..9373108c3 100644 --- a/moto/batch/responses.py +++ b/moto/batch/responses.py @@ -3,7 +3,6 @@ from urllib.parse import unquote, urlsplit from moto.core.models import default_user_config from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .models import BatchBackend, batch_backends @@ -25,8 +24,6 @@ class BatchResponse(BaseResponse): # Return element after the /v1/* return urlsplit(self.uri).path.lstrip("/").split("/")[1] - # CreateComputeEnvironment - @amzn_request_id def createcomputeenvironment(self) -> str: compute_env_name = self._get_param("computeEnvironmentName") compute_resource = self._get_param("computeResources") @@ -46,8 +43,6 @@ class BatchResponse(BaseResponse): return json.dumps(result) - # DescribeComputeEnvironments - @amzn_request_id def describecomputeenvironments(self) -> str: compute_environments = self._get_param("computeEnvironments") @@ -56,8 +51,6 @@ class BatchResponse(BaseResponse): result = {"computeEnvironments": envs} return json.dumps(result) - # DeleteComputeEnvironment - @amzn_request_id def deletecomputeenvironment(self) -> str: compute_environment = self._get_param("computeEnvironment") @@ -65,8 +58,6 @@ class BatchResponse(BaseResponse): return "" - # UpdateComputeEnvironment - @amzn_request_id def updatecomputeenvironment(self) -> str: compute_env_name = self._get_param("computeEnvironment") compute_resource = self._get_param("computeResources") @@ -84,8 +75,6 @@ class BatchResponse(BaseResponse): return json.dumps(result) - # CreateJobQueue - @amzn_request_id def createjobqueue(self) -> str: compute_env_order = self._get_param("computeEnvironmentOrder") queue_name = self._get_param("jobQueueName") @@ -107,8 +96,6 @@ class BatchResponse(BaseResponse): return json.dumps(result) - # DescribeJobQueues - @amzn_request_id def describejobqueues(self) -> str: job_queues = self._get_param("jobQueues") @@ -117,8 +104,6 @@ class BatchResponse(BaseResponse): result = {"jobQueues": queues} return json.dumps(result) - # UpdateJobQueue - @amzn_request_id def updatejobqueue(self) -> str: compute_env_order = self._get_param("computeEnvironmentOrder") queue_name = self._get_param("jobQueue") @@ -138,8 +123,6 @@ class BatchResponse(BaseResponse): return json.dumps(result) - # DeleteJobQueue - @amzn_request_id def deletejobqueue(self) -> str: queue_name = self._get_param("jobQueue") @@ -147,8 +130,6 @@ class BatchResponse(BaseResponse): return "" - # RegisterJobDefinition - @amzn_request_id def registerjobdefinition(self) -> str: container_properties = self._get_param("containerProperties") node_properties = self._get_param("nodeProperties") @@ -181,8 +162,6 @@ class BatchResponse(BaseResponse): return json.dumps(result) - # DeregisterJobDefinition - @amzn_request_id def deregisterjobdefinition(self) -> str: queue_name = self._get_param("jobDefinition") @@ -190,8 +169,6 @@ class BatchResponse(BaseResponse): return "" - # DescribeJobDefinitions - @amzn_request_id def describejobdefinitions(self) -> str: job_def_name = self._get_param("jobDefinitionName") job_def_list = self._get_param("jobDefinitions") @@ -204,8 +181,6 @@ class BatchResponse(BaseResponse): result = {"jobDefinitions": [job.describe() for job in job_defs]} return json.dumps(result) - # SubmitJob - @amzn_request_id def submitjob(self) -> str: container_overrides = self._get_param("containerOverrides") depends_on = self._get_param("dependsOn") @@ -229,15 +204,11 @@ class BatchResponse(BaseResponse): return json.dumps(result) - # DescribeJobs - @amzn_request_id def describejobs(self) -> str: jobs = self._get_param("jobs") return json.dumps({"jobs": self.batch_backend.describe_jobs(jobs)}) - # ListJobs - @amzn_request_id def listjobs(self) -> str: job_queue = self._get_param("jobQueue") job_status = self._get_param("jobStatus") @@ -248,8 +219,6 @@ class BatchResponse(BaseResponse): result = {"jobSummaryList": [job.describe_short() for job in jobs]} return json.dumps(result) - # TerminateJob - @amzn_request_id def terminatejob(self) -> str: job_id = self._get_param("jobId") reason = self._get_param("reason") @@ -258,8 +227,6 @@ class BatchResponse(BaseResponse): return "" - # CancelJob - @amzn_request_id def canceljob(self) -> str: job_id = self._get_param("jobId") reason = self._get_param("reason") @@ -267,7 +234,6 @@ class BatchResponse(BaseResponse): return "" - @amzn_request_id def tags(self) -> str: resource_arn = unquote(self.path).split("/v1/tags/")[-1] tags = self._get_param("tags") @@ -281,7 +247,6 @@ class BatchResponse(BaseResponse): self.batch_backend.untag_resource(resource_arn, tag_keys) # type: ignore[arg-type] return "" - @amzn_request_id def createschedulingpolicy(self) -> str: body = json.loads(self.body) name = body.get("name") @@ -292,26 +257,22 @@ class BatchResponse(BaseResponse): ) return json.dumps(policy.to_dict(create=True)) - @amzn_request_id def describeschedulingpolicies(self) -> str: body = json.loads(self.body) arns = body.get("arns") or [] policies = self.batch_backend.describe_scheduling_policies(arns) return json.dumps({"schedulingPolicies": [pol.to_dict() for pol in policies]}) - @amzn_request_id def listschedulingpolicies(self) -> str: arns = self.batch_backend.list_scheduling_policies() return json.dumps({"schedulingPolicies": [{"arn": arn} for arn in arns]}) - @amzn_request_id def deleteschedulingpolicy(self) -> str: body = json.loads(self.body) arn = body["arn"] self.batch_backend.delete_scheduling_policy(arn) return "" - @amzn_request_id def updateschedulingpolicy(self) -> str: body = json.loads(self.body) arn = body.get("arn") diff --git a/moto/cloudformation/responses.py b/moto/cloudformation/responses.py index cd60af8b5..07a1fb363 100644 --- a/moto/cloudformation/responses.py +++ b/moto/cloudformation/responses.py @@ -8,7 +8,6 @@ from yaml.scanner import ScannerError # pylint:disable=c-extension-no-member from moto.core.responses import BaseResponse from moto.s3.exceptions import S3ClientError -from moto.utilities.aws_headers import amzn_request_id from .exceptions import MissingParameterError, ValidationError from .models import CloudFormationBackend, FakeStack, cloudformation_backends @@ -153,7 +152,6 @@ class CloudFormationResponse(BaseResponse): return True return False - @amzn_request_id def create_change_set(self) -> str: stack_name = self._get_param("StackName") change_set_name = self._get_param("ChangeSetName") @@ -220,7 +218,6 @@ class CloudFormationResponse(BaseResponse): template = self.response_template(DESCRIBE_CHANGE_SET_RESPONSE_TEMPLATE) return template.render(change_set=change_set) - @amzn_request_id def execute_change_set(self) -> str: stack_name = self._get_param("StackName") change_set_name = self._get_param("ChangeSetName") diff --git a/moto/cloudwatch/responses.py b/moto/cloudwatch/responses.py index 527784476..e9bbb3f65 100644 --- a/moto/cloudwatch/responses.py +++ b/moto/cloudwatch/responses.py @@ -4,7 +4,6 @@ from typing import Dict, Iterable, List, Tuple, Union from dateutil.parser import parse as dtparse from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .exceptions import InvalidParameterCombination, ValidationError from .models import ( @@ -32,7 +31,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(ERROR_RESPONSE_TEMPLATE) return template.render(code=code, message=message), dict(status=status) - @amzn_request_id def put_metric_alarm(self) -> str: name = self._get_param("AlarmName") namespace = self._get_param("Namespace") @@ -132,7 +130,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(PUT_METRIC_ALARM_TEMPLATE) return template.render(alarm=alarm) - @amzn_request_id def describe_alarms(self) -> str: action_prefix = self._get_param("ActionPrefix") alarm_name_prefix = self._get_param("AlarmNamePrefix") @@ -160,14 +157,12 @@ class CloudWatchResponse(BaseResponse): metric_alarms=metric_alarms, composite_alarms=composite_alarms ) - @amzn_request_id def delete_alarms(self) -> str: alarm_names = self._get_multi_param("AlarmNames.member") self.cloudwatch_backend.delete_alarms(alarm_names) template = self.response_template(DELETE_METRIC_ALARMS_TEMPLATE) return template.render() - @amzn_request_id def put_metric_data(self) -> str: namespace = self._get_param("Namespace") metric_data = self._get_multi_param("MetricData.member") @@ -175,7 +170,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(PUT_METRIC_DATA_TEMPLATE) return template.render() - @amzn_request_id def get_metric_data(self) -> str: params = self._get_params() start = dtparse(params["StartTime"]) @@ -196,7 +190,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(GET_METRIC_DATA_TEMPLATE) return template.render(results=results) - @amzn_request_id def get_metric_statistics(self) -> str: namespace = self._get_param("Namespace") metric_name = self._get_param("MetricName") @@ -228,7 +221,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(GET_METRIC_STATISTICS_TEMPLATE) return template.render(label=metric_name, datapoints=datapoints) - @amzn_request_id def list_metrics(self) -> str: namespace = self._get_param("Namespace") metric_name = self._get_param("MetricName") @@ -240,7 +232,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(LIST_METRICS_TEMPLATE) return template.render(metrics=metrics, next_token=next_token) - @amzn_request_id def delete_dashboards(self) -> Union[str, ERROR_RESPONSE]: dashboards = self._get_multi_param("DashboardNames.member") if dashboards is None: @@ -253,7 +244,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(DELETE_DASHBOARD_TEMPLATE) return template.render() - @amzn_request_id def describe_alarm_history(self) -> None: raise NotImplementedError() @@ -268,7 +258,6 @@ class CloudWatchResponse(BaseResponse): metric_filtered_alarms.append(alarm) return metric_filtered_alarms - @amzn_request_id def describe_alarms_for_metric(self) -> str: alarms = self.cloudwatch_backend.get_all_alarms() namespace = self._get_param("Namespace") @@ -277,15 +266,12 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(DESCRIBE_METRIC_ALARMS_TEMPLATE) return template.render(alarms=filtered_alarms) - @amzn_request_id def disable_alarm_actions(self) -> str: raise NotImplementedError() - @amzn_request_id def enable_alarm_actions(self) -> str: raise NotImplementedError() - @amzn_request_id def get_dashboard(self) -> Union[str, ERROR_RESPONSE]: dashboard_name = self._get_param("DashboardName") @@ -296,7 +282,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(GET_DASHBOARD_TEMPLATE) return template.render(dashboard=dashboard) - @amzn_request_id def list_dashboards(self) -> str: prefix = self._get_param("DashboardNamePrefix", "") @@ -305,7 +290,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(LIST_DASHBOARD_RESPONSE) return template.render(dashboards=dashboards) - @amzn_request_id def put_dashboard(self) -> Union[str, ERROR_RESPONSE]: name = self._get_param("DashboardName") body = self._get_param("DashboardBody") @@ -320,7 +304,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(PUT_DASHBOARD_RESPONSE) return template.render() - @amzn_request_id def set_alarm_state(self) -> str: alarm_name = self._get_param("AlarmName") reason = self._get_param("StateReason") @@ -334,7 +317,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(SET_ALARM_STATE_TEMPLATE) return template.render() - @amzn_request_id def list_tags_for_resource(self) -> str: resource_arn = self._get_param("ResourceARN") @@ -343,7 +325,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(LIST_TAGS_FOR_RESOURCE_TEMPLATE) return template.render(tags=tags) - @amzn_request_id def tag_resource(self) -> str: resource_arn = self._get_param("ResourceARN") tags = self._get_multi_param("Tags.member") @@ -353,7 +334,6 @@ class CloudWatchResponse(BaseResponse): template = self.response_template(TAG_RESOURCE_TEMPLATE) return template.render() - @amzn_request_id def untag_resource(self) -> str: resource_arn = self._get_param("ResourceARN") tag_keys = self._get_multi_param("TagKeys.member") diff --git a/moto/core/responses.py b/moto/core/responses.py index 02f07d06d..6b6306d2b 100644 --- a/moto/core/responses.py +++ b/moto/core/responses.py @@ -37,6 +37,7 @@ from moto.core.utils import ( params_sort_function, utcfromtimestamp, ) +from moto.utilities.aws_headers import gen_amzn_requestid_long from moto.utilities.utils import load_resource, load_resource_as_bytes log = logging.getLogger(__name__) @@ -267,7 +268,15 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): @functools.wraps(to_call) # type: ignore def _inner(request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: - return getattr(cls(), to_call.__name__)(request, full_url, headers) + response = getattr(cls(), to_call.__name__)(request, full_url, headers) + if isinstance(response, str): + status = 200 + body = response + headers = {} + else: + status, headers, body = response + headers, body = cls._enrich_response(headers, body) + return status, headers, body return _inner @@ -538,7 +547,10 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): self._authenticate_and_authorize_normal_action(resource) except HTTPException as http_error: response = http_error.description, dict(status=http_error.code) - return self._send_response(headers, response) + status, headers, body = self._transform_response(headers, response) + headers, body = self._enrich_response(headers, body) + + return status, headers, body action = camelcase_to_underscores(self._get_action()) method_names = method_names_from_class(self.__class__) @@ -555,9 +567,14 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): response = http_error.description, response_headers # type: ignore[assignment] if isinstance(response, str): - return 200, headers, response + status = 200 + body = response else: - return self._send_response(headers, response) + status, headers, body = self._transform_response(headers, response) + + headers, body = self._enrich_response(headers, body) + + return status, headers, body if not action: return 404, headers, "" @@ -565,19 +582,33 @@ class BaseResponse(_TemplateEnvironmentMixin, ActionAuthenticatorMixin): raise NotImplementedError(f"The {action} action has not been implemented") @staticmethod - def _send_response(headers: Dict[str, str], response: Any) -> Tuple[int, Dict[str, str], str]: # type: ignore[misc] + def _transform_response(headers: Dict[str, str], response: Any) -> TYPE_RESPONSE: # 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) + status = int(new_headers.get("status", 200)) headers.update(new_headers) + return status, headers, body + + @staticmethod + def _enrich_response( # type: ignore[misc] + headers: Dict[str, str], body: Any + ) -> Tuple[Dict[str, str], Any]: # Cast status to string if "status" in headers: headers["status"] = str(headers["status"]) - return status, headers, body + # add request id + request_id = gen_amzn_requestid_long(headers) + + # Update request ID in XML + try: + body = re.sub(r"(?<=).*(?=<\/RequestId>)", request_id, body) + except Exception: # Will just ignore if it cant work + pass + return headers, body def _get_param(self, param_name: str, if_none: Any = None) -> Any: val = self.querystring.get(param_name) diff --git a/moto/databrew/responses.py b/moto/databrew/responses.py index 8420922bc..fc0f209f6 100644 --- a/moto/databrew/responses.py +++ b/moto/databrew/responses.py @@ -3,7 +3,6 @@ from typing import Any, Dict from urllib.parse import unquote from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .models import DataBrewBackend, databrew_backends @@ -22,7 +21,6 @@ class DataBrewResponse(BaseResponse): def parameters(self) -> Dict[str, Any]: # type: ignore[misc] return json.loads(self.body) - @amzn_request_id def create_recipe(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_CreateRecipe.html recipe_description = self.parameters.get("Description") @@ -35,7 +33,6 @@ class DataBrewResponse(BaseResponse): ).as_dict() ) - @amzn_request_id def delete_recipe_version(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_DeleteRecipeVersion.html split_path = self._get_path().strip("/").split("/") @@ -47,7 +44,6 @@ class DataBrewResponse(BaseResponse): def _get_path(self) -> str: return unquote(self.parsed_url.path) - @amzn_request_id def list_recipes(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_ListRecipes.html next_token = self._get_param("NextToken", self._get_param("nextToken")) @@ -71,7 +67,6 @@ class DataBrewResponse(BaseResponse): } ) - @amzn_request_id def list_recipe_versions(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_ListRecipeVersions.html recipe_name = self._get_param("Name", self._get_param("name")) @@ -91,7 +86,6 @@ class DataBrewResponse(BaseResponse): } ) - @amzn_request_id def publish_recipe(self) -> str: recipe_name = self._get_path().strip("/").split("/", 2)[1] recipe_description = self.parameters.get("Description") @@ -123,7 +117,6 @@ class DataBrewResponse(BaseResponse): # region Rulesets - @amzn_request_id def create_ruleset(self) -> str: ruleset_description = self.parameters.get("Description") ruleset_rules = self.parameters.get("Rules") @@ -162,7 +155,6 @@ class DataBrewResponse(BaseResponse): self.databrew_backend.delete_ruleset(ruleset_name) return json.dumps({"Name": ruleset_name}) - @amzn_request_id def list_rulesets(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_ListRulesets.html next_token = self._get_param("NextToken", self._get_param("nextToken")) @@ -185,7 +177,6 @@ class DataBrewResponse(BaseResponse): # region Datasets - @amzn_request_id def create_dataset(self) -> str: dataset_name = self.parameters.get("Name") dataset_format = self.parameters.get("Format") @@ -205,7 +196,6 @@ class DataBrewResponse(BaseResponse): ).as_dict() ) - @amzn_request_id def list_datasets(self) -> str: next_token = self._get_param("NextToken", self._get_param("nextToken")) max_results = self._get_int_param( @@ -224,7 +214,6 @@ class DataBrewResponse(BaseResponse): } ) - @amzn_request_id def update_dataset(self) -> str: dataset_name = self._get_path().split("/")[-1] dataset_format = self.parameters.get("Format") @@ -243,13 +232,11 @@ class DataBrewResponse(BaseResponse): ) return json.dumps(dataset.as_dict()) - @amzn_request_id def delete_dataset(self) -> str: dataset_name = self._get_path().split("/")[-1] self.databrew_backend.delete_dataset(dataset_name) return json.dumps({"Name": dataset_name}) - @amzn_request_id def describe_dataset(self) -> str: dataset_name = self._get_path().split("/")[-1] dataset = self.databrew_backend.describe_dataset(dataset_name) @@ -258,7 +245,6 @@ class DataBrewResponse(BaseResponse): # endregion # region Jobs - @amzn_request_id def list_jobs(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_ListJobs.html dataset_name = self._get_param("datasetName") @@ -291,7 +277,6 @@ class DataBrewResponse(BaseResponse): self.databrew_backend.delete_job(job_name) return json.dumps({"Name": job_name}) - @amzn_request_id def create_profile_job(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_CreateProfileJob.html kwargs = { @@ -331,7 +316,6 @@ class DataBrewResponse(BaseResponse): } return json.dumps(self.databrew_backend.update_profile_job(**kwargs).as_dict()) - @amzn_request_id def create_recipe_job(self) -> str: # https://docs.aws.amazon.com/databrew/latest/dg/API_CreateRecipeJob.html kwargs = { @@ -353,7 +337,6 @@ class DataBrewResponse(BaseResponse): } return json.dumps(self.databrew_backend.create_recipe_job(**kwargs).as_dict()) - @amzn_request_id def update_recipe_job(self) -> str: name = self._get_path().rstrip("/").rsplit("/", 1)[1] # https://docs.aws.amazon.com/databrew/latest/dg/API_UpdateRecipeJob.html diff --git a/moto/dynamodb/responses.py b/moto/dynamodb/responses.py index b964253a5..5e8f93fd9 100644 --- a/moto/dynamodb/responses.py +++ b/moto/dynamodb/responses.py @@ -6,12 +6,11 @@ from typing import Any, Callable, Dict, List, Optional, Union from moto.core.common_types import TYPE_RESPONSE from moto.core.responses import BaseResponse -from moto.core.utils import camelcase_to_underscores from moto.dynamodb.models import DynamoDBBackend, Table, dynamodb_backends from moto.dynamodb.models.utilities import dynamo_json_dump from moto.dynamodb.parsing.key_condition_expression import parse_expression from moto.dynamodb.parsing.reserved_keywords import ReservedKeywords -from moto.utilities.aws_headers import amz_crc32, amzn_request_id +from moto.utilities.aws_headers import amz_crc32 from .exceptions import ( KeyIsEmptyStringException, @@ -40,10 +39,12 @@ def include_consumed_capacity( expected_capacity = handler.body.get("ReturnConsumedCapacity", "NONE") if expected_capacity not in ["NONE", "TOTAL", "INDEXES"]: type_ = "ValidationException" + headers = handler.response_headers.copy() + headers["status"] = "400" message = f"1 validation error detected: Value '{expected_capacity}' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]" return ( 400, - handler.response_headers, + headers, dynamo_json_dump({"__type": type_, "message": message}), ) table_name = handler.body.get("TableName", "") @@ -189,22 +190,9 @@ class DynamoHandler(BaseResponse): return dynamodb_backends[self.current_account][self.region] @amz_crc32 - @amzn_request_id def call_action(self) -> TYPE_RESPONSE: self.body = json.loads(self.body or "{}") - endpoint = self.get_endpoint_name(self.headers) - if endpoint: - endpoint = camelcase_to_underscores(endpoint) - response = getattr(self, endpoint)() - if isinstance(response, str): - return 200, self.response_headers, response - - else: - status_code, new_headers, response_content = response - self.response_headers.update(new_headers) - return status_code, self.response_headers, response_content - else: - return 404, self.response_headers, "" + return super().call_action() def list_tables(self) -> str: body = self.body diff --git a/moto/elbv2/responses.py b/moto/elbv2/responses.py index 8b50ab7bb..74dc6938c 100644 --- a/moto/elbv2/responses.py +++ b/moto/elbv2/responses.py @@ -1,6 +1,5 @@ from moto.core.exceptions import RESTError from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .exceptions import ListenerOrBalancerMissingError, TargetGroupNotFoundError from .models import ELBv2Backend, elbv2_backends @@ -375,7 +374,6 @@ class ELBV2Response(BaseResponse): def elbv2_backend(self) -> ELBv2Backend: return elbv2_backends[self.current_account][self.region] - @amzn_request_id def create_load_balancer(self) -> str: params = self._get_params() load_balancer_name = params.get("Name") @@ -398,7 +396,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(CREATE_LOAD_BALANCER_TEMPLATE) return template.render(load_balancer=load_balancer) - @amzn_request_id def create_rule(self) -> str: params = self._get_params() rules = self.elbv2_backend.create_rule( @@ -412,7 +409,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(CREATE_RULE_TEMPLATE) return template.render(rules=rules) - @amzn_request_id def create_target_group(self) -> str: params = self._get_params() name = params.get("Name") @@ -456,7 +452,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(CREATE_TARGET_GROUP_TEMPLATE) return template.render(target_group=target_group) - @amzn_request_id def create_listener(self) -> str: params = self._get_params() load_balancer_arn = self._get_param("LoadBalancerArn") @@ -486,7 +481,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(CREATE_LISTENER_TEMPLATE) return template.render(listener=listener) - @amzn_request_id def describe_load_balancers(self) -> str: arns = self._get_multi_param("LoadBalancerArns.member") names = self._get_multi_param("Names.member") @@ -510,7 +504,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_LOAD_BALANCERS_TEMPLATE) return template.render(load_balancers=load_balancers_resp, marker=next_marker) - @amzn_request_id def describe_rules(self) -> str: listener_arn = self._get_param("ListenerArn") rule_arns = ( @@ -539,7 +532,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_RULES_TEMPLATE) return template.render(rules=rules_resp, marker=next_marker) - @amzn_request_id def describe_target_groups(self) -> str: load_balancer_arn = self._get_param("LoadBalancerArn") target_group_arns = self._get_multi_param("TargetGroupArns.member") @@ -551,7 +543,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_TARGET_GROUPS_TEMPLATE) return template.render(target_groups=target_groups) - @amzn_request_id def describe_target_group_attributes(self) -> str: target_group_arn = self._get_param("TargetGroupArn") target_group = self.elbv2_backend.target_groups.get(target_group_arn) @@ -560,7 +551,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_TARGET_GROUP_ATTRIBUTES_TEMPLATE) return template.render(attributes=target_group.attributes) - @amzn_request_id def describe_listeners(self) -> str: load_balancer_arn = self._get_param("LoadBalancerArn") listener_arns = self._get_multi_param("ListenerArns.member") @@ -573,35 +563,30 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_LISTENERS_TEMPLATE) return template.render(listeners=listeners) - @amzn_request_id def delete_load_balancer(self) -> str: arn = self._get_param("LoadBalancerArn") self.elbv2_backend.delete_load_balancer(arn) template = self.response_template(DELETE_LOAD_BALANCER_TEMPLATE) return template.render() - @amzn_request_id def delete_rule(self) -> str: arn = self._get_param("RuleArn") self.elbv2_backend.delete_rule(arn) template = self.response_template(DELETE_RULE_TEMPLATE) return template.render() - @amzn_request_id def delete_target_group(self) -> str: arn = self._get_param("TargetGroupArn") self.elbv2_backend.delete_target_group(arn) template = self.response_template(DELETE_TARGET_GROUP_TEMPLATE) return template.render() - @amzn_request_id def delete_listener(self) -> str: arn = self._get_param("ListenerArn") self.elbv2_backend.delete_listener(arn) template = self.response_template(DELETE_LISTENER_TEMPLATE) return template.render() - @amzn_request_id def modify_rule(self) -> str: rule_arn = self._get_param("RuleArn") params = self._get_params() @@ -613,7 +598,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(MODIFY_RULE_TEMPLATE) return template.render(rules=rules) - @amzn_request_id def modify_target_group_attributes(self) -> str: target_group_arn = self._get_param("TargetGroupArn") attrs = self._get_list_prefix("Attributes.member") @@ -623,7 +607,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(MODIFY_TARGET_GROUP_ATTRIBUTES_TEMPLATE) return template.render(attributes=attributes) - @amzn_request_id def register_targets(self) -> str: target_group_arn = self._get_param("TargetGroupArn") targets = self._get_list_prefix("Targets.member") @@ -632,7 +615,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(REGISTER_TARGETS_TEMPLATE) return template.render() - @amzn_request_id def deregister_targets(self) -> str: target_group_arn = self._get_param("TargetGroupArn") targets = self._get_list_prefix("Targets.member") @@ -641,7 +623,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DEREGISTER_TARGETS_TEMPLATE) return template.render() - @amzn_request_id def describe_target_health(self) -> str: target_group_arn = self._get_param("TargetGroupArn") targets = self._get_list_prefix("Targets.member") @@ -652,7 +633,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_TARGET_HEALTH_TEMPLATE) return template.render(target_health_descriptions=target_health_descriptions) - @amzn_request_id def set_rule_priorities(self) -> str: rule_priorities = self._get_list_prefix("RulePriorities.member") for rule_priority in rule_priorities: @@ -661,7 +641,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(SET_RULE_PRIORITIES_TEMPLATE) return template.render(rules=rules) - @amzn_request_id def add_tags(self) -> str: resource_arns = self._get_multi_param("ResourceArns.member") tags = self._get_params().get("Tags") @@ -671,7 +650,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(ADD_TAGS_TEMPLATE) return template.render() - @amzn_request_id def remove_tags(self) -> str: resource_arns = self._get_multi_param("ResourceArns.member") tag_keys = self._get_multi_param("TagKeys.member") @@ -681,7 +659,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(REMOVE_TAGS_TEMPLATE) return template.render() - @amzn_request_id def describe_tags(self) -> str: resource_arns = self._get_multi_param("ResourceArns.member") resource_tags = self.elbv2_backend.describe_tags(resource_arns) @@ -689,7 +666,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_TAGS_TEMPLATE) return template.render(resource_tags=resource_tags) - @amzn_request_id def describe_account_limits(self) -> str: # Supports paging but not worth implementing yet # marker = self._get_param('Marker') @@ -709,7 +685,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_LIMITS_TEMPLATE) return template.render(limits=limits) - @amzn_request_id def describe_ssl_policies(self) -> str: names = self._get_multi_param("Names.member.") # Supports paging but not worth implementing yet @@ -723,7 +698,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_SSL_POLICIES_TEMPLATE) return template.render(policies=policies) - @amzn_request_id def set_ip_address_type(self) -> str: arn = self._get_param("LoadBalancerArn") ip_type = self._get_param("IpAddressType") @@ -733,7 +707,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(SET_IP_ADDRESS_TYPE_TEMPLATE) return template.render(ip_type=ip_type) - @amzn_request_id def set_security_groups(self) -> str: arn = self._get_param("LoadBalancerArn") sec_groups = self._get_multi_param("SecurityGroups.member.") @@ -743,7 +716,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(SET_SECURITY_GROUPS_TEMPLATE) return template.render(sec_groups=sec_groups) - @amzn_request_id def set_subnets(self) -> str: arn = self._get_param("LoadBalancerArn") subnets = self._get_multi_param("Subnets.member.") @@ -754,7 +726,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(SET_SUBNETS_TEMPLATE) return template.render(subnets=subnet_zone_list) - @amzn_request_id def modify_load_balancer_attributes(self) -> str: arn = self._get_param("LoadBalancerArn") attrs = self._get_map_prefix( @@ -766,7 +737,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(MODIFY_LOADBALANCER_ATTRS_TEMPLATE) return template.render(attrs=all_attrs) - @amzn_request_id def describe_load_balancer_attributes(self) -> str: arn = self._get_param("LoadBalancerArn") attrs = self.elbv2_backend.describe_load_balancer_attributes(arn) @@ -774,7 +744,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_LOADBALANCER_ATTRS_TEMPLATE) return template.render(attrs=attrs) - @amzn_request_id def modify_target_group(self) -> str: arn = self._get_param("TargetGroupArn") @@ -806,7 +775,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(MODIFY_TARGET_GROUP_TEMPLATE) return template.render(target_group=target_group) - @amzn_request_id def modify_listener(self) -> str: arn = self._get_param("ListenerArn") port = self._get_param("Port") @@ -828,7 +796,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(MODIFY_LISTENER_TEMPLATE) return template.render(listener=listener) - @amzn_request_id def add_listener_certificates(self) -> str: arn = self._get_param("ListenerArn") certificates = self._get_list_prefix("Certificates.member") @@ -839,7 +806,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(ADD_LISTENER_CERTIFICATES_TEMPLATE) return template.render(certificates=certificate_arns) - @amzn_request_id def describe_listener_certificates(self) -> str: arn = self._get_param("ListenerArn") certificates = self.elbv2_backend.describe_listener_certificates(arn) @@ -847,7 +813,6 @@ class ELBV2Response(BaseResponse): template = self.response_template(DESCRIBE_LISTENER_CERTIFICATES_TEMPLATE) return template.render(certificates=certificates) - @amzn_request_id def remove_listener_certificates(self) -> str: arn = self._get_param("ListenerArn") certificates = self._get_list_prefix("Certificates.member") diff --git a/moto/forecast/responses.py b/moto/forecast/responses.py index 3d4dfa0ac..e824efb3e 100644 --- a/moto/forecast/responses.py +++ b/moto/forecast/responses.py @@ -2,7 +2,6 @@ import json from moto.core.common_types import TYPE_RESPONSE from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .models import ForecastBackend, forecast_backends @@ -15,7 +14,6 @@ class ForecastResponse(BaseResponse): def forecast_backend(self) -> ForecastBackend: return forecast_backends[self.current_account][self.region] - @amzn_request_id def create_dataset_group(self) -> TYPE_RESPONSE: dataset_group_name = self._get_param("DatasetGroupName") domain = self._get_param("Domain") @@ -31,7 +29,6 @@ class ForecastResponse(BaseResponse): response = {"DatasetGroupArn": dataset_group.arn} return 200, {}, json.dumps(response) - @amzn_request_id def describe_dataset_group(self) -> TYPE_RESPONSE: dataset_group_arn = self._get_param("DatasetGroupArn") @@ -49,20 +46,17 @@ class ForecastResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def delete_dataset_group(self) -> TYPE_RESPONSE: dataset_group_arn = self._get_param("DatasetGroupArn") self.forecast_backend.delete_dataset_group(dataset_group_arn) return 200, {}, "" - @amzn_request_id def update_dataset_group(self) -> TYPE_RESPONSE: dataset_group_arn = self._get_param("DatasetGroupArn") dataset_arns = self._get_param("DatasetArns") self.forecast_backend.update_dataset_group(dataset_group_arn, dataset_arns) return 200, {}, "" - @amzn_request_id def list_dataset_groups(self) -> TYPE_RESPONSE: list_all = sorted( [ diff --git a/moto/s3/responses.py b/moto/s3/responses.py index 8d666ebf1..1b189521f 100644 --- a/moto/s3/responses.py +++ b/moto/s3/responses.py @@ -21,7 +21,6 @@ from moto.s3bucket_path.utils import ( from moto.s3bucket_path.utils import ( parse_key_name as bucketpath_parse_key_name, ) -from moto.utilities.aws_headers import amzn_request_id from .exceptions import ( AccessForbidden, @@ -284,7 +283,6 @@ class S3Response(BaseResponse): # Using path-based buckets return self.bucket_response(request, full_url, headers) - @amzn_request_id def bucket_response( self, request: Any, full_url: str, headers: Any ) -> TYPE_RESPONSE: @@ -1246,7 +1244,6 @@ class S3Response(BaseResponse): # last line should equal # amz-checksum-sha256:<..>\r\n - @amzn_request_id def key_response( self, request: Any, full_url: str, headers: Dict[str, Any] ) -> TYPE_RESPONSE: diff --git a/moto/s3control/responses.py b/moto/s3control/responses.py index 8122c5c62..140cf5daf 100644 --- a/moto/s3control/responses.py +++ b/moto/s3control/responses.py @@ -7,7 +7,6 @@ from moto.core.common_types import TYPE_RESPONSE from moto.core.responses import BaseResponse from moto.s3.exceptions import S3ClientError from moto.s3.responses import S3_PUBLIC_ACCESS_BLOCK_CONFIGURATION -from moto.utilities.aws_headers import amzn_request_id from .models import S3ControlBackend, s3control_backends @@ -20,7 +19,6 @@ class S3ControlResponse(BaseResponse): def backend(self) -> S3ControlBackend: return s3control_backends[self.current_account]["global"] - @amzn_request_id def public_access_block(self, request: Any, full_url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore self.setup_class(request, full_url, headers) try: diff --git a/moto/sagemaker/responses.py b/moto/sagemaker/responses.py index fa63920b0..948cf1bc7 100644 --- a/moto/sagemaker/responses.py +++ b/moto/sagemaker/responses.py @@ -4,7 +4,6 @@ from typing import Any from moto.core.common_types import TYPE_RESPONSE from moto.core.responses import BaseResponse from moto.sagemaker.exceptions import AWSValidationException -from moto.utilities.aws_headers import amzn_request_id from .models import SageMakerModelBackend, sagemaker_backends @@ -52,7 +51,6 @@ class SageMakerResponse(BaseResponse): models = self.sagemaker_backend.list_models() return json.dumps({"Models": [model.response_object for model in models]}) - @amzn_request_id def create_notebook_instance(self) -> TYPE_RESPONSE: sagemaker_notebook = self.sagemaker_backend.create_notebook_instance( notebook_instance_name=self._get_param("NotebookInstanceName"), @@ -72,7 +70,6 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps({"NotebookInstanceArn": sagemaker_notebook.arn}) - @amzn_request_id def describe_notebook_instance(self) -> str: notebook_instance_name = self._get_param("NotebookInstanceName") notebook_instance = self.sagemaker_backend.get_notebook_instance( @@ -80,25 +77,21 @@ class SageMakerResponse(BaseResponse): ) return json.dumps(notebook_instance.to_dict()) - @amzn_request_id def start_notebook_instance(self) -> TYPE_RESPONSE: notebook_instance_name = self._get_param("NotebookInstanceName") self.sagemaker_backend.start_notebook_instance(notebook_instance_name) return 200, {}, json.dumps("{}") - @amzn_request_id def stop_notebook_instance(self) -> TYPE_RESPONSE: notebook_instance_name = self._get_param("NotebookInstanceName") self.sagemaker_backend.stop_notebook_instance(notebook_instance_name) return 200, {}, json.dumps("{}") - @amzn_request_id def delete_notebook_instance(self) -> TYPE_RESPONSE: notebook_instance_name = self._get_param("NotebookInstanceName") self.sagemaker_backend.delete_notebook_instance(notebook_instance_name) return 200, {}, json.dumps("{}") - @amzn_request_id def list_notebook_instances(self) -> str: sort_by = self._get_param("SortBy", "Name") sort_order = self._get_param("SortOrder", "Ascending") @@ -121,7 +114,6 @@ class SageMakerResponse(BaseResponse): } ) - @amzn_request_id def list_tags(self) -> TYPE_RESPONSE: arn = self._get_param("ResourceArn") max_results = self._get_param("MaxResults") @@ -134,21 +126,18 @@ class SageMakerResponse(BaseResponse): response["NextToken"] = next_token return 200, {}, json.dumps(response) - @amzn_request_id def add_tags(self) -> TYPE_RESPONSE: arn = self._get_param("ResourceArn") tags = self._get_param("Tags") tags = self.sagemaker_backend.add_tags(arn, tags) return 200, {}, json.dumps({"Tags": tags}) - @amzn_request_id def delete_tags(self) -> TYPE_RESPONSE: arn = self._get_param("ResourceArn") tag_keys = self._get_param("TagKeys") self.sagemaker_backend.delete_tags(arn, tag_keys) return 200, {}, json.dumps({}) - @amzn_request_id def create_endpoint_config(self) -> TYPE_RESPONSE: endpoint_config = self.sagemaker_backend.create_endpoint_config( endpoint_config_name=self._get_param("EndpointConfigName"), @@ -163,19 +152,16 @@ class SageMakerResponse(BaseResponse): json.dumps({"EndpointConfigArn": endpoint_config.endpoint_config_arn}), ) - @amzn_request_id def describe_endpoint_config(self) -> str: endpoint_config_name = self._get_param("EndpointConfigName") response = self.sagemaker_backend.describe_endpoint_config(endpoint_config_name) return json.dumps(response) - @amzn_request_id def delete_endpoint_config(self) -> TYPE_RESPONSE: endpoint_config_name = self._get_param("EndpointConfigName") self.sagemaker_backend.delete_endpoint_config(endpoint_config_name) return 200, {}, json.dumps("{}") - @amzn_request_id def create_endpoint(self) -> TYPE_RESPONSE: endpoint = self.sagemaker_backend.create_endpoint( endpoint_name=self._get_param("EndpointName"), @@ -184,19 +170,16 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps({"EndpointArn": endpoint.endpoint_arn}) - @amzn_request_id def describe_endpoint(self) -> str: endpoint_name = self._get_param("EndpointName") response = self.sagemaker_backend.describe_endpoint(endpoint_name) return json.dumps(response) - @amzn_request_id def delete_endpoint(self) -> TYPE_RESPONSE: endpoint_name = self._get_param("EndpointName") self.sagemaker_backend.delete_endpoint(endpoint_name) return 200, {}, json.dumps("{}") - @amzn_request_id def create_processing_job(self) -> TYPE_RESPONSE: processing_job = self.sagemaker_backend.create_processing_job( app_specification=self._get_param("AppSpecification"), @@ -212,13 +195,11 @@ class SageMakerResponse(BaseResponse): response = {"ProcessingJobArn": processing_job.processing_job_arn} return 200, {}, json.dumps(response) - @amzn_request_id def describe_processing_job(self) -> str: processing_job_name = self._get_param("ProcessingJobName") response = self.sagemaker_backend.describe_processing_job(processing_job_name) return json.dumps(response) - @amzn_request_id def create_transform_job(self) -> TYPE_RESPONSE: transform_job = self.sagemaker_backend.create_transform_job( transform_job_name=self._get_param("TransformJobName"), @@ -241,7 +222,6 @@ class SageMakerResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def describe_transform_job(self) -> str: transform_job_name = self._get_param("TransformJobName") response = self.sagemaker_backend.describe_transform_job( @@ -249,7 +229,6 @@ class SageMakerResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def create_training_job(self) -> TYPE_RESPONSE: training_job = self.sagemaker_backend.create_training_job( training_job_name=self._get_param("TrainingJobName"), @@ -280,13 +259,11 @@ class SageMakerResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def describe_training_job(self) -> str: training_job_name = self._get_param("TrainingJobName") response = self.sagemaker_backend.describe_training_job(training_job_name) return json.dumps(response) - @amzn_request_id def create_notebook_instance_lifecycle_config(self) -> TYPE_RESPONSE: lifecycle_configuration = ( self.sagemaker_backend.create_notebook_instance_lifecycle_config( @@ -302,7 +279,6 @@ class SageMakerResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def describe_notebook_instance_lifecycle_config(self) -> str: response = self.sagemaker_backend.describe_notebook_instance_lifecycle_config( notebook_instance_lifecycle_config_name=self._get_param( @@ -311,7 +287,6 @@ class SageMakerResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def delete_notebook_instance_lifecycle_config(self) -> TYPE_RESPONSE: self.sagemaker_backend.delete_notebook_instance_lifecycle_config( notebook_instance_lifecycle_config_name=self._get_param( @@ -320,7 +295,6 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps("{}") - @amzn_request_id def search(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.search( resource=self._get_param("Resource"), @@ -328,7 +302,6 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def list_experiments(self) -> TYPE_RESPONSE: MaxResults = self._get_param("MaxResults") NextToken = self._get_param("NextToken") @@ -356,28 +329,24 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps(response) - @amzn_request_id def delete_experiment(self) -> TYPE_RESPONSE: self.sagemaker_backend.delete_experiment( experiment_name=self._get_param("ExperimentName") ) return 200, {}, json.dumps({}) - @amzn_request_id def create_experiment(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.create_experiment( experiment_name=self._get_param("ExperimentName") ) return 200, {}, json.dumps(response) - @amzn_request_id def describe_experiment(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.describe_experiment( experiment_name=self._get_param("ExperimentName") ) return 200, {}, json.dumps(response) - @amzn_request_id def list_trials(self) -> TYPE_RESPONSE: MaxResults = self._get_param("MaxResults") NextToken = self._get_param("NextToken") @@ -408,7 +377,6 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps(response) - @amzn_request_id def create_trial(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.create_trial( trial_name=self._get_param("TrialName"), @@ -416,7 +384,6 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def list_trial_components(self) -> TYPE_RESPONSE: MaxResults = self._get_param("MaxResults") NextToken = self._get_param("NextToken") @@ -446,7 +413,6 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps(response) - @amzn_request_id def create_trial_component(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.create_trial_component( trial_component_name=self._get_param("TrialComponentName"), @@ -454,31 +420,26 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def describe_trial(self) -> str: trial_name = self._get_param("TrialName") response = self.sagemaker_backend.describe_trial(trial_name) return json.dumps(response) - @amzn_request_id def delete_trial(self) -> TYPE_RESPONSE: trial_name = self._get_param("TrialName") self.sagemaker_backend.delete_trial(trial_name) return 200, {}, json.dumps({}) - @amzn_request_id def delete_trial_component(self) -> TYPE_RESPONSE: trial_component_name = self._get_param("TrialComponentName") self.sagemaker_backend.delete_trial_component(trial_component_name) return 200, {}, json.dumps({}) - @amzn_request_id def describe_trial_component(self) -> str: trial_component_name = self._get_param("TrialComponentName") response = self.sagemaker_backend.describe_trial_component(trial_component_name) return json.dumps(response) - @amzn_request_id def associate_trial_component(self) -> TYPE_RESPONSE: trial_name = self._get_param("TrialName") trial_component_name = self._get_param("TrialComponentName") @@ -487,7 +448,6 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def disassociate_trial_component(self) -> TYPE_RESPONSE: trial_component_name = self._get_param("TrialComponentName") trial_name = self._get_param("TrialName") @@ -496,14 +456,12 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def describe_pipeline(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.describe_pipeline( self._get_param("PipelineName") ) return 200, {}, json.dumps(response) - @amzn_request_id def start_pipeline_execution(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.start_pipeline_execution( self._get_param("PipelineName"), @@ -515,35 +473,30 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def describe_pipeline_execution(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.describe_pipeline_execution( self._get_param("PipelineExecutionArn") ) return 200, {}, json.dumps(response) - @amzn_request_id def describe_pipeline_definition_for_execution(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.describe_pipeline_definition_for_execution( self._get_param("PipelineExecutionArn") ) return 200, {}, json.dumps(response) - @amzn_request_id def list_pipeline_parameters_for_execution(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.list_pipeline_parameters_for_execution( self._get_param("PipelineExecutionArn") ) return 200, {}, json.dumps(response) - @amzn_request_id def list_pipeline_executions(self) -> TYPE_RESPONSE: response = self.sagemaker_backend.list_pipeline_executions( self._get_param("PipelineName") ) return 200, {}, json.dumps(response) - @amzn_request_id def create_pipeline(self) -> TYPE_RESPONSE: pipeline = self.sagemaker_backend.create_pipeline( pipeline_name=self._get_param("PipelineName"), @@ -563,7 +516,6 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps(response) - @amzn_request_id def delete_pipeline(self) -> TYPE_RESPONSE: pipeline_arn = self.sagemaker_backend.delete_pipeline( pipeline_name=self._get_param("PipelineName"), @@ -571,7 +523,6 @@ class SageMakerResponse(BaseResponse): response = {"PipelineArn": pipeline_arn} return 200, {}, json.dumps(response) - @amzn_request_id def update_pipeline(self) -> TYPE_RESPONSE: pipeline_arn = self.sagemaker_backend.update_pipeline( pipeline_name=self._get_param("PipelineName"), @@ -588,7 +539,6 @@ class SageMakerResponse(BaseResponse): response = {"PipelineArn": pipeline_arn} return 200, {}, json.dumps(response) - @amzn_request_id def list_pipelines(self) -> TYPE_RESPONSE: max_results_range = range(1, 101) allowed_sort_by = ("Name", "CreationTime") @@ -631,7 +581,6 @@ class SageMakerResponse(BaseResponse): return 200, {}, json.dumps(response) - @amzn_request_id def list_processing_jobs(self) -> TYPE_RESPONSE: max_results_range = range(1, 101) allowed_sort_by = ["Name", "CreationTime", "Status"] @@ -684,7 +633,6 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def list_transform_jobs(self) -> TYPE_RESPONSE: max_results_range = range(1, 101) allowed_sort_by = ["Name", "CreationTime", "Status"] @@ -737,7 +685,6 @@ class SageMakerResponse(BaseResponse): ) return 200, {}, json.dumps(response) - @amzn_request_id def list_training_jobs(self) -> TYPE_RESPONSE: max_results_range = range(1, 101) allowed_sort_by = ["Name", "CreationTime", "Status"] diff --git a/moto/sqs/responses.py b/moto/sqs/responses.py index b2a0cf1dc..458a3bb0d 100644 --- a/moto/sqs/responses.py +++ b/moto/sqs/responses.py @@ -12,7 +12,7 @@ from moto.core.utils import ( camelcase_to_underscores, underscores_to_camelcase, ) -from moto.utilities.aws_headers import amz_crc32, amzn_request_id +from moto.utilities.aws_headers import amz_crc32 from moto.utilities.constants import JSON_TYPES from .constants import ( @@ -134,7 +134,6 @@ class SQSResponse(BaseResponse): return visibility_timeout @amz_crc32 # crc last as request_id can edit XML - @amzn_request_id def call_action(self) -> TYPE_RESPONSE: status_code, headers, body = super().call_action() if status_code == 404: diff --git a/moto/stepfunctions/responses.py b/moto/stepfunctions/responses.py index ee38ff011..9335d7805 100644 --- a/moto/stepfunctions/responses.py +++ b/moto/stepfunctions/responses.py @@ -2,7 +2,6 @@ import json from moto.core.common_types import TYPE_RESPONSE from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .models import StepFunctionBackend, stepfunctions_backends @@ -15,7 +14,6 @@ class StepFunctionResponse(BaseResponse): def stepfunction_backend(self) -> StepFunctionBackend: return stepfunctions_backends[self.current_account][self.region] - @amzn_request_id def create_state_machine(self) -> TYPE_RESPONSE: name = self._get_param("name") definition = self._get_param("definition") @@ -30,7 +28,6 @@ class StepFunctionResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def list_state_machines(self) -> TYPE_RESPONSE: max_results = self._get_int_param("maxResults") next_token = self._get_param("nextToken") @@ -50,12 +47,10 @@ class StepFunctionResponse(BaseResponse): response["nextToken"] = next_token return 200, {}, json.dumps(response) - @amzn_request_id def describe_state_machine(self) -> TYPE_RESPONSE: arn = self._get_param("stateMachineArn") return self._describe_state_machine(arn) - @amzn_request_id def _describe_state_machine(self, state_machine_arn: str) -> TYPE_RESPONSE: state_machine = self.stepfunction_backend.describe_state_machine( state_machine_arn @@ -70,13 +65,11 @@ class StepFunctionResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def delete_state_machine(self) -> TYPE_RESPONSE: arn = self._get_param("stateMachineArn") self.stepfunction_backend.delete_state_machine(arn) return 200, {}, json.dumps("{}") - @amzn_request_id def update_state_machine(self) -> TYPE_RESPONSE: arn = self._get_param("stateMachineArn") definition = self._get_param("definition") @@ -89,28 +82,24 @@ class StepFunctionResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def list_tags_for_resource(self) -> TYPE_RESPONSE: arn = self._get_param("resourceArn") tags = self.stepfunction_backend.list_tags_for_resource(arn) response = {"tags": tags} return 200, {}, json.dumps(response) - @amzn_request_id def tag_resource(self) -> TYPE_RESPONSE: arn = self._get_param("resourceArn") tags = self._get_param("tags", []) self.stepfunction_backend.tag_resource(arn, tags) return 200, {}, json.dumps({}) - @amzn_request_id def untag_resource(self) -> TYPE_RESPONSE: arn = self._get_param("resourceArn") tag_keys = self._get_param("tagKeys", []) self.stepfunction_backend.untag_resource(arn, tag_keys) return 200, {}, json.dumps({}) - @amzn_request_id def start_execution(self) -> TYPE_RESPONSE: arn = self._get_param("stateMachineArn") name = self._get_param("name") @@ -124,7 +113,6 @@ class StepFunctionResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def list_executions(self) -> TYPE_RESPONSE: max_results = self._get_int_param("maxResults") next_token = self._get_param("nextToken") @@ -153,7 +141,6 @@ class StepFunctionResponse(BaseResponse): response["nextToken"] = next_token return 200, {}, json.dumps(response) - @amzn_request_id def describe_execution(self) -> TYPE_RESPONSE: arn = self._get_param("executionArn") execution = self.stepfunction_backend.describe_execution(arn) @@ -168,20 +155,17 @@ class StepFunctionResponse(BaseResponse): } return 200, {}, json.dumps(response) - @amzn_request_id def describe_state_machine_for_execution(self) -> TYPE_RESPONSE: arn = self._get_param("executionArn") execution = self.stepfunction_backend.describe_execution(arn) return self._describe_state_machine(execution.state_machine_arn) - @amzn_request_id def stop_execution(self) -> TYPE_RESPONSE: arn = self._get_param("executionArn") execution = self.stepfunction_backend.stop_execution(arn) response = {"stopDate": execution.stop_date} return 200, {}, json.dumps(response) - @amzn_request_id def get_execution_history(self) -> TYPE_RESPONSE: execution_arn = self._get_param("executionArn") execution_history = self.stepfunction_backend.get_execution_history( diff --git a/moto/transcribe/responses.py b/moto/transcribe/responses.py index e8e31876f..140605374 100644 --- a/moto/transcribe/responses.py +++ b/moto/transcribe/responses.py @@ -1,7 +1,6 @@ import json from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .models import TranscribeBackend, transcribe_backends @@ -14,7 +13,6 @@ class TranscribeResponse(BaseResponse): def transcribe_backend(self) -> TranscribeBackend: return transcribe_backends[self.current_account][self.region] - @amzn_request_id def start_transcription_job(self) -> str: name = self._get_param("TranscriptionJobName") response = self.transcribe_backend.start_transcription_job( @@ -37,7 +35,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def start_medical_transcription_job(self) -> str: name = self._get_param("MedicalTranscriptionJobName") response = self.transcribe_backend.start_medical_transcription_job( @@ -54,7 +51,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def list_transcription_jobs(self) -> str: state_equals = self._get_param("Status") job_name_contains = self._get_param("JobNameContains") @@ -69,7 +65,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def list_medical_transcription_jobs(self) -> str: status = self._get_param("Status") job_name_contains = self._get_param("JobNameContains") @@ -84,7 +79,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def get_transcription_job(self) -> str: transcription_job_name = self._get_param("TranscriptionJobName") response = self.transcribe_backend.get_transcription_job( @@ -92,7 +86,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def get_medical_transcription_job(self) -> str: medical_transcription_job_name = self._get_param("MedicalTranscriptionJobName") response = self.transcribe_backend.get_medical_transcription_job( @@ -100,7 +93,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def delete_transcription_job(self) -> str: transcription_job_name = self._get_param("TranscriptionJobName") self.transcribe_backend.delete_transcription_job( @@ -108,7 +100,6 @@ class TranscribeResponse(BaseResponse): ) return "{}" - @amzn_request_id def delete_medical_transcription_job(self) -> str: medical_transcription_job_name = self._get_param("MedicalTranscriptionJobName") self.transcribe_backend.delete_medical_transcription_job( @@ -116,7 +107,6 @@ class TranscribeResponse(BaseResponse): ) return "{}" - @amzn_request_id def create_vocabulary(self) -> str: vocabulary_name = self._get_param("VocabularyName") language_code = self._get_param("LanguageCode") @@ -130,7 +120,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def create_medical_vocabulary(self) -> str: vocabulary_name = self._get_param("VocabularyName") language_code = self._get_param("LanguageCode") @@ -142,7 +131,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def get_vocabulary(self) -> str: vocabulary_name = self._get_param("VocabularyName") response = self.transcribe_backend.get_vocabulary( @@ -150,7 +138,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def get_medical_vocabulary(self) -> str: vocabulary_name = self._get_param("VocabularyName") response = self.transcribe_backend.get_medical_vocabulary( @@ -158,7 +145,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def list_vocabularies(self) -> str: state_equals = self._get_param("StateEquals") name_contains = self._get_param("NameContains") @@ -173,7 +159,6 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def list_medical_vocabularies(self) -> str: state_equals = self._get_param("StateEquals") name_contains = self._get_param("NameContains") @@ -188,13 +173,11 @@ class TranscribeResponse(BaseResponse): ) return json.dumps(response) - @amzn_request_id def delete_vocabulary(self) -> str: vocabulary_name = self._get_param("VocabularyName") self.transcribe_backend.delete_vocabulary(vocabulary_name=vocabulary_name) return "{}" - @amzn_request_id def delete_medical_vocabulary(self) -> str: vocabulary_name = self._get_param("VocabularyName") self.transcribe_backend.delete_medical_vocabulary( diff --git a/moto/utilities/aws_headers.py b/moto/utilities/aws_headers.py index c63a3f73e..15856a4cb 100644 --- a/moto/utilities/aws_headers.py +++ b/moto/utilities/aws_headers.py @@ -7,9 +7,6 @@ else: Protocol = object import binascii -import re - -from moto.moto_api._internal import mock_random as random TypeDec = TypeVar("TypeDec", bound=Callable[..., Any]) @@ -32,6 +29,8 @@ def gen_amz_crc32(response: Any, headerdict: Optional[Dict[str, Any]] = None) -> def gen_amzn_requestid_long(headerdict: Optional[Dict[str, Any]] = None) -> str: + from moto.moto_api._internal import mock_random as random + req_id = random.get_random_string(length=52) if headerdict is not None and isinstance(headerdict, dict): @@ -53,7 +52,7 @@ def amz_crc32(f: TypeDec) -> GenericFunction: else: if len(response) == 2: body, new_headers = response - status = new_headers.get("status", 200) + status = new_headers.get("status", status) else: status, new_headers, body = response headers.update(new_headers) @@ -66,34 +65,3 @@ def amz_crc32(f: TypeDec) -> GenericFunction: return status, headers, body return _wrapper - - -def amzn_request_id(f: TypeDec) -> GenericFunction: - @wraps(f) - def _wrapper(*args: Any, **kwargs: Any) -> Any: # type: ignore[misc] - response = f(*args, **kwargs) - - headers = {} - status = 200 - - if isinstance(response, str): - body = response - else: - if len(response) == 2: - body, new_headers = response - status = new_headers.get("status", 200) - else: - status, new_headers, body = response - headers.update(new_headers) - - request_id = gen_amzn_requestid_long(headers) - - # Update request ID in XML - try: - body = re.sub(r"(?<=).*(?=<\/RequestId>)", request_id, body) - except Exception: # Will just ignore if it cant work - pass - - return status, headers, body - - return _wrapper diff --git a/moto/wafv2/responses.py b/moto/wafv2/responses.py index 62b3dc93e..ea81e45c7 100644 --- a/moto/wafv2/responses.py +++ b/moto/wafv2/responses.py @@ -2,7 +2,6 @@ import json from moto.core.common_types import TYPE_RESPONSE from moto.core.responses import BaseResponse -from moto.utilities.aws_headers import amzn_request_id from .models import GLOBAL_REGION, WAFV2Backend, wafv2_backends @@ -15,7 +14,6 @@ class WAFV2Response(BaseResponse): def wafv2_backend(self) -> WAFV2Backend: return wafv2_backends[self.current_account][self.region] - @amzn_request_id def associate_web_acl(self) -> TYPE_RESPONSE: body = json.loads(self.body) web_acl_arn = body["WebACLArn"] @@ -23,14 +21,12 @@ class WAFV2Response(BaseResponse): self.wafv2_backend.associate_web_acl(web_acl_arn, resource_arn) return 200, {}, "{}" - @amzn_request_id def disassociate_web_acl(self) -> TYPE_RESPONSE: body = json.loads(self.body) resource_arn = body["ResourceArn"] self.wafv2_backend.disassociate_web_acl(resource_arn) return 200, {}, "{}" - @amzn_request_id def get_web_acl_for_resource(self) -> TYPE_RESPONSE: body = json.loads(self.body) resource_arn = body["ResourceArn"] @@ -39,7 +35,6 @@ class WAFV2Response(BaseResponse): response_headers = {"Content-Type": "application/json"} return 200, response_headers, json.dumps(response) - @amzn_request_id def create_web_acl(self) -> TYPE_RESPONSE: """https://docs.aws.amazon.com/waf/latest/APIReference/API_CreateWebACL.html (response syntax section)""" @@ -64,7 +59,6 @@ class WAFV2Response(BaseResponse): response_headers = {"Content-Type": "application/json"} return 200, response_headers, json.dumps(response) - @amzn_request_id def delete_web_acl(self) -> TYPE_RESPONSE: scope = self._get_param("Scope") if scope == "CLOUDFRONT": @@ -75,7 +69,6 @@ class WAFV2Response(BaseResponse): response_headers = {"Content-Type": "application/json"} return 200, response_headers, "{}" - @amzn_request_id def get_web_acl(self) -> TYPE_RESPONSE: scope = self._get_param("Scope") if scope == "CLOUDFRONT": @@ -87,7 +80,6 @@ class WAFV2Response(BaseResponse): response_headers = {"Content-Type": "application/json"} return 200, response_headers, json.dumps(response) - @amzn_request_id def list_web_ac_ls(self) -> TYPE_RESPONSE: """https://docs.aws.amazon.com/waf/latest/APIReference/API_ListWebACLs.html (response syntax section)""" @@ -99,7 +91,6 @@ class WAFV2Response(BaseResponse): response_headers = {"Content-Type": "application/json"} return 200, response_headers, json.dumps(response) - @amzn_request_id def list_rule_groups(self) -> TYPE_RESPONSE: scope = self._get_param("Scope") if scope == "CLOUDFRONT": @@ -109,7 +100,6 @@ class WAFV2Response(BaseResponse): response_headers = {"Content-Type": "application/json"} return 200, response_headers, json.dumps(response) - @amzn_request_id def list_tags_for_resource(self) -> TYPE_RESPONSE: arn = self._get_param("ResourceARN") self.region = arn.split(":")[3] @@ -118,7 +108,6 @@ class WAFV2Response(BaseResponse): response_headers = {"Content-Type": "application/json"} return 200, response_headers, json.dumps(response) - @amzn_request_id def tag_resource(self) -> TYPE_RESPONSE: body = json.loads(self.body) arn = body.get("ResourceARN") @@ -127,7 +116,6 @@ class WAFV2Response(BaseResponse): self.wafv2_backend.tag_resource(arn, tags) return 200, {}, "{}" - @amzn_request_id def untag_resource(self) -> TYPE_RESPONSE: body = json.loads(self.body) arn = body.get("ResourceARN") @@ -136,7 +124,6 @@ class WAFV2Response(BaseResponse): self.wafv2_backend.untag_resource(arn, tag_keys) return 200, {}, "{}" - @amzn_request_id def update_web_acl(self) -> TYPE_RESPONSE: body = json.loads(self.body) name = body.get("Name") diff --git a/tests/test_apigateway/test_apigateway.py b/tests/test_apigateway/test_apigateway.py index 6832ec956..88bfc2a2b 100644 --- a/tests/test_apigateway/test_apigateway.py +++ b/tests/test_apigateway/test_apigateway.py @@ -296,6 +296,7 @@ def test_create_resource(): # this is hard to match against, so remove it root_resource["ResponseMetadata"].pop("HTTPHeaders", None) root_resource["ResponseMetadata"].pop("RetryAttempts", None) + root_resource["ResponseMetadata"].pop("RequestId") assert root_resource == { "path": "/", "id": root_id, @@ -340,6 +341,7 @@ def test_child_resource(): # this is hard to match against, so remove it child_resource["ResponseMetadata"].pop("HTTPHeaders", None) child_resource["ResponseMetadata"].pop("RetryAttempts", None) + child_resource["ResponseMetadata"].pop("RequestId") assert child_resource == { "path": "/users/tags", "pathPart": "tags", @@ -373,6 +375,7 @@ def test_create_method(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "httpMethod": "GET", "authorizationType": "none", @@ -407,6 +410,7 @@ def test_create_method_apikeyrequired(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "httpMethod": "GET", "authorizationType": "none", @@ -431,7 +435,7 @@ def test_create_method_response(): restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="none" ) - response = client.get_method(restApiId=api_id, resourceId=root_id, httpMethod="GET") + client.get_method(restApiId=api_id, resourceId=root_id, httpMethod="GET") response = client.put_method_response( restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200" @@ -439,6 +443,7 @@ def test_create_method_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "ResponseMetadata": {"HTTPStatusCode": 201}, "statusCode": "200", @@ -450,6 +455,7 @@ def test_create_method_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "ResponseMetadata": {"HTTPStatusCode": 200}, "statusCode": "200", @@ -461,6 +467,7 @@ def test_create_method_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == {"ResponseMetadata": {"HTTPStatusCode": 204}} @@ -540,6 +547,7 @@ def test_integrations(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "ResponseMetadata": {"HTTPStatusCode": 201}, "httpMethod": "POST", @@ -560,6 +568,7 @@ def test_integrations(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "ResponseMetadata": {"HTTPStatusCode": 200}, "httpMethod": "POST", @@ -578,6 +587,7 @@ def test_integrations(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response["resourceMethods"]["GET"]["httpMethod"] == "GET" assert response["resourceMethods"]["GET"]["authorizationType"] == "none" assert response["resourceMethods"]["GET"]["methodIntegration"] == { @@ -678,6 +688,7 @@ def test_integration_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "statusCode": "200", "selectionPattern": "foobar", @@ -695,6 +706,7 @@ def test_integration_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "statusCode": "200", "selectionPattern": "foobar", @@ -710,6 +722,7 @@ def test_integration_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response["methodIntegration"]["integrationResponses"] == { "200": { "responseTemplates": {}, # Note: TF compatibility @@ -760,6 +773,7 @@ def test_integration_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "statusCode": "200", "selectionPattern": "foobar", @@ -774,6 +788,7 @@ def test_integration_response(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "statusCode": "200", "selectionPattern": "foobar", @@ -810,6 +825,7 @@ def test_update_authorizer_configuration(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "id": authorizer_id, "name": authorizer_name, @@ -903,6 +919,7 @@ def test_create_authorizer(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "id": authorizer_id, "name": authorizer_name, @@ -928,6 +945,7 @@ def test_create_authorizer(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response["items"][0]["id"] in [authorizer_id, authorizer_id2] assert response["items"][1]["id"] in [authorizer_id, authorizer_id2] @@ -945,6 +963,7 @@ def test_create_authorizer(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "name": new_authorizer_name_with_vars, @@ -992,6 +1011,7 @@ def test_delete_authorizer(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "id": authorizer_id, "name": authorizer_name, @@ -1069,6 +1089,7 @@ def test_put_integration_response_with_response_template(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "statusCode": "200", "selectionPattern": "foobar", diff --git a/tests/test_awslambda/test_lambda.py b/tests/test_awslambda/test_lambda.py index 21b6345f7..5476728fd 100644 --- a/tests/test_awslambda/test_lambda.py +++ b/tests/test_awslambda/test_lambda.py @@ -187,6 +187,7 @@ def test_create_function_from_zipfile(): result["ResponseMetadata"].pop("HTTPHeaders", None) # Botocore inserts retry attempts not seen in Python27 result["ResponseMetadata"].pop("RetryAttempts", None) + result["ResponseMetadata"].pop("RequestId") result.pop("LastModified") assert result == { @@ -800,6 +801,7 @@ def test_delete_function(): success_result["ResponseMetadata"].pop("HTTPHeaders", None) # Botocore inserts retry attempts not seen in Python27 success_result["ResponseMetadata"].pop("RetryAttempts", None) + success_result["ResponseMetadata"].pop("RequestId") assert success_result == {"ResponseMetadata": {"HTTPStatusCode": 204}} @@ -1028,6 +1030,7 @@ def test_list_create_list_get_delete_list(): func["ResponseMetadata"].pop("HTTPHeaders", None) # Botocore inserts retry attempts not seen in Python27 func["ResponseMetadata"].pop("RetryAttempts", None) + func["ResponseMetadata"].pop("RequestId") func["Configuration"].pop("LastModified") func["Configuration"].pop("FunctionArn") diff --git a/tests/test_cognitoidp/test_cognitoidp.py b/tests/test_cognitoidp/test_cognitoidp.py index 31fc3842a..45456b770 100644 --- a/tests/test_cognitoidp/test_cognitoidp.py +++ b/tests/test_cognitoidp/test_cognitoidp.py @@ -36,6 +36,8 @@ def test_create_user_pool(): assert result["UserPool"]["Name"] == name assert result["UserPool"]["LambdaConfig"]["PreSignUp"] == value + assert "RequestId" in result["ResponseMetadata"] + @mock_aws def test_create_user_pool__overwrite_template_messages(): diff --git a/tests/test_config/test_config.py b/tests/test_config/test_config.py index ad738b966..8b86e10a4 100644 --- a/tests/test_config/test_config.py +++ b/tests/test_config/test_config.py @@ -1985,6 +1985,7 @@ def test_put_evaluations(): # this is hard to match against, so remove it response["ResponseMetadata"].pop("HTTPHeaders", None) response["ResponseMetadata"].pop("RetryAttempts", None) + response["ResponseMetadata"].pop("RequestId") assert response == { "FailedEvaluations": [], "ResponseMetadata": {"HTTPStatusCode": 200}, diff --git a/tests/test_moto_api/seeder/test_seeder.py b/tests/test_moto_api/seeder/test_seeder.py index e11c4b5c2..250da2826 100644 --- a/tests/test_moto_api/seeder/test_seeder.py +++ b/tests/test_moto_api/seeder/test_seeder.py @@ -41,7 +41,7 @@ class TestDifferentAccountsDoesNotBreakSeeding: instances = self.ec2_client.run_instances(MaxCount=1, MinCount=1)["Instances"] instance_ids = [instance["InstanceId"] for instance in instances] - assert instance_ids == ["i-dc50244d2b9e8e0b7"] + assert instance_ids == ["i-0df6e943394d7fdb0"] def test_1(self) -> None: # Create some data in a different account (111111111111)