AWSLambda - refactor exception handling

This commit is contained in:
Bert Blommers 2019-11-17 10:59:20 +00:00
commit c6dd3c96ea
4 changed files with 56 additions and 42 deletions

View file

@ -33,6 +33,11 @@ from moto.s3.models import s3_backend
from moto.logs.models import logs_backends
from moto.s3.exceptions import MissingBucket, MissingKey
from moto import settings
from .exceptions import (
CrossAccountNotAllowed,
InvalidRoleFormat,
InvalidParameterValueException,
)
from .utils import make_function_arn, make_function_ver_arn
from moto.sqs import sqs_backends
from moto.dynamodb2 import dynamodb_backends2
@ -215,9 +220,8 @@ class LambdaFunction(BaseModel):
key = s3_backend.get_key(self.code["S3Bucket"], self.code["S3Key"])
except MissingBucket:
if do_validate_s3():
raise ValueError(
"InvalidParameterValueException",
"Error occurred while GetObject. S3 Error Code: NoSuchBucket. S3 Error Message: The specified bucket does not exist",
raise InvalidParameterValueException(
"Error occurred while GetObject. S3 Error Code: NoSuchBucket. S3 Error Message: The specified bucket does not exist"
)
except MissingKey:
if do_validate_s3():
@ -669,28 +673,19 @@ class LambdaStorage(object):
:param fn: Function
:type fn: LambdaFunction
"""
pattern = r"arn:(aws[a-zA-Z-]*)?:iam::(\d{12}):role/?[a-zA-Z_0-9+=,.@\-_/]+"
valid_role = re.match(pattern, fn.role)
valid_role = re.match(InvalidRoleFormat.pattern, fn.role)
if valid_role:
account = valid_role.group(2)
if account != ACCOUNT_ID:
raise ValueError(
"AccessDeniedException", "Cross-account pass role is not allowed."
)
raise CrossAccountNotAllowed()
try:
iam_backend.get_role_by_arn(fn.role)
except IAMNotFoundException:
raise ValueError(
"InvalidParameterValueException",
"The role defined for the function cannot be assumed by Lambda.",
raise InvalidParameterValueException(
"The role defined for the function cannot be assumed by Lambda."
)
else:
raise ValueError(
"ValidationException",
"1 validation error detected: Value '{0}' at 'role' failed to satisfy constraint: Member must satisfy regular expression pattern: {1}".format(
fn.role, pattern
),
)
raise InvalidRoleFormat(fn.role)
if fn.function_name in self._functions:
self._functions[fn.function_name]["latest"] = fn
else: