Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if secret is in Azure Key Vault

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?

like image 736
dustinos3 Avatar asked Mar 06 '23 04:03

dustinos3


2 Answers

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;
    }
}
like image 89
fatherOfWine Avatar answered Mar 12 '23 01:03

fatherOfWine


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
    }

 }
like image 22
Tommy Avatar answered Mar 12 '23 00:03

Tommy