diff --git a/src/aws_encryption_sdk/internal/formatting/encryption_context.py b/src/aws_encryption_sdk/internal/formatting/encryption_context.py index 949ebe6f2..febf1f5fb 100644 --- a/src/aws_encryption_sdk/internal/formatting/encryption_context.py +++ b/src/aws_encryption_sdk/internal/formatting/encryption_context.py @@ -16,6 +16,14 @@ _LOGGER = logging.getLogger(__name__) +def _validate_encryption_context_entry(key, value): + max_entry_length = aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE + if len(key) > max_entry_length: + raise SerializationError("The encryption context contains a key that is too large.") + if len(value) > max_entry_length: + raise SerializationError("The encryption context contains a value that is too large.") + + def assemble_content_aad(message_id, aad_content_string, seq_num, length): """Assembles the Body AAD string for a message body structure. @@ -72,6 +80,7 @@ def serialize_encryption_context(encryption_context): ) for key, value in sorted(encryption_context_list, key=lambda x: x[0]): + _validate_encryption_context_entry(key, value) serialized_context.extend( struct.pack( ">H{key_size}sH{value_size}s".format(key_size=len(key), value_size=len(value)), diff --git a/test/unit/test_encryption_context.py b/test/unit/test_encryption_context.py index bd717fbd8..6871f0d71 100644 --- a/test/unit/test_encryption_context.py +++ b/test/unit/test_encryption_context.py @@ -64,6 +64,22 @@ def test_serialize_encryption_context_too_large(self): ) excinfo.match("The serialized context is too large") + def test_serialize_encryption_context_key_too_large(self): + oversized_key = "a" * (aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE + 1) + with pytest.raises(SerializationError) as excinfo: + aws_encryption_sdk.internal.formatting.encryption_context.serialize_encryption_context( + {oversized_key: "value"} + ) + excinfo.match("The encryption context contains a key that is too large.") + + def test_serialize_encryption_context_value_too_large(self): + oversized_value = "a" * (aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE + 1) + with pytest.raises(SerializationError) as excinfo: + aws_encryption_sdk.internal.formatting.encryption_context.serialize_encryption_context( + {"key": oversized_value} + ) + excinfo.match("The encryption context contains a value that is too large.") + def test_serialize_encryption_context_unencodable(self): """Validate that the serialize_encryption_context function behaves as expected when presented