diff --git a/aws_lambda_powertools/utilities/jmespath_utils/__init__.py b/aws_lambda_powertools/utilities/jmespath_utils/__init__.py index c35f9b610cf..e16db4a90c2 100644 --- a/aws_lambda_powertools/utilities/jmespath_utils/__init__.py +++ b/aws_lambda_powertools/utilities/jmespath_utils/__init__.py @@ -14,7 +14,7 @@ from typing import Any import jmespath -from jmespath.exceptions import LexerError +from jmespath.exceptions import ParseError from jmespath.functions import Functions, signature from typing_extensions import deprecated @@ -84,7 +84,7 @@ def handler(event: dict, context: LambdaContext): try: logger.debug(f"Envelope detected: {envelope}. JMESPath options: {jmespath_options}") return jmespath.search(envelope, data, options=jmespath.Options(**jmespath_options)) - except (LexerError, TypeError, UnicodeError) as e: + except (ParseError, TypeError, UnicodeError) as e: message = f"Failed to unwrap event from envelope using expression. Error: {e} Exp: {envelope}, Data: {data}" # noqa: B306, E501 raise InvalidEnvelopeExpressionError(message) diff --git a/tests/functional/validator/_fastjsonschema/test_validator.py b/tests/functional/validator/_fastjsonschema/test_validator.py index 0d86ea2fd29..2ee73506391 100644 --- a/tests/functional/validator/_fastjsonschema/test_validator.py +++ b/tests/functional/validator/_fastjsonschema/test_validator.py @@ -103,6 +103,25 @@ def test_validate_invalid_envelope_expression(schema, wrapped_event): validate(event=wrapped_event, schema=schema, envelope=True) +@pytest.mark.parametrize( + "envelope", + [ + "powertools_json(data", # incomplete expression + "powertools_json(data, data)", # wrong number of arguments + "data.", # trailing dot + 'powertools_json("data)', # unclosed quote + ], +) +def test_validate_malformed_envelope_raises_invalid_envelope_expression_error(schema, envelope): + # GIVEN an event and an envelope with a JMESPath syntax error + event = {"data": '{"message": "hello"}'} + + # WHEN validating + # THEN every syntax error is reported as InvalidEnvelopeExpressionError, not a raw jmespath exception + with pytest.raises(exceptions.InvalidEnvelopeExpressionError): + validate(event=event, schema=schema, envelope=envelope) + + def test_validate_invalid_event(schema): b64_event = "eyJtZXNzYWdlIjogImhlbGxvIGhlbGxvIiwgInVzZXJuYW1lIjogImJsYWggYmxhaCJ9=" with pytest.raises(exceptions.SchemaValidationError):