@@ -375,13 +375,29 @@ def encrypt_api_key(api_key: str, settings_service: SettingsService):
375
375
376
376
377
377
def decrypt_api_key (encrypted_api_key : str , settings_service : SettingsService ):
378
+ """Decrypt the provided encrypted API key using Fernet decryption.
379
+
380
+ This function first attempts to decrypt the API key by encoding it,
381
+ assuming it is a properly encoded string. If that fails, it logs a detailed
382
+ debug message including the exception information and retries decryption
383
+ using the original string input.
384
+
385
+ Args:
386
+ encrypted_api_key (str): The encrypted API key.
387
+ settings_service (SettingsService): Service providing authentication settings.
388
+
389
+ Returns:
390
+ str: The decrypted API key, or an empty string if decryption cannot be performed.
391
+ """
378
392
fernet = get_fernet (settings_service )
379
- decrypted_key = ""
380
- # Two-way decryption
381
393
if isinstance (encrypted_api_key , str ):
382
394
try :
383
- decrypted_key = fernet .decrypt (encrypted_api_key .encode ()).decode ()
384
- except Exception : # noqa: BLE001
385
- logger .debug ("Failed to decrypt API key" )
386
- decrypted_key = fernet .decrypt (encrypted_api_key ).decode ()
387
- return decrypted_key
395
+ return fernet .decrypt (encrypted_api_key .encode ()).decode ()
396
+ except Exception as primary_exception : # noqa: BLE001
397
+ logger .debug (
398
+ "Decryption using UTF-8 encoded API key failed. Error: %s. "
399
+ "Retrying decryption using the raw string input." ,
400
+ primary_exception ,
401
+ )
402
+ return fernet .decrypt (encrypted_api_key ).decode ()
403
+ return ""
0 commit comments