refactor: Improve API key decryption error logging (#6193)
refactor: improve API key decryption error handling and logging
This commit is contained in:
parent
73d2b2f9af
commit
25ac555e8f
1 changed files with 23 additions and 7 deletions
|
|
@ -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 ""
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue