public override bool Execute()
        {
            var debug      = string.Equals("true", DebugTask?.Trim(), StringComparison.OrdinalIgnoreCase);
            var promptAuth = string.Equals("true", AlwaysPromptInteractiveAuth?.Trim(), StringComparison.OrdinalIgnoreCase);

            Config.Log.Information = x => Log.LogWarning(x);
            Config.Log.Error       = (ex, m) => Log.LogError("Error while processing secrets from keyvault. " + Environment.NewLine + ex);

            try
            {
                if (debug && !Debugger.IsAttached)
                {
                    Debugger.Launch();
                    Debugger.Break();
                }

                if (promptAuth)
                {
                    Log.LogWarning("KeyVaultBuildTask: Set to always prompting for auth information.");
                }

                var service = SecretServiceBuilder.Create()
                              .AlwaysPromptInteractiveAuth(promptAuth)
                              .WithDirectory(DirectoryId)
                              .WithServicePrincipal(ClientId, Secret);

                if (!string.IsNullOrEmpty(VaultAliases))
                {
                    foreach (var alias in VaultAliases?.Trim().Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var pair = alias.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        service.WithVaultAlias(pair.First(), pair.Last());
                        Log.LogWarning("Overriding vault '{0}' with '{1}'", pair.First(), pair.Last());
                    }
                }

                var transformKey = new TransformKeys(service.Build());
                var files        = ConfigFiles.Select(file => file.GetMetadata("Fullpath")).ToArray();

                Parallel.ForEach(files, file =>
                {
                    transformKey.SaveAsFile(file);
                });
            }
            catch (Exception ex)
            {
                TokenCache.DefaultShared.Clear();
                Config.Log.Error(ex, "Error occured processing secrets. ");
                if (debug)
                {
                    Debugger.Break();
                }
                return(false);
            }

            return(true);
        }
 public void GivenASecretServiceBuilderWithNoAuthInformation_ThenAnExceptionIsThrown()
 {
     Assert.Throws <Exception>(() => SecretServiceBuilder.Create().Build());
 }
示例#3
0
        private static int RunAddAndReturnExitCode(TemplateArguments opts)
        {
            Console.WriteLine("** KeyVaultBuild Template File Processor **");
            try
            {
                var service = SecretServiceBuilder.Create()
                              .WithDirectory(opts.DirectoryId)
                              .AlwaysPromptInteractiveAuth(opts.AlwaysPromptAuth)
                              .Build();
                var writer = service.GetWriter(opts.Vault);

                var loaded      = XDocument.Load(opts.ConfigFile);
                var appSettings = loaded.Descendants("appSettings").Descendants("add")
                                  .Where(x =>
                {
                    foreach (var pattern in opts.AppSettings)
                    {
                        if (Regex.IsMatch((string)x.Attribute("key"), pattern))
                        {
                            return(true);
                        }
                    }

                    return(false);
                });

                var connectionStrings = loaded.Descendants("connectionStrings").Descendants("add");

                foreach (var setting in appSettings)
                {
                    var keyName = "appsetting-" + ((string)setting.Attribute("key")).ToSlug();
                    var val     = (string)setting.Attribute("value");

                    if (!string.IsNullOrEmpty(keyName) && !string.IsNullOrEmpty(val))
                    {
                        writer.Set(keyName, val).Wait();
                        setting.SetAttributeValue("value", $"#{{keyvault:{writer.Vault}:{keyName}}}");
                    }
                }

                foreach (var setting in connectionStrings)
                {
                    var keyName = "connectionstring-" + ((string)setting.Attribute("name")).ToSlug();
                    var val     = (string)setting.Attribute("connectionString");

                    if (!string.IsNullOrEmpty(keyName) && !string.IsNullOrEmpty(val))
                    {
                        writer.Set(keyName, val).Wait();
                        setting.SetAttributeValue("connectionString", $"#{{keyvault:{writer.Vault}:{keyName}}}");
                    }
                }

                var file         = new FileInfo(opts.ConfigFile);
                var templateFile = Path.Combine(file.DirectoryName, file.Name.Replace(file.Extension, ".keyvault.template"));
                loaded.Save(File.OpenWrite(templateFile));

                Console.WriteLine("Successfully created template file '{0}'.", templateFile);
                Console.WriteLine("When ready you can delete the original config file and use the build task to restore the values from KeyVault.");
                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(1);
            }

            return(0);
        }