Every dev on my team has their own personal Azure key vault linked to their local machine. We have a production Azure key vault that our production site looks at.
In the code, it looks for a specific secret from the vault. The devs won't have the secret in their personal key vaults, but the production key vault will have the secret.
So, when the devs are debugging it will catch an exception saying that the secret doesn't exist.
Is there a way to conditionally check whether or not the secret exists, or do I just have to let it catch the exception?
There is no method to check if a secret exists in a key vault. So some creativity could be employed to do just that(skipped arguments checks for brevity):
public bool CheckIfSecretExists(string accessToken, string secretUri)
{
var kvClient= new KeyVaultClient(accessToken);
try
{
kvClient.GetSecretAsync(secretUri ).Result.Value;
return true;
}
catch (AggregateException ex)
{
if (ex.InnerException is KeyVaultErrorException exception && exception.Body.Error.Code == "SecretNotFound")
return false;
throw;
}
}
EDIT: Found a way to check if secret exists without relying on exception:
public async Task<bool> DoesSecretExist(string accessToken, string keyVaultBaseUrl, string secretName)
{
var kvClient = new KeyVaultClient(accessToken);
try
{
IPage<SecretItem> secretVersions = await kvClient.GetSecretVersionsAsync(keyVaultBaseUrl, secretName)
.ConfigureAwait(false);
if (!secretVersions.Any())
return false;
return true;
}
catch (Exception )
{
throw;
}
}
An easier way to check if the error is a not found in the exception is from the HTTPRequest response
try
{
var secret = await this.keyVaultClient.GetSecretAsync(keyVaultUri, secretName, cancellationToken).ConfigureAwait(false);
}
catch (KeyVaultErrorException ex)
{
if (ex.Response.StatusCode != HttpStatusCode.NotFound)
{
// Handle the error
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With