Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve Key Vault references using local identity #2258

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ internal class StartHostAction : BaseAction
private const int DefaultTimeout = 20;
private readonly ISecretsManager _secretsManager;
private IConfigurationRoot _hostJsonConfig;
private readonly KeyVaultReferencesManager _keyVaultReferencesManager;

public int Port { get; set; }

Expand Down Expand Up @@ -74,6 +75,7 @@ internal class StartHostAction : BaseAction
public StartHostAction(ISecretsManager secretsManager)
{
_secretsManager = secretsManager;
_keyVaultReferencesManager = new KeyVaultReferencesManager();
}

public override ICommandLineParserResult ParseArgs(string[] args)
Expand Down Expand Up @@ -184,6 +186,7 @@ private async Task<IWebHost> BuildWebHost(ScriptApplicationHostOptions hostOptio

IDictionary<string, string> settings = await GetConfigurationSettings(hostOptions.ScriptPath, baseAddress);
settings.AddRange(LanguageWorkerHelper.GetWorkerConfiguration(LanguageWorkerSetting));
_keyVaultReferencesManager.ResolveKeyVaultReferences(settings);
UpdateEnvironmentVariables(settings);

var defaultBuilder = Microsoft.AspNetCore.WebHost.CreateDefaultBuilder(Array.Empty<string>());
Expand Down
2 changes: 2 additions & 0 deletions src/Azure.Functions.Cli/Azure.Functions.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="4.6.2" />
<PackageReference Include="Azure.Identity" Version="1.2.3" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.0.3" />
<PackageReference Include="Colors.Net" Version="1.1.0" />
<PackageReference Include="AccentedCommandLineParser" Version="2.0.0" />
<PackageReference Include="DotNetZip" Version="1.13.3" />
Expand Down
111 changes: 111 additions & 0 deletions src/Azure.Functions.Cli/Common/KeyVaultReferencesManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Azure.Core;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

namespace Azure.Functions.Cli.Common
{
class KeyVaultReferencesManager
{
private const string directiveStart = "@Microsoft.KeyVault(";
private const string directiveEnd = ")";
private const string vaultUriSuffix = "vault.azure.net";
private readonly ConcurrentDictionary<string, SecretClient> clients = new ConcurrentDictionary<string, SecretClient>();
private readonly TokenCredential credential = new ChainedTokenCredential(
new AzureCliCredential(),
new VisualStudioCodeCredential(),
new VisualStudioCredential(),
new EnvironmentCredential());

public void ResolveKeyVaultReferences(IDictionary<string, string> settings)
{
foreach (var key in settings.Keys.ToList())
{
var keyVaultValue = GetSecretValue(settings[key]);
if (keyVaultValue != null)
{
settings[key] = keyVaultValue;
}
}
}

private string GetSecretValue(string value)
{
var result = ParseSecret(value);

if (result != null)
{
var client = GetSecretClient(result.Uri);
var secret = client.GetSecret(result.Name, result.Version);
return secret.Value.Value;
}

return null;
}

private ParseSecretResult ParseSecret(string value)
{
var referenceString = ExtractReferenceString(value);
if (string.IsNullOrEmpty(referenceString))
{
return null;
}

try
{
var uriMatches = Regex.Match(referenceString, @"SecretUri=(https://.+?)/secrets/([^/]+)/?(.*)");
if (uriMatches.Success)
{
return new ParseSecretResult
{
Uri = new Uri(uriMatches.Groups[1].Value),
Name = uriMatches.Groups[2].Value,
Version = uriMatches.Groups[3].Value
};
}

var keyValuePairs = referenceString.Split(";")
.Select(item => item.Split("="))
.ToDictionary(pair => pair[0], pair => pair[1]);

return new ParseSecretResult
{
Uri = new Uri($"https://{keyValuePairs.GetValueOrDefault("VaultName")}.{vaultUriSuffix}"),
Name = keyValuePairs.GetValueOrDefault("SecretName"),
Version = keyValuePairs.GetValueOrDefault("SecretVersion")
};
}
catch
{
throw new FormatException($"Key Vault Reference format invalid: {value}");
}
}

private string ExtractReferenceString(string value)
{
if (value == null ||
!(value.StartsWith(directiveStart) && value.EndsWith(directiveEnd)))
{
return null;
}

return value.Substring(directiveStart.Length, value.Length - directiveStart.Length - directiveEnd.Length);
}

private SecretClient GetSecretClient(Uri vaultUri)
{
return clients.GetOrAdd(vaultUri.ToString(), _ => new SecretClient(vaultUri, credential));
}

private class ParseSecretResult
{
public Uri Uri { get; set; }
public string Name { get; set; }
public string Version { get; set; }
}
}
}