public override void ExecuteCmdlet() { Guid subscriptionIdGuid; string subscriptionName = null; string subscriptionId = null; if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription))) { if (Guid.TryParse(Subscription, out subscriptionIdGuid)) { subscriptionId = Subscription; } else { subscriptionName = Subscription; } } if (ClientAssertionParameterSet.Equals(ParameterSetName, StringComparison.OrdinalIgnoreCase)) { string suppressWarningOrErrorValue = System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME); bool.TryParse(suppressWarningOrErrorValue, out bool suppressWarningOrError); if (!suppressWarningOrError) { WriteWarning("The feature related to parameter name 'FederatedToken' is under preview."); } } var azureAccount = new AzureAccount(); switch (ParameterSetName) { case AccessTokenParameterSet: azureAccount.Type = AzureAccount.AccountType.AccessToken; azureAccount.Id = AccountId; azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken); azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken); azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken); break; case ServicePrincipalCertificateParameterSet: case ServicePrincipalCertificateFileParameterSet: case ServicePrincipalParameterSet: azureAccount.Type = AzureAccount.AccountType.ServicePrincipal; break; case ClientAssertionParameterSet: azureAccount.Type = "ClientAssertion"; break; case ManagedServiceParameterSet: azureAccount.Type = AzureAccount.AccountType.ManagedService; azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : $"{Constants.DefaultMsiAccountIdPrefix}{DefaultManagedServicePort}"; break; default: //Support username + password for both Windows PowerShell and PowerShell 6+ azureAccount.Type = AzureAccount.AccountType.User; break; } SecureString password = null; if (Credential != null) { azureAccount.Id = Credential.UserName; password = Credential.Password; } if (UseDeviceAuthentication.IsPresent) { azureAccount.SetProperty("UseDeviceAuth", "true"); } if (azureAccount.Type == AzureAccount.AccountType.User && password != null) { azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true"); } if (!string.IsNullOrEmpty(ApplicationId)) { azureAccount.Id = ApplicationId; } if (!string.IsNullOrWhiteSpace(CertificateThumbprint)) { azureAccount.SetThumbprint(CertificateThumbprint); } if (!string.IsNullOrWhiteSpace(CertificatePath)) { var resolvedPath = this.SessionState.Path.GetResolvedPSPathFromPSPath(CertificatePath).FirstOrDefault()?.Path; if (string.IsNullOrEmpty(resolvedPath)) { var parametersLog = $"- Invalid certificate path :'{CertificatePath}'."; throw new InvalidOperationException(parametersLog); } azureAccount.SetProperty(AzureAccount.Property.CertificatePath, resolvedPath); if (CertificatePassword != null) { azureAccount.SetProperty(AzureAccount.Property.CertificatePassword, CertificatePassword.ConvertToString()); } } if ((ParameterSetName == ServicePrincipalCertificateParameterSet || ParameterSetName == ServicePrincipalCertificateFileParameterSet) && SendCertificateChain) { azureAccount.SetProperty(AzureAccount.Property.SendCertificateChain, SendCertificateChain.ToString()); bool supressWarningOrError = false; try { supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); } catch { //if value of env variable is invalid, use default value of supressWarningOrError } if (!supressWarningOrError) { WriteWarning(Resources.PreviewFunctionMessage); } } if (!string.IsNullOrEmpty(Tenant)) { azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant); } if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && password != null) { azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString()); if (GetContextModificationScope() == ContextModificationScope.CurrentUser) { var file = AzureSession.Instance.ARMProfileFile; var directory = AzureSession.Instance.ARMProfileDirectory; WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory)); } } if (azureAccount.Type == "ClientAssertion" && FederatedToken != null) { password = SecureStringExtensions.ConvertToSecureString(FederatedToken); azureAccount.SetProperty("ClientAssertion", FederatedToken); if (GetContextModificationScope() == ContextModificationScope.CurrentUser) { var file = AzureSession.Instance.ARMProfileFile; var directory = AzureSession.Instance.ARMProfileDirectory; WriteWarning(string.Format(Resources.ClientAssertionWarning, file, directory)); } } var resourceId = PreProcessAuthScope(); if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in")) { if (AzureRmProfileProvider.Instance.Profile == null) { InitializeProfileProvider(); } if (!AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out CommonUtilities commonUtilities)) { commonUtilities = new CommonUtilities(); AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => commonUtilities); } if (!commonUtilities.IsDesktopSession() && IsUsingInteractiveAuthentication()) { WriteWarning(Resources.InteractiveAuthNotSupported); return; } SetContextWithOverwritePrompt((localProfile, profileClient, name) => { bool shouldPopulateContextList = true; if (this.IsParameterBound(c => c.SkipContextPopulation)) { shouldPopulateContextList = false; } profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message))); profileClient.DebugLog = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message))); var task = new Task <AzureRmProfile>(() => profileClient.Login( azureAccount, _environment, Tenant, subscriptionId, subscriptionName, password, SkipValidation, WriteWarningEvent, //Could not use WriteWarning directly because it may be in worker thread name, shouldPopulateContextList, MaxContextPopulation, resourceId)); task.Start(); while (!task.IsCompleted) { HandleActions(); Thread.Yield(); } HandleActions(); try { //Must not use task.Result as it wraps inner exception into AggregateException var result = (PSAzureProfile)task.GetAwaiter().GetResult(); WriteObject(result); } catch (AuthenticationFailedException ex) { if (IsUnableToOpenWebPageError(ex)) { WriteWarning(Resources.InteractiveAuthNotSupported); WriteDebug(ex.ToString()); } else { if (IsUsingInteractiveAuthentication()) { //Display only if user is using Interactive auth WriteWarning(Resources.SuggestToUseDeviceCodeAuth); } WriteDebug(ex.ToString()); throw; } } }); } }
public async Task CreateWithSimpleParameters(IAsyncCmdlet adapter) { var parameters = new Parameters(this); var client = new WebClient(DefaultContext); var output = await client.RunAsync(client.SubscriptionId, parameters, adapter); output.SiteConfig = WebsitesClient .WrappedWebsitesClient .WebApps() .GetConfiguration(output.ResourceGroup, output.Name) .ConvertToSiteConfig(); try { var appSettings = WebsitesClient .WrappedWebsitesClient .WebApps() .ListApplicationSettings(output.ResourceGroup, output.Name); output.SiteConfig.AppSettings = appSettings .Properties .Select(s => new NameValuePair { Name = s.Key, Value = s.Value }) .ToList(); var connectionStrings = WebsitesClient.WrappedWebsitesClient.WebApps().ListConnectionStrings( output.ResourceGroup, output.Name); output.SiteConfig.ConnectionStrings = connectionStrings .Properties .Select(s => new ConnStringInfo() { Name = s.Key, ConnectionString = s.Value.Value, Type = s.Value.Type }).ToList(); } catch { //ignore if this call fails as it will for reader RBAC } string userName = null, password = null; try { var scmHostName = output.EnabledHostNames.FirstOrDefault(s => s.Contains(".scm.")); if (!string.IsNullOrWhiteSpace(scmHostName)) { var profile = await WebsitesClient.WrappedWebsitesClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(output.ResourceGroup, output.Name, new CsmPublishingProfileOptions { Format = "WebDeploy" }); var doc = new XmlDocument(); doc.Load(profile); userName = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userName").Value; password = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userPWD").Value; var newOutput = new PSSite(output) { GitRemoteUri = $"https://{scmHostName}", GitRemoteUsername = userName, GitRemotePassword = SecureStringExtensions.ConvertToSecureString(password) }; output = newOutput; var git = new GitCommand(SessionState.Path, GitRepositoryPath); var repository = await git.VerifyGitRepository(); if (repository != null) { if (!await git.CheckExistence()) { adapter.WriteWarning(git.InstallationInstructions); } else if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { await git.AddRemoteRepository("azure", $"https://{userName}:{password}@{scmHostName}"); adapter.WriteVerbose(Properties.Resources.GitRemoteMessage); newOutput.GitRemoteName = "azure"; } } } } catch (Exception exception) { // do not write errors for problems with adding git repository var repoPath = GitRepositoryPath ?? SessionState?.Path?.CurrentFileSystemLocation?.Path; adapter.WriteWarning(string.Format( Properties.Resources.GitRemoteAddFailure, repoPath, exception.Message)); } adapter.WriteObject(output); }
public async Task CreateWithSimpleParameters(ICmdletAdapter adapter) { ResourceGroupName = ResourceGroupName ?? Name; AppServicePlan = AppServicePlan ?? Name; string planResourceGroup = ResourceGroupName; string planName = AppServicePlan; var rgStrategy = ResourceGroupStrategy.CreateResourceGroupConfig(ResourceGroupName); ResourceConfig <ResourceGroup> planRG = rgStrategy; if (MyInvocation.BoundParameters.ContainsKey(nameof(AppServicePlan))) { if (!TryGetServerFarmFromResourceId(AppServicePlan, out planResourceGroup, out planName)) { planResourceGroup = ResourceGroupName; planName = AppServicePlan; } planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } else { var farm = await GetDefaultServerFarm(Location); if (farm != null) { planResourceGroup = farm.ResourceGroup; planName = farm.Name; planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup); } } var farmStrategy = planRG.CreateServerFarmConfig(planResourceGroup, planName); var siteStrategy = rgStrategy.CreateSiteConfig(farmStrategy, Name); var client = new WebClient(DefaultContext); var current = await siteStrategy.GetStateAsync(client, default(CancellationToken)); if (!MyInvocation.BoundParameters.ContainsKey(nameof(Location))) { Location = current.GetLocation(siteStrategy) ?? "East US"; } var engine = new SdkEngine(DefaultContext.Subscription.Id); var target = siteStrategy.GetTargetState(current, engine, Location); var endState = await siteStrategy.UpdateStateAsync(client, target, default(CancellationToken), adapter, adapter.ReportTaskProgress); var output = endState.Get(siteStrategy) ?? current.Get(siteStrategy); output.SiteConfig = WebsitesClient.WrappedWebsitesClient.WebApps().GetConfiguration(output.ResourceGroup, output.Name).ConvertToSiteConfig(); try { var appSettings = WebsitesClient.WrappedWebsitesClient.WebApps().ListApplicationSettings(output.ResourceGroup, output.Name); output.SiteConfig.AppSettings = appSettings.Properties.Select(s => new NameValuePair { Name = s.Key, Value = s.Value }).ToList(); var connectionStrings = WebsitesClient.WrappedWebsitesClient.WebApps().ListConnectionStrings(output.ResourceGroup, output.Name); output.SiteConfig.ConnectionStrings = connectionStrings .Properties .Select(s => new ConnStringInfo() { Name = s.Key, ConnectionString = s.Value.Value, Type = s.Value.Type }).ToList(); } catch { //ignore if this call fails as it will for reader RBAC } string userName = null, password = null; try { var scmHostName = output.EnabledHostNames.FirstOrDefault(s => s.Contains(".scm.")); if (!string.IsNullOrWhiteSpace(scmHostName)) { var profile = await WebsitesClient.WrappedWebsitesClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(output.ResourceGroup, output.Name, new CsmPublishingProfileOptions { Format = "WebDeploy" }); var doc = new XmlDocument(); doc.Load(profile); userName = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userName").Value; password = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userPWD").Value; var newOutput = new PSSite(output) { GitRemoteUri = $"https://{scmHostName}", GitRemoteUsername = userName, GitRemotePassword = SecureStringExtensions.ConvertToSecureString(password) }; output = newOutput; var git = new GitCommand(adapter.SessionState.Path, GitRepositoryPath); var repository = await git.VerifyGitRepository(); if (repository != null) { if (!await git.CheckExistence()) { adapter.WriteWarningAsync(git.InstallationInstructions); } else if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { await git.AddRemoteRepository("azure", $"https://{userName}:{password}@{scmHostName}"); adapter.WriteVerboseAsync(Microsoft.Azure.Commands.WebApps.Properties.Resources.GitRemoteMessage); newOutput.GitRemoteName = "azure"; } } } } catch (Exception exception) { // do not write errors for problems with adding git repository var repoPath = GitRepositoryPath ?? adapter?.SessionState?.Path?.CurrentFileSystemLocation?.Path; adapter.WriteWarningAsync(String.Format(Microsoft.Azure.Commands.WebApps.Properties.Resources.GitRemoteAddFailure, repoPath, exception.Message)); } adapter.WriteObjectAsync(output); }
public void VerifyThatConvertToSecureStringThrowsArgumentException() { Assert.Throws <ArgumentException>(() => SecureStringExtensions.ConvertToSecureString(null)); Assert.Throws <ArgumentException>(() => SecureStringExtensions.ConvertToSecureString(string.Empty)); }