Skip to content

Commit

Permalink
refactor: validate encryption context values
Browse files Browse the repository at this point in the history
  • Loading branch information
heitorlessa committed Dec 19, 2023
1 parent 8519896 commit 7be9566
Showing 1 changed file with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@
LocalCryptoMaterialsCache,
StrictAwsKmsMasterKeyProvider,
)
from aws_encryption_sdk.exceptions import DecryptKeyError, GenerateKeyError, NotSupportedError
from aws_encryption_sdk.exceptions import (
DecryptKeyError,
GenerateKeyError,
NotSupportedError,
)

from aws_lambda_powertools.shared.user_agent import register_feature_to_botocore_session
from aws_lambda_powertools.utilities._data_masking.constants import (
Expand All @@ -28,6 +32,7 @@
DataMaskingDecryptKeyError,
DataMaskingDecryptValueError,
DataMaskingEncryptKeyError,
DataMaskingUnsupportedTypeError,
)
from aws_lambda_powertools.utilities._data_masking.provider import BaseProvider

Expand Down Expand Up @@ -144,8 +149,9 @@ def encrypt(self, data: Any, provider_options: dict | None = None, **encryption_
The encrypted data, as a base64-encoded string.
"""
provider_options = provider_options or {}
data_encoded = self.json_serializer(data).encode("utf-8")
self._validate_encryption_context(encryption_context)

data_encoded = self.json_serializer(data).encode("utf-8")
try:
ciphertext, _ = self.client.encrypt(
source=data_encoded,
Expand Down Expand Up @@ -177,6 +183,7 @@ def decrypt(self, data: str, provider_options: dict | None = None, **encryption_
The decrypted data in bytes
"""
provider_options = provider_options or {}
self._validate_encryption_context(encryption_context)

try:
ciphertext_decoded = base64.b64decode(data)
Expand Down Expand Up @@ -208,3 +215,14 @@ def decrypt(self, data: str, provider_options: dict | None = None, **encryption_

ciphertext = self.json_deserializer(ciphertext.decode("utf-8"))
return ciphertext

@staticmethod
def _validate_encryption_context(context: dict):
if not context:
return

for key, value in context.items():
if not isinstance(value, str):
raise DataMaskingUnsupportedTypeError(
f"Encryption context values must be string. Received: {key}={value}",
)

0 comments on commit 7be9566

Please sign in to comment.