diff --git a/src/Acme.BookStore.HttpApi.Host/Infrastructure/EnviromentLoader.cs b/src/Acme.BookStore.HttpApi.Host/Infrastructure/EnviromentLoader.cs new file mode 100644 index 0000000..f8159be --- /dev/null +++ b/src/Acme.BookStore.HttpApi.Host/Infrastructure/EnviromentLoader.cs @@ -0,0 +1,57 @@ +using Castle.Core.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Threading.Tasks; +using VaultSharp; +using VaultSharp.V1.AuthMethods.Token; +using VaultSharp.V1.Commons; + +namespace Acme.BookStore.Infrastructure; + +public static class EnviromentLoader +{ + public static async Task SetDatabaseEnviroment([NotNull] this WebApplicationBuilder builder) + { + if (!builder.Environment.IsProduction()) + return; + + var connectionSection = builder.Configuration.GetSection("ConnectionStrings"); + var connections = connectionSection.GetChildren(); + var sb = new StringBuilder(); + + foreach (var connection in connections) + { + sb.Append(connection.Path); + sb.Append('='); + sb.Append(await UpdateVaue(connection.Key)); + } + + builder.Configuration.AddEnvironmentVariables(sb.ToString()); + } + + private static async Task UpdateVaue(string key) + { + var secrate = await GetSecret(); + return secrate.Data.Data.TryGetValue(key, out var val) + ? val?.ToString() ?? string.Empty + : string.Empty; + } + + public static async Task> GetSecret() + { + var path = Environment.GetEnvironmentVariable("path") ?? throw new ArgumentNullException("path"); + var mountPoint = Environment.GetEnvironmentVariable("mountPoint") ?? throw new ArgumentNullException("mountPoint"); + var token = Environment.GetEnvironmentVariable("token") ?? throw new ArgumentNullException("token"); + var url = Environment.GetEnvironmentVariable("url") ?? throw new ArgumentNullException("url"); + var authMethod = new TokenAuthMethodInfo(token); + var vaultClientSettings = new VaultClientSettings(url, authMethod); + IVaultClient client = new VaultClient(vaultClientSettings); + var kv2Secret = await client.V1.Secrets.KeyValue.V2 + .ReadSecretAsync(path: path, mountPoint: mountPoint); + return kv2Secret; + } +} diff --git a/src/Acme.BookStore.HttpApi.Host/Program.cs b/src/Acme.BookStore.HttpApi.Host/Program.cs index 08f7008..8c3d88a 100644 --- a/src/Acme.BookStore.HttpApi.Host/Program.cs +++ b/src/Acme.BookStore.HttpApi.Host/Program.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using Acme.BookStore.Infrastructure; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -39,6 +40,7 @@ public class Program .WriteTo.Async(c => c.Console()) .WriteTo.Async(c => c.AbpStudio(services)); }); + await builder.SetDatabaseEnviroment(); await builder.AddApplicationAsync(); var app = builder.Build(); await app.InitializeApplicationAsync();