in samtranslator/model/api/api_generator.py [0:0]
def _add_cors(self) -> None:
"""
Add CORS configuration to the Swagger file, if necessary
"""
INVALID_ERROR = "Invalid value for 'Cors' property"
if not self.cors:
return
if self.cors and not self.definition_body:
raise InvalidResourceException(
self.logical_id, "Cors works only with inline Swagger specified in 'DefinitionBody' property."
)
if isinstance(self.cors, str) or is_intrinsic(self.cors):
# Just set Origin property. Others will be defaults
properties = CorsProperties(AllowOrigin=self.cors) # type: ignore[call-arg]
elif isinstance(self.cors, dict):
# Make sure keys in the dict are recognized
for key in self.cors:
if key not in CorsProperties._fields:
raise InvalidResourceException(self.logical_id, f"Invalid key '{key}' for 'Cors' property.")
properties = CorsProperties(**self.cors)
else:
raise InvalidResourceException(self.logical_id, INVALID_ERROR)
if not SwaggerEditor.is_valid(self.definition_body):
raise InvalidResourceException(
self.logical_id,
"Unable to add Cors configuration because "
"'DefinitionBody' does not contain a valid Swagger definition.",
)
if properties.AllowCredentials is True and properties.AllowOrigin == _CORS_WILDCARD:
raise InvalidResourceException(
self.logical_id,
"Unable to add Cors configuration because "
"'AllowCredentials' can not be true when "
"'AllowOrigin' is \"'*'\" or not set",
)
editor = SwaggerEditor(self.definition_body)
for path in editor.iter_on_path():
try:
editor.add_cors( # type: ignore[no-untyped-call]
path,
properties.AllowOrigin,
properties.AllowHeaders,
properties.AllowMethods,
max_age=properties.MaxAge,
allow_credentials=properties.AllowCredentials,
)
except InvalidTemplateException as ex:
raise InvalidResourceException(self.logical_id, ex.message) from ex
# Assign the Swagger back to template
self.definition_body = editor.swagger