Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to detect non-existent key in KeyVault

I'm using KeyVaultClient from the 2.3.2 Microsoft.Azure.KeyVault NuGet. Using GetSecretAsync(,), I noticed that a KeyVaultErrorException is raised if I try to access a non-existent secret.

Unfortunately that same error is also raised when access to the keyvault is denied or the keyvault endpoint is not found.

The only distinguisher I see at the moment is the Message property. So what's the right way to detect that a secret was not found? Why would this throw an exception versus returning a null or some other 'empty' object?

like image 697
Jim O'Neil Avatar asked Oct 18 '22 08:10

Jim O'Neil


1 Answers

Asking for nonexistent secret:

System.AggregateException occurred
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib

Inner Exception 1:
KeyVaultErrorException: Secret not found: secret22222

((Microsoft.Azure.KeyVault.Models.KeyVaultErrorException)($exception).InnerException)
    .Body.Error.Code = "SecretNotFound"
((Microsoft.Azure.KeyVault.Models.KeyVaultErrorException)($exception).InnerException)
    .Body.Error.Message = "Secret not found: secret22222"

No rights for reading secret:

System.AggregateException occurred
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib

Inner Exception 1:
KeyVaultErrorException: Access denied

((Microsoft.Azure.KeyVault.Models.KeyVaultErrorException)($exception).InnerException)
    .Body.Error.Code = "Forbidden"
((Microsoft.Azure.KeyVault.Models.KeyVaultErrorException)($exception).InnerException)
    .Body.Error.Message = "Access denied"

Trying to read a disabled secret:

System.AggregateException occurred
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib

Inner Exception 1:
KeyVaultErrorException: Operation get is not allowed on a disabled secret.

((Microsoft.Azure.KeyVault.Models.KeyVaultErrorException)($exception).InnerException)
    .Body.Error.Code = "Forbidden"
((Microsoft.Azure.KeyVault.Models.KeyVaultErrorException)($exception).InnerException)
    .Body.Error.Message = "Operation get is not allowed on a disabled secret."

Invalid vault endpoint:

System.AggregateException occurred
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib

Inner Exception 1:
HttpRequestException: An error occurred while sending the request.

Inner Exception 2:
WebException: The remote name could not be resolved: 'alicezzzzzz.vault.azure.net'

Doesn't look that bad to me. If you're expecting strong error typing, i don't think that's going to happen given the SDK is just light REST wrapper, probably (partially?) generated by AutoRest - not obviously mentioned, but still mentioned :) in the NuGet project description (Project Site).

like image 187
evilSnobu Avatar answered Oct 21 '22 01:10

evilSnobu