diff --git a/src/backend/base/langflow/services/auth/utils.py b/src/backend/base/langflow/services/auth/utils.py index 50a24806e..28b1b1c4d 100644 --- a/src/backend/base/langflow/services/auth/utils.py +++ b/src/backend/base/langflow/services/auth/utils.py @@ -375,13 +375,29 @@ def encrypt_api_key(api_key: str, settings_service: SettingsService): def decrypt_api_key(encrypted_api_key: str, settings_service: SettingsService): + """Decrypt the provided encrypted API key using Fernet decryption. + + This function first attempts to decrypt the API key by encoding it, + assuming it is a properly encoded string. If that fails, it logs a detailed + debug message including the exception information and retries decryption + using the original string input. + + Args: + encrypted_api_key (str): The encrypted API key. + settings_service (SettingsService): Service providing authentication settings. + + Returns: + str: The decrypted API key, or an empty string if decryption cannot be performed. + """ fernet = get_fernet(settings_service) - decrypted_key = "" - # Two-way decryption if isinstance(encrypted_api_key, str): try: - decrypted_key = fernet.decrypt(encrypted_api_key.encode()).decode() - except Exception: # noqa: BLE001 - logger.debug("Failed to decrypt API key") - decrypted_key = fernet.decrypt(encrypted_api_key).decode() - return decrypted_key + return fernet.decrypt(encrypted_api_key.encode()).decode() + except Exception as primary_exception: # noqa: BLE001 + logger.debug( + "Decryption using UTF-8 encoded API key failed. Error: %s. " + "Retrying decryption using the raw string input.", + primary_exception, + ) + return fernet.decrypt(encrypted_api_key).decode() + return ""