public void SetEditItem(DeploymentTaskConfig config) { EditModel = new ViewModel.DeploymentTaskConfigViewModel(config); DataContext = EditModel; EditModel.RefreshOptions(); }
public DeploymentTask(IDeploymentTaskProvider provider, DeploymentTaskConfig config, Dictionary <string, string> credentials) { TaskConfig = config; TaskProvider = provider; _credentials = credentials; }
public async Task <List <ActionResult> > Execute(ILog log, object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, bool isPreviewOnly, DeploymentProviderDefinition definition) { var results = new List <ActionResult>(); var managedCert = ManagedCertificate.GetManagedCertificate(subject); // check settings are valid before proceeding var validationResults = await Validate(managedCert, settings, credentials, definition); if (validationResults.Any()) { return(validationResults); } var requestedStore = settings.Parameters.FirstOrDefault(p => p.Key == "storetype")?.Value.Trim().ToLower(); var friendlyName = settings.Parameters.FirstOrDefault(p => p.Key == "friendlyname")?.Value.Trim(); //store cert against primary domain, optionally with custom friendly name var certStoreName = CertificateManager.DEFAULT_STORE_NAME; if (requestedStore != "default") { certStoreName = requestedStore; } X509Certificate2 storedCert = null; if (!isPreviewOnly) { try { storedCert = await CertificateManager.StoreCertificate( managedCert.RequestConfig.PrimaryDomain, managedCert.CertificatePath, isRetry : false, enableRetryBehaviour : _enableCertDoubleImportBehaviour, storeName : certStoreName, customFriendlyName : friendlyName ); if (storedCert != null) { // certHash = storedCert.GetCertHash(); results.Add(new ActionResult("Certificate stored OK", true)); } } catch (Exception exp) { results.Add(new ActionResult("Error storing certificate :: " + exp.Message, false)); } } else { results.Add(new ActionResult($"Would store certificate in Local Certificate Store [{certStoreName}]", true)); } return(results); }
public EditDeploymentTask(DeploymentTaskConfig config, bool editAsPostRequestTask) { InitializeComponent(); this.DataContext = AppViewModel; this.Width *= AppViewModel.UIScaleFactor; this.Height *= AppViewModel.UIScaleFactor; DeploymentTaskEditor.SetEditItem(config, editAsPostRequestTask); }
public DeploymentTaskConfigViewModel(DeploymentTaskConfig item) { if (item == null) { item = new DeploymentTaskConfig { Description = "A description for this task", Parameters = new List <ProviderParameterSetting>() }; } SelectedItem = item; }
public DeploymentTaskConfigViewModel(DeploymentTaskConfig item) { if (item == null) { item = new DeploymentTaskConfig { ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting>() }; } SelectedItem = item; }
public void SetEditItem(DeploymentTaskConfig config, bool editAsPostRequestTask) { EditModel = new ViewModel.DeploymentTaskConfigViewModel(config, editAsPostRequestTask); this.StoredCredentials.ItemsSource = EditModel.FilteredCredentials; DataContext = EditModel; var providers = EditModel.DeploymentProviders; Task.Run(async() => await RefreshEditModelOptions(resetDefaults: false)); }
private void TaskCompleteDrop(object sender, DragEventArgs e) { DeploymentTaskConfig targetTask = null; if (e.OriginalSource is TextBlock) { targetTask = (e.OriginalSource as TextBlock).DataContext as DeploymentTaskConfig; } if (e.Data.GetDataPresent(DataFormats.StringFormat)) { string context = "PostRequest"; var droppedTaskId = (string)e.Data.GetData(DataFormats.StringFormat); var droppedTask = ItemViewModel.SelectedItem.PostRequestTasks?.FirstOrDefault(t => t.Id == droppedTaskId); if (droppedTask == null) { context = "PreRequest"; droppedTask = ItemViewModel.SelectedItem.PreRequestTasks?.FirstOrDefault(t => t.Id == droppedTaskId); } if (targetTask != null && droppedTask != null) { //get index of target task and insert at that position if (context == "PostRequest") { var targetIndex = ItemViewModel.SelectedItem.PostRequestTasks?.IndexOf(targetTask); if (targetIndex >= 0) { ItemViewModel.SelectedItem.PostRequestTasks.Remove(droppedTask); ItemViewModel.SelectedItem.PostRequestTasks.Insert((int)targetIndex, droppedTask); } } else { var targetIndex = ItemViewModel.SelectedItem.PreRequestTasks?.IndexOf(targetTask); if (targetIndex >= 0) { ItemViewModel.SelectedItem.PreRequestTasks.Remove(droppedTask); ItemViewModel.SelectedItem.PreRequestTasks.Insert((int)targetIndex, droppedTask); } } } // re-order task list e.Effects = DragDropEffects.Move; } e.Handled = true; }
public async Task <List <ActionResult> > Validate(object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, DeploymentProviderDefinition definition) { var results = new List <ActionResult> { }; foreach (var p in definition.ProviderParameters) { if (!settings.Parameters.Exists(s => s.Key == p.Key) && p.IsRequired) { results.Add(new ActionResult($"Required parameter not supplied: { p.Name}", false)); } } return(results); }
public DeploymentTaskConfigViewModel(DeploymentTaskConfig item, bool editAsPostRequestTask) { EditAsPostRequestTask = editAsPostRequestTask; if (item == null) { item = new DeploymentTaskConfig { ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting>(), TaskTrigger = editAsPostRequestTask ? TaskTriggerType.ON_SUCCESS : TaskTriggerType.ANY_STATUS }; } SelectedItem = item; }
public static SshConnectionConfig GetConnectionConfig(DeploymentTaskConfig config, Dictionary <string, string> credentials) { int port = 22; var host = config.TargetHost; if (config.TargetHost?.Contains(":") == true) { try { var components = config.TargetHost.Split(':'); port = int.Parse(components[1].Trim()); host = components[0].Trim(); } catch { } } var sshConfig = new SshConnectionConfig { Host = host, Port = port }; credentials.TryGetValue("username", out var username); if (username != null) { sshConfig.Username = username; } credentials.TryGetValue("password", out var password); if (password != null) { sshConfig.Password = password; } credentials.TryGetValue("privatekey", out var privatekey); if (privatekey != null) { sshConfig.PrivateKeyPath = privatekey; } credentials.TryGetValue("key_passphrase", out var passphrase); if (passphrase != null) { sshConfig.KeyPassphrase = passphrase; } return(sshConfig); }
public async Task <List <ActionResult> > Validate(object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, DeploymentProviderDefinition definition) { var results = new List <ActionResult>(); var url = settings.Parameters.FirstOrDefault(p => p.Key == "url")?.Value; var method = settings.Parameters.FirstOrDefault(p => p.Key == "method")?.Value; if (url == null || !Uri.TryCreate(url, UriKind.Absolute, out var result)) { results.Add(new ActionResult($"The webhook url must be a valid url.", false)); } if (string.IsNullOrEmpty(method)) { results.Add(new ActionResult($"The webhook HTTP method must be a selected.", false)); } return(results); }
public async Task TestDeployToKeyVault() { var deploymentTasks = new List <DeploymentTask>(); var azureKeyVaultUri = ConfigSettings["Azure_TestKeyVaultUri"]; var inputFile = ConfigSettings["TestLocalPath"] + "\\testcert.pfx"; var tasktypeId = Plugin.DeploymentTasks.Azure.AzureKeyVault.Definition.Id.ToLower(); var config = new DeploymentTaskConfig { TaskTypeId = tasktypeId, TaskName = "A test pfx export task", ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("vault_uri", azureKeyVaultUri) } }; var credentialsManager = new CredentialsManager(); var credentials = await credentialsManager.GetUnlockedCredentialsDictionary(ConfigSettings["TestCredentialsKey_AzureKeyVault"]); var provider = DeploymentTaskProviderFactory.Create(tasktypeId, _pluginManager.DeploymentTaskProviders); var t = new DeploymentTask(provider, config, credentials); deploymentTasks.Add(t); // perform preview deployments var managedCert = GetMockManagedCertificate("DeploymentTest", "123", PrimaryTestDomain, PrimaryIISRoot); managedCert.CertificatePath = inputFile; foreach (var task in deploymentTasks) { var results = await task.Execute(_log, null, managedCert, CancellationToken.None, new DeploymentContext { }, isPreviewOnly : false); // assert new valid pfx exists in destination Assert.IsTrue(results.All(r => r.IsSuccess)); } }
public async Task <List <ActionResult> > Validate(object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, DeploymentProviderDefinition definition) { var results = new List <ActionResult>(); var requestedStore = settings.Parameters.FirstOrDefault(p => p.Key == "storetype")?.Value.Trim().ToLower(); var friendlyName = settings.Parameters.FirstOrDefault(p => p.Key == "friendlyname")?.Value; if (!string.IsNullOrEmpty(requestedStore)) { // check store name is valid if (!(requestedStore == "default" || requestedStore.ToLower() == "my" || requestedStore == "webhosting")) { results.Add(new ActionResult($"Invalid Certificate Store Name: {requestedStore}", false)); } } return(results); }
public async Task TestPemApacheExport() { var deploymentTasks = new List <DeploymentTask>(); var outputPath = ConfigSettings["TestLocalPath"] + "\\test_pfx_export"; var config = new DeploymentTaskConfig { TaskTypeId = Certify.Providers.DeploymentTasks.Apache.Definition.Id.ToLower(), TaskName = "A test Apache export task", ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("path_cert", outputPath + ".crt"), new ProviderParameterSetting("path_key", outputPath + ".key"), new ProviderParameterSetting("path_chain", outputPath + ".chain") } }; var provider = DeploymentTaskProviderFactory.Create(Certify.Providers.DeploymentTasks.Apache.Definition.Id.ToLower(), _pluginManager.DeploymentTaskProviders); var t = new DeploymentTask(provider, config, null); deploymentTasks.Add(t); // perform preview deployments var managedCert = GetMockManagedCertificate("LocalApacheDeploymentTest", "123", PrimaryTestDomain, PrimaryIISRoot); foreach (var task in deploymentTasks) { var result = await task.Execute(_log, null, managedCert, CancellationToken.None, new DeploymentContext { }, isPreviewOnly : false); } // assert output exists in destination Assert.IsTrue(File.Exists(outputPath + ".crt")); Assert.IsTrue(File.Exists(outputPath + ".key")); Assert.IsTrue(File.Exists(outputPath + ".chain")); File.Delete(outputPath + ".crt"); File.Delete(outputPath + ".key"); File.Delete(outputPath + ".chain"); }
public async Task TestServiceManagerValidation() { var taskTypeId = Certify.Providers.DeploymentTasks.ServiceManager.Definition.Id.ToLower(); var provider = DeploymentTaskProviderFactory.Create(taskTypeId, _pluginManager.DeploymentTaskProviders); var svcName = "aspnet_state"; var restartTaskConfig = new DeploymentTaskConfig { TaskTypeId = taskTypeId, TaskName = "A test service manager task restart", ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("servicename", svcName), new ProviderParameterSetting("action", "restart"), new ProviderParameterSetting("maxwait", "20") } }; var managedCert = GetMockManagedCertificate("Test", "123", PrimaryTestDomain, PrimaryIISRoot); List <ActionResult> results = new List <ActionResult>(); var task = new DeploymentTask(provider, restartTaskConfig, null); var validationResult = await task.TaskProvider.Validate( new DeploymentTaskExecutionParams( _log, null, managedCert, task.TaskConfig, null, isPreviewOnly : false, task.TaskProvider.GetDefinition(), CancellationToken.None, new DeploymentContext { } ) ); Assert.IsFalse(validationResult.Any()); }
public DeploymentTaskExecutionParams( ILog log, ICredentialsManager credentialsManager, object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, bool isPreviewOnly, DeploymentProviderDefinition definition, CancellationToken cancellationToken ) { Log = log; CredentialsManager = credentialsManager; Subject = subject; Settings = settings; Credentials = credentials; IsPreviewOnly = isPreviewOnly; Definition = definition; CancellationToken = cancellationToken; }
/// <summary> /// Execute a local powershell script /// </summary> /// <param name="log"></param> /// <param name="managedCert"></param> /// <param name="settings"></param> /// <param name="credentials"></param> /// <param name="isPreviewOnly"></param> /// <returns></returns> public async Task <List <ActionResult> > Execute( ILog log, object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, bool isPreviewOnly, DeploymentProviderDefinition definition = null ) { definition = GetDefinition(definition); var msg = settings.Parameters.FirstOrDefault(c => c.Key == "message")?.Value; bool.TryParse(settings.Parameters.FirstOrDefault(c => c.Key == "throw")?.Value, out var shouldThrow); if (string.IsNullOrEmpty(msg)) { // fail task log?.Warning($"Mock Task says: <msg not supplied, task will fail>"); return(new List <ActionResult> { new ActionResult("Mock Task message not supplied.", false) }); } else { if (shouldThrow) { throw new System.Exception($"Mock task should throw: {msg}"); } else { log?.Information($"Mock Task says: {msg}"); return(new List <ActionResult> { new ActionResult($"{msg}.", true), new ActionResult($"MockTaskWorkCompleted.", true) }); } } }
public async Task <List <ActionResult> > Execute(ILog log, object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, bool isPreviewOnly, DeploymentProviderDefinition definition) { var managedCert = ManagedCertificate.GetManagedCertificate(subject); try { var webhookConfig = new Shared.Utils.Webhook.WebhookConfig { Url = settings.Parameters.FirstOrDefault(p => p.Key == "url")?.Value, Method = settings.Parameters.FirstOrDefault(p => p.Key == "method")?.Value, ContentType = settings.Parameters.FirstOrDefault(p => p.Key == "contenttype")?.Value, ContentBody = settings.Parameters.FirstOrDefault(p => p.Key == "contentbody")?.Value }; if (!isPreviewOnly) { var webHookResult = await Certify.Shared.Utils.Webhook.SendRequest(webhookConfig, managedCert, managedCert.LastRenewalStatus != RequestState.Error); var msg = $"Webhook invoked: Url: {webhookConfig.Url}, Success: {webHookResult.Success}, StatusCode: {webHookResult.StatusCode}"; log.Information(msg); return(new List <ActionResult> { new ActionResult(msg, true) }); } else { return(await Validate(managedCert, settings, credentials, definition)); } } catch (Exception exp) { return(new List <ActionResult> { new ActionResult("Webhook call failed: " + exp.ToString(), false) }); } }
public Task <List <ActionResult> > Execute(ILog log, object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, bool isPreviewOnly, DeploymentProviderDefinition definition) { throw new System.NotImplementedException(); }
public EditDeploymentTask(DeploymentTaskConfig config) { InitializeComponent(); DeploymentTaskEditor.SetEditItem(config); }
public async Task TestServiceManager() { var deploymentTasks = new List <DeploymentTask>(); var taskTypeId = Certify.Providers.DeploymentTasks.ServiceManager.Definition.Id.ToLower(); var provider = DeploymentTaskProviderFactory.Create(taskTypeId, _pluginManager.DeploymentTaskProviders); var svcName = "aspnet_state"; var restartTaskConfig = new DeploymentTaskConfig { TaskTypeId = taskTypeId, TaskName = "A test service manager task restart", ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("servicename", svcName), new ProviderParameterSetting("action", "restart"), new ProviderParameterSetting("maxwait", "20") } }; deploymentTasks.Add(new DeploymentTask(provider, restartTaskConfig, null)); var stopTaskConfig = new DeploymentTaskConfig { TaskTypeId = taskTypeId, TaskName = "A test service manager task stop", ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("servicename", svcName), new ProviderParameterSetting("action", "stop"), new ProviderParameterSetting("maxwait", "20") } }; deploymentTasks.Add(new DeploymentTask(provider, stopTaskConfig, null)); var startTaskConfig = new DeploymentTaskConfig { TaskTypeId = taskTypeId, TaskName = "A test service manager task start", ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("servicename", svcName), new ProviderParameterSetting("action", "start"), new ProviderParameterSetting("maxwait", "20") } }; deploymentTasks.Add(new DeploymentTask(provider, startTaskConfig, null)); // perform preview deployments var managedCert = GetMockManagedCertificate("Test", "123", PrimaryTestDomain, PrimaryIISRoot); List <ActionResult> results = new List <ActionResult>(); foreach (var task in deploymentTasks) { results.AddRange(await task.Execute(_log, null, managedCert, CancellationToken.None, new DeploymentContext { }, isPreviewOnly: false)); } // assert output exists in destination Assert.IsTrue(results.All(r => r.IsSuccess == true)); }
public async Task <DeploymentProviderDefinition> GetDeploymentProviderDefinition(string id, DeploymentTaskConfig config) { return(await _certifyManager.GetDeploymentProviderDefinition(id, config)); }
private static ActionResult RunLocalScript(ILog log, string command, string args, DeploymentTaskConfig settings, Dictionary <string, string> credentials) { var _log = new StringBuilder(); // https://stackoverflow.com/questions/5519328/executing-batch-file-in-c-sharp var maxWaitTime = 120; var scriptProcessInfo = new ProcessStartInfo(Environment.ExpandEnvironmentVariables(command)) { RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; if (!string.IsNullOrWhiteSpace(args)) { scriptProcessInfo.Arguments = args; } else { _log.AppendLine($"{Definition.Title}: Running script [{command} {args}]"); } try { var process = new Process { StartInfo = scriptProcessInfo }; var logMessages = new StringBuilder(); // capture output streams and add to log process.OutputDataReceived += (obj, a) => { if (a.Data != null) { logMessages.AppendLine(a.Data); } }; process.ErrorDataReceived += (obj, a) => { if (!string.IsNullOrWhiteSpace(a.Data)) { logMessages.AppendLine($"Error: {a.Data}"); } }; try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit((maxWaitTime) * 1000); } catch (Exception exp) { _log.AppendLine("Error Running Script: " + exp.ToString()); } // append output to main log _log.Append(logMessages.ToString()); if (!process.HasExited) { //process still running, kill task process.CloseMainWindow(); _log.AppendLine("Warning: Script ran but took too long to exit and was closed."); return(new ActionResult { IsSuccess = false, Message = _log.ToString() }); } else if (process.ExitCode != 0) { _log.AppendLine("Warning: Script exited with the following ExitCode: " + process.ExitCode); return(new ActionResult { IsSuccess = false, Message = _log.ToString() }); } return(new ActionResult { IsSuccess = true, Message = _log.ToString() }); } catch (Exception exp) { _log.AppendLine("Error: " + exp.ToString()); return(new ActionResult { IsSuccess = false, Message = _log.ToString() }); } }
public Task <List <ActionResult> > Validate(object subject, DeploymentTaskConfig settings, Dictionary <string, string> credentials, DeploymentProviderDefinition definition) { throw new System.NotImplementedException(); }
private static async Task <List <ActionResult> > RunSSHScript(ILog log, string command, string args, DeploymentTaskConfig settings, Dictionary <string, string> credentials) { var sshConfig = SshClient.GetConnectionConfig(settings, credentials); var ssh = new SshClient(sshConfig); var commandList = new List <string> { $"{command} {args}" }; log?.Information($"Executing command via SSH [{sshConfig.Host}:{sshConfig.Port}]"); var scriptResults = await Task.FromResult(ssh.ExecuteCommands(commandList, log)); if (scriptResults.Any(r => r.IsError)) { var firstError = scriptResults.First(c => c.IsError); return(new List <ActionResult> { new ActionResult { IsSuccess = false, Message = $"One or more commands failed: {firstError.Command} :: {firstError.Result}" } }); } else { return(new List <ActionResult> { new ActionResult { IsSuccess = true, Message = "Command Completed" } }); } }
/// <summary> /// Perform validation for a specific deployment task configuration /// </summary> /// <param name="managedCertificate"></param> /// <param name="taskConfig"></param> /// <returns></returns> public async Task <List <ActionResult> > ValidateDeploymentTask(ManagedCertificate managedCertificate, DeploymentTaskConfig taskConfig) { var provider = DeploymentTaskProviderFactory.Create(taskConfig.TaskTypeId.ToLower(), _pluginManager.DeploymentTaskProviders); Dictionary <string, string> credentials = null; if (!string.IsNullOrEmpty(taskConfig.ChallengeCredentialKey)) { credentials = await _credentialsManager.GetUnlockedCredentialsDictionary(taskConfig.ChallengeCredentialKey); } try { var execParams = new DeploymentTaskExecutionParams(null, _credentialsManager, managedCertificate, taskConfig, credentials, true, provider.GetDefinition(), CancellationToken.None, new DeploymentContext { PowershellExecutionPolicy = _serverConfig.PowershellExecutionPolicy }); var validationResult = await provider.Validate(execParams); return(validationResult); } catch (Exception exp) { return(new List <ActionResult> { new ActionResult("Failed to validate task: " + exp.ToString(), false) }); } }
/// <summary> /// Get the current definition for a provider including dynamic elements affected by the given config /// </summary> /// <param name="id"></param> /// <param name="config"></param> /// <returns></returns> public async Task <DeploymentProviderDefinition> GetDeploymentProviderDefinition(string id, DeploymentTaskConfig config = null) { var provider = DeploymentTaskProviderFactory.Create(id, _pluginManager.DeploymentTaskProviders); return(provider.GetDefinition()); }
public async Task <List <ActionResult> > ValidateDeploymentTask(ManagedCertificate managedCertificate, DeploymentTaskConfig taskConfig) { var provider = DeploymentTaskProviderFactory.Create(taskConfig.TaskTypeId.ToLower(), _pluginManager.DeploymentTaskProviders); Dictionary <string, string> credentials = null; if (!string.IsNullOrEmpty(taskConfig.ChallengeCredentialKey)) { credentials = await _credentialsManager.GetUnlockedCredentialsDictionary(taskConfig.ChallengeCredentialKey); } try { var validationResult = await provider.Validate(managedCertificate, taskConfig, credentials, provider.GetDefinition()); return(validationResult); } catch (Exception exp) { return(new List <ActionResult> { new ActionResult("Failed to validate task: " + exp.ToString(), false) }); } }
/// <summary> /// Convert legacy pre/post request scripts, webhooks and deployments to Pre/Post Deployment Tasks /// </summary> /// <param name="managedCertificate"></param> /// <returns></returns> public Tuple <ManagedCertificate, bool> MigrateDeploymentTasks(ManagedCertificate managedCertificate) { bool requiredMigration = false; if (managedCertificate.PreRequestTasks == null) { managedCertificate.PreRequestTasks = new System.Collections.ObjectModel.ObservableCollection <DeploymentTaskConfig>(); } if (managedCertificate.PostRequestTasks == null) { managedCertificate.PostRequestTasks = new System.Collections.ObjectModel.ObservableCollection <DeploymentTaskConfig>(); } if (!string.IsNullOrEmpty(managedCertificate.RequestConfig.PreRequestPowerShellScript)) { //add pre-request script task var task = new DeploymentTaskConfig { Id = Guid.NewGuid().ToString(), TaskTypeId = StandardTaskTypes.POWERSHELL, ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, TaskName = "[Pre-Request Script]", IsFatalOnError = true, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("scriptpath", managedCertificate.RequestConfig.PreRequestPowerShellScript), new ProviderParameterSetting("inputresult", "true") } }; if (!managedCertificate.PreRequestTasks.Any(t => t.TaskName == "[Pre-Request Script]")) { managedCertificate.PreRequestTasks.Insert(0, task); requiredMigration = true; } managedCertificate.RequestConfig.PreRequestPowerShellScript = null; } if (!string.IsNullOrEmpty(managedCertificate.RequestConfig.PostRequestPowerShellScript)) { //add post-request script task var task = new DeploymentTaskConfig { Id = Guid.NewGuid().ToString(), TaskTypeId = StandardTaskTypes.POWERSHELL, ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, TaskName = "[Post-Request Script]", IsFatalOnError = true, TaskTrigger = TaskTriggerType.ON_SUCCESS, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("scriptpath", managedCertificate.RequestConfig.PostRequestPowerShellScript), new ProviderParameterSetting("inputresult", "true") } }; if (!managedCertificate.PostRequestTasks.Any(t => t.TaskName == "[Post-Request Script]")) { managedCertificate.PostRequestTasks.Insert(0, task); requiredMigration = true; } managedCertificate.RequestConfig.PostRequestPowerShellScript = null; } if (!string.IsNullOrEmpty(managedCertificate.RequestConfig.WebhookUrl)) { //add post-request script task for webhook, migrate trigger type to task trigger type var triggerType = TaskTriggerType.ANY_STATUS; if (managedCertificate.RequestConfig.WebhookTrigger == Webhook.ON_NONE) { triggerType = TaskTriggerType.NOT_ENABLED; } else if (managedCertificate.RequestConfig.WebhookTrigger == Webhook.ON_SUCCESS) { triggerType = TaskTriggerType.ON_SUCCESS; } else if (managedCertificate.RequestConfig.WebhookTrigger == Webhook.ON_ERROR) { triggerType = TaskTriggerType.ON_ERROR; } else if (managedCertificate.RequestConfig.WebhookTrigger == Webhook.ON_SUCCESS_OR_ERROR) { triggerType = TaskTriggerType.ANY_STATUS; } var task = new DeploymentTaskConfig { Id = Guid.NewGuid().ToString(), ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL, TaskName = "[Post-Request Webhook]", IsFatalOnError = false, TaskTrigger = triggerType, TaskTypeId = StandardTaskTypes.WEBHOOK, Parameters = new List <ProviderParameterSetting> { new ProviderParameterSetting("url", managedCertificate.RequestConfig.WebhookUrl), new ProviderParameterSetting("method", managedCertificate.RequestConfig.WebhookMethod), new ProviderParameterSetting("contenttype", managedCertificate.RequestConfig.WebhookContentType), new ProviderParameterSetting("contentbody", managedCertificate.RequestConfig.WebhookContentBody) } }; if (!managedCertificate.PostRequestTasks.Any(t => t.TaskName == "[Post-Request Webhook]")) { managedCertificate.PostRequestTasks.Insert(0, task); requiredMigration = true; } managedCertificate.RequestConfig.WebhookUrl = null; managedCertificate.RequestConfig.WebhookTrigger = Webhook.ON_NONE; } // #516 check for any post-request webhooks incorrectly set to be powershell if (managedCertificate.PostRequestTasks?.Any(t => t.TaskTypeId == StandardTaskTypes.POWERSHELL && t.Parameters?.Any(p => p.Key == "url") == true) == true) { var webhookTask = managedCertificate.PostRequestTasks.First(t => t.TaskTypeId == StandardTaskTypes.POWERSHELL && t.Parameters?.Any(p => p.Key == "url") == true); if (webhookTask != null) { webhookTask.TaskTypeId = StandardTaskTypes.WEBHOOK; requiredMigration = true; } } return(new Tuple <ManagedCertificate, bool>(managedCertificate, requiredMigration)); }