Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

fix: fallback for no encryption key (#2968)

jnjpng631a27ee5211
diff --git a/letta/helpers/crypto_utils.py b/letta/helpers/crypto_utils.py
index 292e1a2fc..ce8abc725 100644
--- a/letta/helpers/crypto_utils.py
+++ b/letta/helpers/crypto_utils.py
@@ -132,3 +132,13 @@ class CryptoUtils:
return len(decoded) >= cls.SALT_SIZE + cls.IV_SIZE + cls.TAG_SIZE + 1
except Exception:
return False
+
+ @classmethod
+ def is_encryption_available(cls) -> bool:
+ """
+ Check if encryption is available (encryption key is configured).
+
+ Returns:
+ True if encryption key is configured, False otherwise
+ """
+ return bool(settings.encryption_key)
diff --git a/letta/schemas/secret.py b/letta/schemas/secret.py
index 6cba8249a..45059aef7 100644
--- a/letta/schemas/secret.py
+++ b/letta/schemas/secret.py
@@ -4,6 +4,9 @@ from typing import Any, Dict, Optional
from pydantic import BaseModel, ConfigDict, PrivateAttr
from letta.helpers.crypto_utils import CryptoUtils
+from letta.log import get_logger
+
+logger = get_logger(__name__)
class Secret(BaseModel):
@@ -32,13 +35,13 @@ class Secret(BaseModel):
@classmethod
def from_plaintext(cls, value: Optional[str]) -> "Secret":
"""
- Create a Secret from a plaintext value, encrypting it immediately.
+ Create a Secret from a plaintext value, encrypting it if possible.
Args:
value: The plaintext value to encrypt
Returns:
- A Secret instance with the encrypted value
+ A Secret instance with the encrypted value, or plaintext if encryption unavailable
"""
if value is None:
instance = cls()
@@ -46,11 +49,26 @@ class Secret(BaseModel):
instance._was_encrypted = False
return instance
- encrypted = CryptoUtils.encrypt(value)
- instance = cls()
- instance._encrypted_value = encrypted
- instance._was_encrypted = False
- return instance
+ # Try to encrypt, but fall back to plaintext if no encryption key
+ try:
+ encrypted = CryptoUtils.encrypt(value)
+ instance = cls()
+ instance._encrypted_value = encrypted
+ instance._was_encrypted = False
+ return instance
+ except ValueError as e:
+ # No encryption key available, store as plaintext
+ if "No encryption key configured" in str(e):
+ logger.warning(
+ "No encryption key configured. Storing Secret value as plaintext. "
+ "Set LETTA_ENCRYPTION_KEY environment variable to enable encryption."
+ )
+ instance = cls()
+ instance._encrypted_value = value # Store plaintext
+ instance._plaintext_cache = value # Cache it
+ instance._was_encrypted = False
+ return instance
+ raise # Re-raise if it's a different error
@classmethod
def from_encrypted(cls, encrypted_value: Optional[str]) -> "Secret":
@@ -111,9 +129,15 @@ class Secret(BaseModel):
if self._encrypted_value is None:
return None
- # Use cached value if available
+ # Use cached value if available, but only if it looks like plaintext
+ # or we're confident we can decrypt it
if self._plaintext_cache is not None:
- return self._plaintext_cache
+ # If we have a cache but the stored value looks encrypted and we have no key,
+ # we should not use the cache
+ if CryptoUtils.is_encrypted(self._encrypted_value) and not CryptoUtils.is_encryption_available():
+ self._plaintext_cache = None # Clear invalid cache
+ else:
+ return self._plaintext_cache
# Decrypt and cache
try:
@@ -121,11 +145,46 @@ class Secret(BaseModel):
# Cache the decrypted value (PrivateAttr fields can be mutated even with frozen=True)
self._plaintext_cache = plaintext
return plaintext
- except Exception:
- # If decryption fails and this wasn't originally encrypted,
- # it might be that the value is actually plaintext (during migration)
- if not self._was_encrypted:
+ except ValueError as e:
+ error_msg = str(e)
+
+ # Handle missing encryption key
+ if "No encryption key configured" in error_msg:
+ # Check if the value looks encrypted
+ if CryptoUtils.is_encrypted(self._encrypted_value):
+ # Value was encrypted, but now we have no key - can't decrypt
+ logger.warning(
+ "Cannot decrypt Secret value - no encryption key configured. "
+ "The value was encrypted and requires the original key to decrypt."
+ )
+ # Return None to indicate we can't get the plaintext
+ return None
+ else:
+ # Value is plaintext (stored when no key was available)
+ logger.debug("Secret value is plaintext (stored without encryption)")
+ self._plaintext_cache = self._encrypted_value
+ return self._encrypted_value
+
+ # Handle decryption failure (might be plaintext stored as such)
+ elif "Failed to decrypt data" in error_msg:
+ # Check if it might be plaintext
+ if not CryptoUtils.is_encrypted(self._encrypted_value):
+ # It's plaintext that was stored when no key was available
+ logger.debug("Secret value appears to be plaintext (stored without encryption)")
+ self._plaintext_cache = self._encrypted_value
+ return self._encrypted_value
+ # Otherwise, it's corrupted or wrong key
+ logger.error("Failed to decrypt Secret value - data may be corrupted or wrong key")
+ raise
+
+ # Migration case: handle legacy plaintext
+ elif not self._was_encrypted:
+ if self._encrypted_value and not CryptoUtils.is_encrypted(self._encrypted_value):
+ self._plaintext_cache = self._encrypted_value
+ return self._encrypted_value
return None
+
+ # Re-raise for other errors
raise
def is_empty(self) -> bool:
@@ -189,13 +248,27 @@ class SecretDict(BaseModel):
instance._was_encrypted = False
return instance
- # Serialize to JSON then encrypt
+ # Serialize to JSON then try to encrypt
json_str = json.dumps(value)
- encrypted = CryptoUtils.encrypt(json_str)
- instance = cls()
- instance._encrypted_value = encrypted
- instance._was_encrypted = False
- return instance
+ try:
+ encrypted = CryptoUtils.encrypt(json_str)
+ instance = cls()
+ instance._encrypted_value = encrypted
+ instance._was_encrypted = False
+ return instance
+ except ValueError as e:
+ # No encryption key available, store as plaintext JSON
+ if "No encryption key configured" in str(e):
+ logger.warning(
+ "No encryption key configured. Storing SecretDict value as plaintext JSON. "
+ "Set LETTA_ENCRYPTION_KEY environment variable to enable encryption."
+ )
+ instance = cls()
+ instance._encrypted_value = json_str # Store JSON string
+ instance._plaintext_cache = value # Cache the dict
+ instance._was_encrypted = False
+ return instance
+ raise # Re-raise if it's a different error
@classmethod
def from_encrypted(cls, encrypted_value: Optional[str]) -> "SecretDict":
@@ -224,9 +297,15 @@ class SecretDict(BaseModel):
if self._encrypted_value is None:
return None
- # Use cached value if available
+ # Use cached value if available, but only if it looks like plaintext
+ # or we're confident we can decrypt it
if self._plaintext_cache is not None:
- return self._plaintext_cache
+ # If we have a cache but the stored value looks encrypted and we have no key,
+ # we should not use the cache
+ if CryptoUtils.is_encrypted(self._encrypted_value) and not CryptoUtils.is_encryption_available():
+ self._plaintext_cache = None # Clear invalid cache
+ else:
+ return self._plaintext_cache
try:
decrypted_json = CryptoUtils.decrypt(self._encrypted_value)
@@ -234,9 +313,60 @@ class SecretDict(BaseModel):
# Cache the decrypted value (PrivateAttr fields can be mutated even with frozen=True)
self._plaintext_cache = plaintext_dict
return plaintext_dict
- except Exception:
- if not self._was_encrypted:
+ except ValueError as e:
+ error_msg = str(e)
+
+ # Handle missing encryption key
+ if "No encryption key configured" in error_msg:
+ # Check if the value looks encrypted
+ if CryptoUtils.is_encrypted(self._encrypted_value):
+ # Value was encrypted, but now we have no key - can't decrypt
+ logger.warning(
+ "Cannot decrypt SecretDict value - no encryption key configured. "
+ "The value was encrypted and requires the original key to decrypt."
+ )
+ # Return None to indicate we can't get the plaintext
+ return None
+ else:
+ # Value is plaintext JSON (stored when no key was available)
+ logger.debug("SecretDict value is plaintext JSON (stored without encryption)")
+ try:
+ plaintext_dict = json.loads(self._encrypted_value)
+ self._plaintext_cache = plaintext_dict
+ return plaintext_dict
+ except json.JSONDecodeError:
+ logger.error("Failed to parse SecretDict plaintext as JSON")
+ return None
+
+ # Handle decryption failure (might be plaintext JSON)
+ elif "Failed to decrypt data" in error_msg:
+ # Check if it might be plaintext JSON
+ if not CryptoUtils.is_encrypted(self._encrypted_value):
+ # It's plaintext JSON that was stored when no key was available
+ logger.debug("SecretDict value appears to be plaintext JSON (stored without encryption)")
+ try:
+ plaintext_dict = json.loads(self._encrypted_value)
+ self._plaintext_cache = plaintext_dict
+ return plaintext_dict
+ except json.JSONDecodeError:
+ logger.error("Failed to parse SecretDict plaintext as JSON")
+ return None
+ # Otherwise, it's corrupted or wrong key
+ logger.error("Failed to decrypt SecretDict value - data may be corrupted or wrong key")
+ raise
+
+ # Migration case: handle legacy plaintext
+ elif not self._was_encrypted:
+ if self._encrypted_value:
+ try:
+ plaintext_dict = json.loads(self._encrypted_value)
+ self._plaintext_cache = plaintext_dict
+ return plaintext_dict
+ except json.JSONDecodeError:
+ pass
return None
+
+ # Re-raise for other errors
raise
def is_empty(self) -> bool:
diff --git a/tests/test_crypto_utils.py b/tests/test_crypto_utils.py
index 0922ce84b..602c484b1 100644
--- a/tests/test_crypto_utils.py
+++ b/tests/test_crypto_utils.py
@@ -148,6 +148,9 @@ class TestCryptoUtils:
try:
with pytest.raises(ValueError, match="No encryption key configured"):
CryptoUtils.encrypt("test data")
+
+ with pytest.raises(ValueError, match="No encryption key configured"):
+ CryptoUtils.decrypt("test data")
finally:
# Restore original key
settings.encryption_key = original_key
diff --git a/tests/test_secret.py b/tests/test_secret.py
index 595339182..24cdce002 100644
--- a/tests/test_secret.py
+++ b/tests/test_secret.py
@@ -36,7 +36,7 @@ class TestSecret:
settings.encryption_key = original_key
def test_from_plaintext_without_key(self):
- """Test creating a Secret from plaintext without encryption key."""
+ """Test creating a Secret from plaintext without encryption key (fallback behavior)."""
from letta.settings import settings
# Clear encryption key
@@ -46,9 +46,13 @@ class TestSecret:
try:
plaintext = "my-plaintext-value"
- # Should raise error when trying to encrypt without key
- with pytest.raises(ValueError):
- Secret.from_plaintext(plaintext)
+ # Should now handle gracefully and store as plaintext
+ secret = Secret.from_plaintext(plaintext)
+
+ # Should store the plaintext value
+ assert secret._encrypted_value == plaintext
+ assert secret.get_plaintext() == plaintext
+ assert not secret._was_encrypted
finally:
settings.encryption_key = original_key
@@ -495,3 +499,133 @@ class TestSecretDict:
# Second call should also return None (not trying to decrypt)
result2 = secret_dict.get_plaintext()
assert result2 is None
+
+ def test_from_plaintext_dict_without_key(self):
+ """Test creating a SecretDict from plaintext dictionary without encryption key (fallback)."""
+ from letta.settings import settings
+
+ original_key = settings.encryption_key
+ settings.encryption_key = None
+
+ try:
+ plaintext_dict = {"key1": "value1", "key2": "value2"}
+
+ # Should handle gracefully and store as JSON plaintext
+ secret_dict = SecretDict.from_plaintext(plaintext_dict)
+
+ # Should store the JSON string
+ assert secret_dict._encrypted_value == json.dumps(plaintext_dict)
+ assert secret_dict.get_plaintext() == plaintext_dict
+ assert not secret_dict._was_encrypted
+ finally:
+ settings.encryption_key = original_key
+
+ def test_encryption_key_transition_no_key_to_has_key(self):
+ """Test transition from no encryption key to having one."""
+ from letta.settings import settings
+
+ original_key = settings.encryption_key
+
+ try:
+ # Start with no encryption key
+ settings.encryption_key = None
+
+ # Create secrets without encryption
+ plaintext = "test-value-123"
+ secret = Secret.from_plaintext(plaintext)
+
+ plaintext_dict = {"api_key": "sk-12345", "api_secret": "secret"}
+ secret_dict = SecretDict.from_plaintext(plaintext_dict)
+
+ # Verify they're stored as plaintext
+ assert secret._encrypted_value == plaintext
+ assert secret_dict._encrypted_value == json.dumps(plaintext_dict)
+
+ # Now add an encryption key
+ settings.encryption_key = self.MOCK_KEY
+
+ # Should still be able to read the plaintext values
+ assert secret.get_plaintext() == plaintext
+ assert secret_dict.get_plaintext() == plaintext_dict
+
+ # Create new secrets with encryption enabled
+ new_secret = Secret.from_plaintext("new-encrypted-value")
+ assert new_secret._encrypted_value != "new-encrypted-value" # Should be encrypted
+
+ finally:
+ settings.encryption_key = original_key
+
+ def test_encryption_key_transition_has_key_to_no_key(self):
+ """Test transition from having encryption key to not having one."""
+ from letta.settings import settings
+
+ original_key = settings.encryption_key
+
+ try:
+ # Start with encryption key
+ settings.encryption_key = self.MOCK_KEY
+
+ # Create secrets with encryption
+ plaintext = "encrypted-test-value"
+ secret = Secret.from_plaintext(plaintext)
+
+ plaintext_dict = {"token": "bearer-xyz", "key": "value"}
+ secret_dict = SecretDict.from_plaintext(plaintext_dict)
+
+ # Verify they're encrypted
+ assert secret._encrypted_value != plaintext
+ assert secret_dict._encrypted_value != json.dumps(plaintext_dict)
+
+ # Remove encryption key
+ settings.encryption_key = None
+
+ # Should handle gracefully - return None for encrypted values
+ # (can't decrypt without key)
+ result = secret.get_plaintext()
+ assert result is None # Can't decrypt without key
+
+ dict_result = secret_dict.get_plaintext()
+ assert dict_result is None # Can't decrypt without key
+
+ finally:
+ settings.encryption_key = original_key
+
+ def test_round_trip_compatibility(self):
+ """Test that values can be read correctly regardless of when they were stored."""
+ from letta.settings import settings
+
+ original_key = settings.encryption_key
+
+ try:
+ # Create some values without encryption
+ settings.encryption_key = None
+ unencrypted_secret = Secret.from_plaintext("unencrypted")
+ unencrypted_dict = SecretDict.from_plaintext({"plain": "text"})
+
+ # Create some values with encryption
+ settings.encryption_key = self.MOCK_KEY
+ encrypted_secret = Secret.from_plaintext("encrypted")
+ encrypted_dict = SecretDict.from_plaintext({"secure": "data"})
+
+ # Mix them - can read unencrypted with key present
+ assert unencrypted_secret.get_plaintext() == "unencrypted"
+ assert unencrypted_dict.get_plaintext() == {"plain": "text"}
+ assert encrypted_secret.get_plaintext() == "encrypted"
+ assert encrypted_dict.get_plaintext() == {"secure": "data"}
+
+ # Remove key - can only read unencrypted
+ settings.encryption_key = None
+ assert unencrypted_secret.get_plaintext() == "unencrypted"
+ assert unencrypted_dict.get_plaintext() == {"plain": "text"}
+ assert encrypted_secret.get_plaintext() is None # Can't decrypt
+ assert encrypted_dict.get_plaintext() is None # Can't decrypt
+
+ # Restore key - can read all again
+ settings.encryption_key = self.MOCK_KEY
+ assert unencrypted_secret.get_plaintext() == "unencrypted"
+ assert unencrypted_dict.get_plaintext() == {"plain": "text"}
+ assert encrypted_secret.get_plaintext() == "encrypted"
+ assert encrypted_dict.get_plaintext() == {"secure": "data"}
+
+ finally:
+ settings.encryption_key = original_key