diff --git a/src/aws_encryption_sdk/internal/formatting/encryption_context.py b/src/aws_encryption_sdk/internal/formatting/encryption_context.py index 949ebe6f2..83b5aaa19 100644 --- a/src/aws_encryption_sdk/internal/formatting/encryption_context.py +++ b/src/aws_encryption_sdk/internal/formatting/encryption_context.py @@ -71,7 +71,12 @@ def serialize_encryption_context(encryption_context): "Cannot encode dictionary key or value using {}.".format(aws_encryption_sdk.internal.defaults.ENCODING) ) + max_value_length = aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE for key, value in sorted(encryption_context_list, key=lambda x: x[0]): + if len(key) > max_value_length: + raise SerializationError("The encryption context contains a key that is too large.") + if len(value) > max_value_length: + raise SerializationError("The encryption context contains a value that is too large.") 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