refactor: Improve API key decryption error logging (#6193)

refactor: improve API key decryption error handling and logging
This commit is contained in:
Gabriel Luiz Freitas Almeida 2025-02-18 12:32:14 -03:00 committed by GitHub
commit 25ac555e8f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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 ""