53 lines
1.9 KiB
C#
53 lines
1.9 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.Threading.Tasks;
|
|
using JD.SecretsManager;
|
|
|
|
namespace JD.Vault
|
|
{
|
|
public static class ServiceAccounts
|
|
{
|
|
private static readonly IReadOnlyDictionary<string, string> _knownAccounts;
|
|
private static readonly ConcurrentDictionary<string, string> _cachedCredentials;
|
|
|
|
static ServiceAccounts()
|
|
{
|
|
var knownAccounts = new Dictionary<string, string>
|
|
{
|
|
{ "jd4-robot", "tools/service-accounts/jd4-robot" },
|
|
{ "jd-tools-robot", "tools/service-accounts/jd-tools-robot" },
|
|
};
|
|
_knownAccounts = new ReadOnlyDictionary<string, string>(knownAccounts);
|
|
_cachedCredentials = new ConcurrentDictionary<string, string>();
|
|
}
|
|
|
|
public static string GetServiceAccountPassword(string accountLogin)
|
|
{
|
|
return _cachedCredentials.GetOrAdd(accountLogin, GetPasswordFromSecretsManager);
|
|
}
|
|
|
|
private static string GetPasswordFromSecretsManager(string accountLogin)
|
|
{
|
|
if (!_knownAccounts.TryGetValue(accountLogin, out string secretsPath))
|
|
{
|
|
// Not a known account, ignore
|
|
return null;
|
|
}
|
|
|
|
const string passwordKey = "password";
|
|
|
|
ISecretsManager secretsManager = SecretsManagement.GetSecretsManager();
|
|
IDictionary<string, object> secrets = Task.Run(() => secretsManager.GetSecretAsync(secretsPath)).Result;
|
|
if (secrets is null
|
|
|| !secrets.TryGetValue(passwordKey, out object password))
|
|
{
|
|
string errorMessage = $"Failed to get configuration secrets from {secretsPath}. Please contact support.";
|
|
throw new Exception(errorMessage);
|
|
}
|
|
|
|
return password as string;
|
|
}
|
|
}
|
|
}
|