1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
|
"""Handles incoming appsync requests, invokes methods, returns responses."""
import json
import re
from typing import Any
from urllib.parse import unquote
from uuid import uuid4
from moto.core.common_types import TYPE_RESPONSE
from moto.core.responses import BaseResponse
from moto.core.utils import unix_time
from .exceptions import ApiKeyValidityOutOfBoundsException, AWSValidationException
from .models import AppSyncBackend, appsync_backends
class AppSyncResponse(BaseResponse):
"""Handler for AppSync requests and responses."""
def __init__(self) -> None:
super().__init__(service_name="appsync")
@staticmethod
def dns_event_response(request: Any, url: str, headers: Any) -> TYPE_RESPONSE: # type: ignore[misc]
data = json.loads(request.data.decode("utf-8"))
response: dict[str, list[Any]] = {"failed": [], "successful": []}
for idx in range(len(data.get("events", []))):
response["successful"].append({"identifier": str(uuid4()), "index": idx})
return 200, {}, json.dumps(response).encode("utf-8")
@property
def appsync_backend(self) -> AppSyncBackend:
"""Return backend instance specific for this region."""
return appsync_backends[self.current_account][self.region]
def create_graphql_api(self) -> str:
params = json.loads(self.body)
name = params.get("name")
log_config = params.get("logConfig")
authentication_type = params.get("authenticationType")
user_pool_config = params.get("userPoolConfig")
open_id_connect_config = params.get("openIDConnectConfig")
tags = params.get("tags")
additional_authentication_providers = params.get(
"additionalAuthenticationProviders"
)
xray_enabled = params.get("xrayEnabled", False)
lambda_authorizer_config = params.get("lambdaAuthorizerConfig")
visibility = params.get("visibility")
graphql_api = self.appsync_backend.create_graphql_api(
name=name,
log_config=log_config,
authentication_type=authentication_type,
user_pool_config=user_pool_config,
open_id_connect_config=open_id_connect_config,
additional_authentication_providers=additional_authentication_providers,
xray_enabled=xray_enabled,
lambda_authorizer_config=lambda_authorizer_config,
tags=tags,
visibility=visibility,
)
response = graphql_api.to_json()
response["tags"] = self.appsync_backend.list_tags_for_resource(graphql_api.arn)
return json.dumps({"graphqlApi": response})
def get_graphql_api(self) -> str:
api_id = self.path.split("/")[-1]
graphql_api = self.appsync_backend.get_graphql_api(api_id=api_id)
response = graphql_api.to_json()
response["tags"] = self.appsync_backend.list_tags_for_resource(graphql_api.arn)
return json.dumps({"graphqlApi": response})
def delete_graphql_api(self) -> str:
api_id = self.path.split("/")[-1]
self.appsync_backend.delete_graphql_api(api_id=api_id)
return "{}"
def update_graphql_api(self) -> str:
api_id = self.path.split("/")[-1]
params = json.loads(self.body)
name = params.get("name")
log_config = params.get("logConfig")
authentication_type = params.get("authenticationType")
user_pool_config = params.get("userPoolConfig")
open_id_connect_config = params.get("openIDConnectConfig")
additional_authentication_providers = params.get(
"additionalAuthenticationProviders"
)
xray_enabled = params.get("xrayEnabled", False)
lambda_authorizer_config = params.get("lambdaAuthorizerConfig")
api = self.appsync_backend.update_graphql_api(
api_id=api_id,
name=name,
log_config=log_config,
authentication_type=authentication_type,
user_pool_config=user_pool_config,
open_id_connect_config=open_id_connect_config,
additional_authentication_providers=additional_authentication_providers,
xray_enabled=xray_enabled,
lambda_authorizer_config=lambda_authorizer_config,
)
return json.dumps({"graphqlApi": api.to_json()})
def list_graphql_apis(self) -> str:
graphql_apis = self.appsync_backend.list_graphql_apis()
return json.dumps({"graphqlApis": [api.to_json() for api in graphql_apis]})
def create_api_key(self) -> str:
params = json.loads(self.body)
# /v1/apis/[api_id]/apikeys
api_id = self.path.split("/")[-2]
description = params.get("description")
expires = params.get("expires")
if expires:
current_time = int(unix_time())
min_validity = current_time + 86400 # 1 day in seconds
if expires < min_validity:
raise ApiKeyValidityOutOfBoundsException(
"API key must be valid for a minimum of 1 days."
)
api_key = self.appsync_backend.create_api_key(
api_id=api_id, description=description, expires=expires
)
return json.dumps({"apiKey": api_key.to_json()})
def delete_api_key(self) -> str:
api_id = self.path.split("/")[-3]
api_key_id = self.path.split("/")[-1]
self.appsync_backend.delete_api_key(api_id=api_id, api_key_id=api_key_id)
return "{}"
def list_api_keys(self) -> str:
# /v1/apis/[api_id]/apikeys
api_id = self.path.split("/")[-2]
api_keys = self.appsync_backend.list_api_keys(api_id=api_id)
return json.dumps({"apiKeys": [key.to_json() for key in api_keys]})
def update_api_key(self) -> str:
api_id = self.path.split("/")[-3]
api_key_id = self.path.split("/")[-1]
params = json.loads(self.body)
description = params.get("description")
expires = params.get("expires")
# Validate that API key expires at least 1 day from now
if expires:
current_time = int(unix_time())
min_validity = current_time + 86400 # 1 day in seconds
if expires < min_validity:
raise ApiKeyValidityOutOfBoundsException(
"API key must be valid for a minimum of 1 days."
)
api_key = self.appsync_backend.update_api_key(
api_id=api_id,
api_key_id=api_key_id,
description=description,
expires=expires,
)
return json.dumps({"apiKey": api_key.to_json()})
def start_schema_creation(self) -> str:
params = json.loads(self.body)
api_id = self.path.split("/")[-2]
definition = params.get("definition")
status = self.appsync_backend.start_schema_creation(
api_id=api_id, definition=definition
)
return json.dumps({"status": status})
def get_schema_creation_status(self) -> str:
api_id = self.path.split("/")[-2]
status, details = self.appsync_backend.get_schema_creation_status(api_id=api_id)
return json.dumps({"status": status, "details": details})
def tag_resource(self) -> str:
resource_arn = self._extract_arn_from_path()
params = json.loads(self.body)
tags = params.get("tags")
self.appsync_backend.tag_resource(resource_arn=resource_arn, tags=tags)
return "{}"
def untag_resource(self) -> str:
resource_arn = self._extract_arn_from_path()
tag_keys = self.querystring.get("tagKeys", [])
self.appsync_backend.untag_resource(
resource_arn=resource_arn, tag_keys=tag_keys
)
return "{}"
def list_tags_for_resource(self) -> str:
resource_arn = self._extract_arn_from_path()
tags = self.appsync_backend.list_tags_for_resource(resource_arn=resource_arn)
return json.dumps({"tags": tags})
def _extract_arn_from_path(self) -> str:
# /v1/tags/arn_that_may_contain_a_slash
path = unquote(self.path)
return "/".join(path.split("/")[3:])
def get_type(self) -> str:
api_id = unquote(self.path.split("/")[-3])
type_name = self.path.split("/")[-1]
type_format = self.querystring.get("format")[0] # type: ignore[index]
graphql_type = self.appsync_backend.get_type(
api_id=api_id, type_name=type_name, type_format=type_format
)
return json.dumps({"type": graphql_type})
def get_introspection_schema(self) -> str:
api_id = self.path.split("/")[-2]
format_ = self.querystring.get("format")[0] # type: ignore[index]
if self.querystring.get("includeDirectives"):
include_directives = (
self.querystring.get("includeDirectives")[0].lower() == "true" # type: ignore[index]
)
else:
include_directives = True
graphql_schema = self.appsync_backend.get_graphql_schema(api_id=api_id)
schema = graphql_schema.get_introspection_schema(
format_=format_, include_directives=include_directives
)
return schema
def get_api_cache(self) -> str:
api_id = self.path.split("/")[-2]
api_cache = self.appsync_backend.get_api_cache(
api_id=api_id,
)
return json.dumps({"apiCache": api_cache.to_json()})
def delete_api_cache(self) -> str:
api_id = self.path.split("/")[-2]
self.appsync_backend.delete_api_cache(
api_id=api_id,
)
return "{}"
def create_api_cache(self) -> str:
params = json.loads(self.body)
api_id = self.path.split("/")[-2]
ttl = params.get("ttl")
transit_encryption_enabled = params.get("transitEncryptionEnabled")
at_rest_encryption_enabled = params.get("atRestEncryptionEnabled")
api_caching_behavior = params.get("apiCachingBehavior")
type = params.get("type")
health_metrics_config = params.get("healthMetricsConfig")
api_cache = self.appsync_backend.create_api_cache(
api_id=api_id,
ttl=ttl,
transit_encryption_enabled=transit_encryption_enabled,
at_rest_encryption_enabled=at_rest_encryption_enabled,
api_caching_behavior=api_caching_behavior,
type=type,
health_metrics_config=health_metrics_config,
)
return json.dumps({"apiCache": api_cache.to_json()})
def update_api_cache(self) -> str:
api_id = self.path.split("/")[-3]
params = json.loads(self.body)
ttl = params.get("ttl")
api_caching_behavior = params.get("apiCachingBehavior")
type = params.get("type")
health_metrics_config = params.get("healthMetricsConfig")
api_cache = self.appsync_backend.update_api_cache(
api_id=api_id,
ttl=ttl,
api_caching_behavior=api_caching_behavior,
type=type,
health_metrics_config=health_metrics_config,
)
return json.dumps({"apiCache": api_cache.to_json()})
def flush_api_cache(self) -> str:
api_id = self.path.split("/")[-2]
self.appsync_backend.flush_api_cache(
api_id=api_id,
)
return "{}"
def create_api(self) -> str:
params = json.loads(self.body)
name = params.get("name")
if name:
pattern = r"^[A-Za-z0-9_\-\ ]+$"
if not re.match(pattern, name):
raise AWSValidationException(
"1 validation error detected: "
"Value at 'name' failed to satisfy constraint: "
"Member must satisfy regular expression pattern: "
"[A-Za-z0-9_\\-\\ ]+"
)
owner_contact = params.get("ownerContact")
tags = params.get("tags", {})
event_config = params.get("eventConfig")
api = self.appsync_backend.create_api(
name=name,
owner_contact=owner_contact,
tags=tags,
event_config=event_config,
)
response = api.to_json()
return json.dumps({"api": response})
def list_apis(self) -> str:
apis = self.appsync_backend.list_apis()
return json.dumps({"apis": [api.to_json() for api in apis]})
def delete_api(self) -> str:
api_id = self.path.split("/")[-1]
self.appsync_backend.delete_api(api_id=api_id)
return "{}"
def create_channel_namespace(self) -> str:
params = json.loads(self.body)
api_id = self.path.split("/")[-2]
name = params.get("name")
if name:
pattern = r"^[A-Za-z0-9](?:[A-Za-z0-9\-]{0,48}[A-Za-z0-9])?$"
if not re.match(pattern, name):
raise AWSValidationException(
"1 validation error detected: "
"Value at 'name' failed to satisfy constraint: "
"Member must satisfy regular expression pattern: "
"([A-Za-z0-9](?:[A-Za-z0-9\\-]{0,48}[A-Za-z0-9])?)"
)
subscribe_auth_modes = params.get("subscribeAuthModes")
publish_auth_modes = params.get("publishAuthModes")
code_handlers = params.get("codeHandlers")
tags = params.get("tags", {})
handler_configs = params.get("handlerConfigs", {})
channel_namespace = self.appsync_backend.create_channel_namespace(
api_id=api_id,
name=name,
subscribe_auth_modes=subscribe_auth_modes,
publish_auth_modes=publish_auth_modes,
code_handlers=code_handlers,
tags=tags,
handler_configs=handler_configs,
)
return json.dumps({"channelNamespace": channel_namespace.to_json()})
def list_channel_namespaces(self) -> str:
api_id = self.path.split("/")[-2]
channel_namespaces = self.appsync_backend.list_channel_namespaces(api_id=api_id)
return json.dumps(
{
"channelNamespaces": [
channel_namespace.to_json()
for channel_namespace in channel_namespaces
]
}
)
def delete_channel_namespace(self) -> str:
path_parts = self.path.split("/")
api_id = path_parts[-3]
name = path_parts[-1]
self.appsync_backend.delete_channel_namespace(
api_id=api_id,
name=name,
)
return "{}"
def get_api(self) -> str:
api_id = self.path.split("/")[-1]
api = self.appsync_backend.get_api(api_id=api_id)
response = api.to_json()
response["tags"] = self.appsync_backend.list_tags_for_resource(api.api_arn)
return json.dumps({"api": response})
|