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: run PBKDF2 in thread pool to prevent event loop freeze (#6763)

Kian Jonesbce1749408e3
diff --git a/letta/helpers/crypto_utils.py b/letta/helpers/crypto_utils.py
index 629d6a800..6cbdc5e70 100644
--- a/letta/helpers/crypto_utils.py
+++ b/letta/helpers/crypto_utils.py
@@ -1,5 +1,7 @@
+import asyncio
import base64
import os
+from functools import lru_cache
from typing import Optional
from cryptography.hazmat.backends import default_backend
@@ -45,15 +47,43 @@ class CryptoUtils:
SALT_SIZE = 16
@classmethod
- def _derive_key(cls, master_key: str, salt: bytes) -> bytes:
- """Derive an AES key from the master key using PBKDF2."""
+ @lru_cache(maxsize=256)
+ def _derive_key_cached(cls, master_key: str, salt: bytes) -> bytes:
+ """
+ Derive an AES key from the master key using PBKDF2 with caching.
+
+ This is a CPU-intensive operation (100k iterations of PBKDF2-HMAC-SHA256)
+ that can take 100-500ms. Results are cached since key derivation is deterministic.
+
+ WARNING: This is a synchronous blocking operation. Use _derive_key_async()
+ in async contexts to avoid blocking the event loop.
+ """
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=cls.KEY_SIZE, salt=salt, iterations=100000, backend=default_backend())
return kdf.derive(master_key.encode())
+ @classmethod
+ def _derive_key(cls, master_key: str, salt: bytes) -> bytes:
+ """Derive an AES key from the master key using PBKDF2 (cached)."""
+ return cls._derive_key_cached(master_key, salt)
+
+ @classmethod
+ async def _derive_key_async(cls, master_key: str, salt: bytes) -> bytes:
+ """
+ Async version of _derive_key that runs PBKDF2 in a thread pool.
+
+ This prevents PBKDF2 (a CPU-intensive operation) from blocking the event loop.
+ PBKDF2 with 100k iterations typically takes 100-500ms, which would freeze
+ the event loop and prevent all other requests from being processed.
+ """
+ return await asyncio.to_thread(cls._derive_key, master_key, salt)
+
@classmethod
def encrypt(cls, plaintext: str, master_key: Optional[str] = None) -> str:
"""
- Encrypt a string using AES-256-GCM.
+ Encrypt a string using AES-256-GCM (synchronous version).
+
+ WARNING: This performs CPU-intensive PBKDF2 key derivation that can block for 100-500ms.
+ Use encrypt_async() in async contexts to avoid blocking the event loop.
Args:
plaintext: The string to encrypt
@@ -77,7 +107,7 @@ class CryptoUtils:
salt = os.urandom(cls.SALT_SIZE)
iv = os.urandom(cls.IV_SIZE)
- # Derive key from master key
+ # Derive key from master key (CPU-intensive, but cached)
key = cls._derive_key(master_key, salt)
# Create cipher
@@ -96,10 +126,62 @@ class CryptoUtils:
# Return as base64 encoded string
return base64.b64encode(encrypted_data).decode("utf-8")
+ @classmethod
+ async def encrypt_async(cls, plaintext: str, master_key: Optional[str] = None) -> str:
+ """
+ Encrypt a string using AES-256-GCM (async version).
+
+ Runs the CPU-intensive PBKDF2 key derivation in a thread pool to avoid
+ blocking the event loop.
+
+ Args:
+ plaintext: The string to encrypt
+ master_key: Optional master key (defaults to settings.encryption_key)
+
+ Returns:
+ Base64 encoded string containing: salt + iv + ciphertext + tag
+
+ Raises:
+ ValueError: If no encryption key is configured
+ """
+ if master_key is None:
+ master_key = settings.encryption_key
+
+ if not master_key:
+ raise ValueError(
+ "No encryption key configured. Please set the LETTA_ENCRYPTION_KEY environment variable (not fully supported yet for Letta v0.12.1 and below)."
+ )
+
+ # Generate random salt and IV
+ salt = os.urandom(cls.SALT_SIZE)
+ iv = os.urandom(cls.IV_SIZE)
+
+ # Derive key from master key (async to avoid blocking)
+ key = await cls._derive_key_async(master_key, salt)
+
+ # Create cipher
+ cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
+ encryptor = cipher.encryptor()
+
+ # Encrypt the plaintext
+ ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize()
+
+ # Get the authentication tag
+ tag = encryptor.tag
+
+ # Combine salt + iv + ciphertext + tag
+ encrypted_data = salt + iv + ciphertext + tag
+
+ # Return as base64 encoded string
+ return base64.b64encode(encrypted_data).decode("utf-8")
+
@classmethod
def decrypt(cls, encrypted: str, master_key: Optional[str] = None) -> str:
"""
- Decrypt a string that was encrypted using AES-256-GCM.
+ Decrypt a string that was encrypted using AES-256-GCM (synchronous version).
+
+ WARNING: This performs CPU-intensive PBKDF2 key derivation that can block for 100-500ms.
+ Use decrypt_async() in async contexts to avoid blocking the event loop.
Args:
encrypted: Base64 encoded encrypted string
@@ -129,7 +211,7 @@ class CryptoUtils:
ciphertext = encrypted_data[cls.SALT_SIZE + cls.IV_SIZE : -cls.TAG_SIZE]
tag = encrypted_data[-cls.TAG_SIZE :]
- # Derive key from master key
+ # Derive key from master key (CPU-intensive, but cached)
key = cls._derive_key(master_key, salt)
# Create cipher
@@ -144,6 +226,57 @@ class CryptoUtils:
except Exception as e:
raise ValueError(f"Failed to decrypt data: {str(e)}")
+ @classmethod
+ async def decrypt_async(cls, encrypted: str, master_key: Optional[str] = None) -> str:
+ """
+ Decrypt a string that was encrypted using AES-256-GCM (async version).
+
+ Runs the CPU-intensive PBKDF2 key derivation in a thread pool to avoid
+ blocking the event loop.
+
+ Args:
+ encrypted: Base64 encoded encrypted string
+ master_key: Optional master key (defaults to settings.encryption_key)
+
+ Returns:
+ The decrypted plaintext string
+
+ Raises:
+ ValueError: If no encryption key is configured or decryption fails
+ """
+ if master_key is None:
+ master_key = settings.encryption_key
+
+ if not master_key:
+ raise ValueError(
+ "No encryption key configured. Please set the LETTA_ENCRYPTION_KEY environment variable (not fully supported yet for Letta v0.12.1 and below)."
+ )
+
+ try:
+ # Decode from base64
+ encrypted_data = base64.b64decode(encrypted)
+
+ # Extract components
+ salt = encrypted_data[: cls.SALT_SIZE]
+ iv = encrypted_data[cls.SALT_SIZE : cls.SALT_SIZE + cls.IV_SIZE]
+ ciphertext = encrypted_data[cls.SALT_SIZE + cls.IV_SIZE : -cls.TAG_SIZE]
+ tag = encrypted_data[-cls.TAG_SIZE :]
+
+ # Derive key from master key (async to avoid blocking)
+ key = await cls._derive_key_async(master_key, salt)
+
+ # Create cipher
+ cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend())
+ decryptor = cipher.decryptor()
+
+ # Decrypt the ciphertext
+ plaintext = decryptor.update(ciphertext) + decryptor.finalize()
+
+ return plaintext.decode("utf-8")
+
+ except Exception as e:
+ raise ValueError(f"Failed to decrypt data: {str(e)}")
+
@classmethod
def is_encrypted(cls, value: str) -> bool:
"""
diff --git a/letta/orm/agent.py b/letta/orm/agent.py
index 8ff2dab67..2980d6388 100644
--- a/letta/orm/agent.py
+++ b/letta/orm/agent.py
@@ -16,6 +16,7 @@ from letta.orm.sqlalchemy_base import SqlalchemyBase
from letta.schemas.agent import AgentState as PydanticAgentState
from letta.schemas.embedding_config import EmbeddingConfig
from letta.schemas.enums import AgentType
+from letta.schemas.environment_variables import AgentEnvironmentVariable as PydanticAgentEnvVar
from letta.schemas.letta_stop_reason import StopReasonType
from letta.schemas.llm_config import LLMConfig
from letta.schemas.memory import Memory
@@ -432,8 +433,10 @@ class Agent(SqlalchemyBase, OrganizationMixin, ProjectMixin, TemplateEntityMixin
state["identities"] = [i.to_pydantic() for i in identities]
state["multi_agent_group"] = multi_agent_group
state["managed_group"] = multi_agent_group
- state["tool_exec_environment_variables"] = tool_exec_environment_variables
- state["secrets"] = tool_exec_environment_variables
+ # Convert ORM env vars to Pydantic with async decryption
+ env_vars_pydantic = [await PydanticAgentEnvVar.from_orm_async(e) for e in tool_exec_environment_variables]
+ state["tool_exec_environment_variables"] = env_vars_pydantic
+ state["secrets"] = env_vars_pydantic
state["model"] = self.llm_config.handle if self.llm_config else None
state["model_settings"] = self.llm_config._to_model_settings() if self.llm_config else None
state["embedding"] = self.embedding_config.handle if self.embedding_config else None
diff --git a/letta/schemas/agent.py b/letta/schemas/agent.py
index ec5a27648..57d8e0b8c 100644
--- a/letta/schemas/agent.py
+++ b/letta/schemas/agent.py
@@ -165,10 +165,11 @@ class AgentState(OrmMetadataBase, validate_assignment=True):
)
def get_agent_env_vars_as_dict(self) -> Dict[str, str]:
- # Get environment variables for this agent specifically (read from encrypted value_enc)
+ # Get environment variables for this agent (value is already decrypted via from_orm_async)
per_agent_env_vars = {}
for agent_env_var_obj in self.secrets:
- per_agent_env_vars[agent_env_var_obj.key] = agent_env_var_obj.value_enc.get_plaintext() if agent_env_var_obj.value_enc else None
+ # Use the pre-decrypted value field (populated by from_orm_async)
+ per_agent_env_vars[agent_env_var_obj.key] = agent_env_var_obj.value or ""
return per_agent_env_vars
@model_validator(mode="after")
diff --git a/letta/schemas/environment_variables.py b/letta/schemas/environment_variables.py
index 4d1d3afdb..81abfa357 100644
--- a/letta/schemas/environment_variables.py
+++ b/letta/schemas/environment_variables.py
@@ -59,6 +59,33 @@ class SandboxEnvironmentVariableBase(EnvironmentVariableBase):
class SandboxEnvironmentVariable(SandboxEnvironmentVariableBase):
id: str = SandboxEnvironmentVariableBase.generate_id_field()
+ @classmethod
+ async def from_orm_async(cls, orm_obj) -> "SandboxEnvironmentVariable":
+ """
+ Create Pydantic model from ORM with async decryption.
+
+ This pre-decrypts value_enc asynchronously before model creation,
+ avoiding the synchronous decryption in the model validator.
+ """
+ data = {
+ "id": orm_obj.id,
+ "key": orm_obj.key,
+ "description": orm_obj.description,
+ "organization_id": orm_obj.organization_id,
+ "sandbox_config_id": orm_obj.sandbox_config_id,
+ "value": "",
+ "value_enc": None,
+ }
+
+ if orm_obj.value_enc:
+ secret = Secret.from_encrypted(orm_obj.value_enc)
+ data["value"] = await secret.get_plaintext_async() or ""
+ data["value_enc"] = secret
+ elif orm_obj.value:
+ data["value"] = orm_obj.value
+
+ return cls.model_validate(data)
+
class SandboxEnvironmentVariableCreate(EnvironmentVariableCreateBase):
pass
@@ -77,6 +104,33 @@ class AgentEnvironmentVariableBase(EnvironmentVariableBase):
class AgentEnvironmentVariable(AgentEnvironmentVariableBase):
id: str = AgentEnvironmentVariableBase.generate_id_field()
+ @classmethod
+ async def from_orm_async(cls, orm_obj) -> "AgentEnvironmentVariable":
+ """
+ Create Pydantic model from ORM with async decryption.
+
+ This pre-decrypts value_enc asynchronously before model creation,
+ avoiding the synchronous decryption in the model validator.
+ """
+ data = {
+ "id": orm_obj.id,
+ "key": orm_obj.key,
+ "description": orm_obj.description,
+ "organization_id": orm_obj.organization_id,
+ "agent_id": orm_obj.agent_id,
+ "value": "",
+ "value_enc": None,
+ }
+
+ if orm_obj.value_enc:
+ secret = Secret.from_encrypted(orm_obj.value_enc)
+ data["value"] = await secret.get_plaintext_async() or ""
+ data["value_enc"] = secret
+ elif orm_obj.value:
+ data["value"] = orm_obj.value
+
+ return cls.model_validate(data)
+
class AgentEnvironmentVariableCreate(EnvironmentVariableCreateBase):
pass
diff --git a/letta/schemas/secret.py b/letta/schemas/secret.py
index 2790c4aa6..e28f7641f 100644
--- a/letta/schemas/secret.py
+++ b/letta/schemas/secret.py
@@ -129,7 +129,10 @@ class Secret(BaseModel):
def get_plaintext(self) -> Optional[str]:
"""
- Get the decrypted plaintext value.
+ Get the decrypted plaintext value (synchronous version).
+
+ WARNING: This performs CPU-intensive PBKDF2 key derivation that can block for 100-500ms.
+ Use get_plaintext_async() in async contexts to avoid blocking the event loop.
This should only be called when the plaintext is actually needed,
such as when making an external API call.
@@ -191,6 +194,63 @@ class Secret(BaseModel):
# Re-raise for other errors
raise
+ async def get_plaintext_async(self) -> Optional[str]:
+ """
+ Get the decrypted plaintext value (async version).
+
+ Runs the CPU-intensive PBKDF2 key derivation in a thread pool to avoid
+ blocking the event loop. This prevents the event loop freeze that occurs
+ when decrypting secrets synchronously during HTTP request handling.
+
+ This should be used in all async contexts (FastAPI endpoints, async services, etc.)
+ to avoid blocking the event loop for 100-500ms per decryption.
+
+ Returns:
+ The decrypted plaintext value, or None if the secret is empty
+ """
+ if self.encrypted_value is None:
+ return None
+
+ # Use cached value if available
+ if self._plaintext_cache is not None:
+ if not self.was_encrypted:
+ return self._plaintext_cache
+ return self._plaintext_cache
+
+ # Try to decrypt (async)
+ try:
+ plaintext = await CryptoUtils.decrypt_async(self.encrypted_value)
+ # Cache the decrypted value
+ self._plaintext_cache = plaintext
+ return plaintext
+ except ValueError as e:
+ error_msg = str(e)
+
+ # Handle missing encryption key - check if value is actually plaintext
+ if "No encryption key configured" in error_msg:
+ if CryptoUtils.is_encrypted(self.encrypted_value):
+ logger.warning(
+ "Cannot decrypt Secret value - no encryption key configured. "
+ "The value was encrypted and requires the original key to decrypt."
+ )
+ return None
+ else:
+ logger.debug("Secret value is plaintext (stored without encryption)")
+ self._plaintext_cache = self.encrypted_value
+ return self.encrypted_value
+
+ # Handle decryption failure - check if value might be plaintext
+ elif "Failed to decrypt data" in error_msg:
+ if not CryptoUtils.is_encrypted(self.encrypted_value):
+ logger.debug("Secret value appears to be plaintext (stored without encryption)")
+ self._plaintext_cache = self.encrypted_value
+ return self.encrypted_value
+ logger.error("Failed to decrypt Secret value - data may be corrupted or wrong key")
+ raise
+
+ # Re-raise for other errors
+ raise
+
def is_empty(self) -> bool:
"""Check if the secret is empty/None."""
return self.encrypted_value is None
diff --git a/letta/services/sandbox_config_manager.py b/letta/services/sandbox_config_manager.py
index 9a4ac0604..67823bd30 100644
--- a/letta/services/sandbox_config_manager.py
+++ b/letta/services/sandbox_config_manager.py
@@ -211,7 +211,7 @@ class SandboxConfigManager:
env_var = SandboxEnvVarModel(**env_var.model_dump(to_orm=True))
await env_var.create_async(session, actor=actor)
- return env_var.to_pydantic()
+ return await PydanticEnvVar.from_orm_async(env_var)
@enforce_types
@trace_method
@@ -232,7 +232,7 @@ class SandboxConfigManager:
existing_value = None
if env_var.value_enc:
existing_secret = Secret.from_encrypted(env_var.value_enc)
- existing_value = existing_secret.get_plaintext()
+ existing_value = await existing_secret.get_plaintext_async()
# Only re-encrypt if different
if existing_value != update_data["value"]:
@@ -255,7 +255,7 @@ class SandboxConfigManager:
f"`update_sandbox_env_var` called with user_id={actor.id}, organization_id={actor.organization_id}, "
f"key={env_var.key}, but nothing to update."
)
- return env_var.to_pydantic()
+ return await PydanticEnvVar.from_orm_async(env_var)
@enforce_types
@trace_method
@@ -264,7 +264,7 @@ class SandboxConfigManager:
async with db_registry.async_session() as session:
env_var = await SandboxEnvVarModel.read_async(db_session=session, identifier=env_var_id, actor=actor)
await env_var.hard_delete_async(db_session=session, actor=actor)
- return env_var.to_pydantic()
+ return await PydanticEnvVar.from_orm_async(env_var)
@enforce_types
@trace_method
@@ -285,7 +285,7 @@ class SandboxConfigManager:
organization_id=actor.organization_id,
sandbox_config_id=sandbox_config_id,
)
- return [env_var.to_pydantic() for env_var in env_vars]
+ return [await PydanticEnvVar.from_orm_async(env_var) for env_var in env_vars]
@enforce_types
@trace_method
@@ -301,7 +301,7 @@ class SandboxConfigManager:
organization_id=actor.organization_id,
key=key,
)
- return [env_var.to_pydantic() for env_var in env_vars]
+ return [await PydanticEnvVar.from_orm_async(env_var) for env_var in env_vars]
@enforce_types
@trace_method
@@ -323,8 +323,8 @@ class SandboxConfigManager:
self, sandbox_config_id: str, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50
) -> Dict[str, str]:
env_vars = await self.list_sandbox_env_vars_async(sandbox_config_id, actor, after, limit)
- # Decrypt values before returning
- return {env_var.key: env_var.value_enc.get_plaintext() if env_var.value_enc else None for env_var in env_vars}
+ # Values are already decrypted via from_orm_async
+ return {env_var.key: env_var.value for env_var in env_vars}
@enforce_types
@trace_method
@@ -343,7 +343,7 @@ class SandboxConfigManager:
limit=1,
)
if env_var:
- return env_var[0].to_pydantic()
+ return await PydanticEnvVar.from_orm_async(env_var[0])
return None
except NoResultFound:
return None