/// <summary> /// The storage service blob endpoint format. /// </summary> private static string StorageBlobEndpointFormat(this IAzureEnvironment environment) { return(environment.EndpointFormatFor("blob")); }
public IList <AzureSubscription> ListAllSubscriptionsForTenant(IAccessToken accessToken, IAzureAccount account, IAzureEnvironment environment) { using (var subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers())) { return((subscriptionClient.ListAllSubscriptions()? .Select(s => s.ToAzureSubscription(account, environment, accessToken.TenantId))).ToList() ?? new List <AzureSubscription>()); } }
public void AddsEnvironmentMultipleTimes() { Mock <ICommandRuntime> commandRuntimeMock = new Mock <ICommandRuntime>(); SetupConfirmation(commandRuntimeMock); var cmdlet = new AddAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Katal", PublishSettingsFileUrl = "http://microsoft.com", EnableAdfsAuthentication = true, }; var dict = new Dictionary <string, object>(); dict["PublishSettingsFileUrl"] = "http://microsoft.com"; dict["EnableAdfsAuthentication"] = true; cmdlet.SetBoundParameters(dict); cmdlet.SetParameterSet("Name"); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Once()); IAzureEnvironment env = AzureRmProfileProvider.Instance.Profile.GetEnvironment("KaTaL"); Assert.Equal(env.Name, cmdlet.Name); Assert.True(env.OnPremise); Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); // Execute the same without PublishSettingsFileUrl and make sure the first value is preserved var cmdlet2 = new AddAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Katal", EnableAdfsAuthentication = true, }; dict.Clear(); dict["EnableAdfsAuthentication"] = true; cmdlet2.SetBoundParameters(dict); cmdlet2.SetParameterSet("Name"); cmdlet2.InvokeBeginProcessing(); cmdlet2.ExecuteCmdlet(); cmdlet2.InvokeEndProcessing(); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Exactly(2)); IAzureEnvironment env2 = AzureRmProfileProvider.Instance.Profile.GetEnvironment("KaTaL"); Assert.Equal(env2.Name, cmdlet2.Name); Assert.True(env2.OnPremise); Assert.Equal(env2.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); var cmdlet3 = new AddAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Katal", }; dict.Clear(); cmdlet3.SetBoundParameters(dict); cmdlet3.SetParameterSet("Name"); cmdlet3.InvokeBeginProcessing(); cmdlet3.ExecuteCmdlet(); cmdlet3.InvokeEndProcessing(); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Exactly(3)); IAzureEnvironment env3 = AzureRmProfileProvider.Instance.Profile.GetEnvironment("KaTaL"); Assert.Equal(env3.Name, cmdlet3.Name); Assert.Equal(env3.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); }
public IList <AzureSubscription> ListAllSubscriptionsForTenant(IAccessToken accessToken, IAzureAccount account, IAzureEnvironment environment) { IList <AzureSubscription> result = null; SubscriptionClientFallBack((client) => result = client?.ListAllSubscriptionsForTenant(accessToken, account, environment), WriteWarningMessage); return(result); }
/// <summary> /// Check if this environment equals another environment /// </summary> /// <param name="environment">this environment</param> /// <param name="other">The environment to compare to</param> /// <returns>Treu fi the elements of the environment are equal, otherwise false</returns> public static bool IsEqual(this IAzureEnvironment environment, IAzureEnvironment other) { return((environment == null && other == null) || environment.CheckExtensionsEqual(other)); }
private string GetResourceId(string resourceIdorEndpointName, IAzureEnvironment environment) { return(environment.GetEndpoint(resourceIdorEndpointName) ?? resourceIdorEndpointName); }
private bool TryGetTenantSubscription(IAccessToken accessToken, IAzureAccount account, IAzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, out IAzureSubscription subscription, out IAzureTenant tenant) { using (var subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers())) { Subscription subscriptionFromServer = null; try { if (subscriptionId != null) { subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId); } else { var subscriptions = (subscriptionClient.ListAllSubscriptions().ToList() ?? new List <Subscription>()) .Where(s => "enabled".Equals(s.State.ToString(), StringComparison.OrdinalIgnoreCase) || "warned".Equals(s.State.ToString(), StringComparison.OrdinalIgnoreCase)); account.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.Select(i => i.SubscriptionId).ToArray()); if (subscriptions.Any()) { if (subscriptionName != null) { subscriptionFromServer = subscriptions.FirstOrDefault( s => s.DisplayName.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase)); } else { if (subscriptions.Count() > 1) { WriteWarningMessage(string.Format( "TenantId '{0}' contains more than one active subscription. First one will be selected for further use. " + "To select another subscription, use Set-AzContext.", tenantId)); } subscriptionFromServer = subscriptions.First(); } } } } catch (CloudException ex) { WriteWarningMessage(ex.Message); } if (subscriptionFromServer != null) { subscription = new AzureSubscription { Id = subscriptionFromServer.SubscriptionId, Name = subscriptionFromServer.DisplayName, State = subscriptionFromServer.State.ToString() }; subscription.SetAccount(accessToken.UserId); subscription.SetEnvironment(environment.Name); subscription.SetTenant(accessToken.TenantId); tenant = new AzureTenant(); tenant.Id = accessToken.TenantId; return(true); } subscription = null; if (accessToken != null && accessToken.TenantId != null) { tenant = new AzureTenant(); tenant.Id = accessToken.TenantId; return(true); } tenant = null; return(false); } }
/// <summary> /// Translate the given Uri into the appropriate Uri for the current environment. /// </summary> /// <param name="environment">The current Azure Environment</param> /// <param name="baseEndpoint">The Uri to transform</param> /// <returns>The Uri, with naseUri appropriately altered for the current Azure environment</returns> public static Uri GetUriFromBaseRequestUri(this IAzureEnvironment environment, Uri baseEndpoint) { if (null == environment) { throw new ArgumentNullException(nameof(environment)); } var baseEnvironment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud]; if (baseEnvironment.GraphUrl.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchHost(environment.GraphUrl)); } if (baseEnvironment.ResourceManagerUrl.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchHost(environment.ResourceManagerUrl)); } if (baseEnvironment.ServiceManagementUrl.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchHost(environment.ServiceManagementUrl)); } if (environment.ExtendedProperties.ContainsKey(AzureEnvironment.ExtendedEndpoint.MicrosoftGraphEndpointResourceId) && baseEnvironment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.MicrosoftGraphEndpointResourceId].IsMatch(baseEndpoint)) { return(baseEndpoint.PatchHost(environment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.MicrosoftGraphEndpointResourceId])); } if (environment.ExtendedProperties.ContainsKey(AzureEnvironment.ExtendedEndpoint.MicrosoftGraphUrl) && baseEnvironment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.MicrosoftGraphUrl].IsMatch(baseEndpoint)) { return(baseEndpoint.PatchHost(environment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.MicrosoftGraphUrl])); } if (environment.ExtendedProperties.ContainsKey(AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpoint) && baseEnvironment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpoint].IsMatch(baseEndpoint)) { return(baseEndpoint.PatchHost(environment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpoint])); } if (!string.IsNullOrWhiteSpace(environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix) && baseEnvironment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchDnsSuffix(environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix)); } if (!string.IsNullOrWhiteSpace(environment.AzureDataLakeStoreFileSystemEndpointSuffix) && baseEnvironment.AzureDataLakeStoreFileSystemEndpointSuffix.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchDnsSuffix(environment.AzureDataLakeStoreFileSystemEndpointSuffix)); } if (!string.IsNullOrWhiteSpace(environment.AzureKeyVaultDnsSuffix) && baseEnvironment.AzureKeyVaultDnsSuffix.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchDnsSuffix(environment.AzureKeyVaultDnsSuffix)); } if (!string.IsNullOrWhiteSpace(environment.SqlDatabaseDnsSuffix) && baseEnvironment.SqlDatabaseDnsSuffix.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchDnsSuffix(environment.SqlDatabaseDnsSuffix)); } if (!string.IsNullOrWhiteSpace(environment.StorageEndpointSuffix) && baseEnvironment.StorageEndpointSuffix.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchDnsSuffix(environment.StorageEndpointSuffix)); } if (!string.IsNullOrWhiteSpace(environment.TrafficManagerDnsSuffix) && baseEnvironment.TrafficManagerDnsSuffix.IsMatch(baseEndpoint)) { return(baseEndpoint.PatchDnsSuffix(environment.TrafficManagerDnsSuffix)); } if (environment.ExtendedProperties.ContainsKey(AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointSuffix) && baseEnvironment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointSuffix].IsMatch(baseEndpoint)) { return(baseEndpoint.PatchDnsSuffix(environment.ExtendedProperties[AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointSuffix])); } return(baseEndpoint); }
public void AddEnvironmentUpdatesContext() { var cmdlet = new AddAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock, Name = "Katal", ARMEndpoint = "https://management.azure.com/", AzureKeyVaultDnsSuffix = "vault.local.azurestack.external", AzureKeyVaultServiceEndpointResourceId = "https://vault.local.azurestack.external" }; var dict = new Dictionary <string, object> { { "ARMEndpoint", "https://management.azure.com/" }, { "AzureKeyVaultDnsSuffix", "vault.local.azurestack.external" }, { "AzureKeyVaultServiceEndpointResourceId", "https://vault.local.azurestack.external" } }; cmdlet.SetBoundParameters(dict); cmdlet.SetParameterSet("ARMEndpoint"); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); commandRuntimeMock = new MockCommandRuntime(); var profileClient = new RMProfileClient(AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>()); IAzureEnvironment env = AzureRmProfileProvider.Instance.Profile.Environments.First((e) => string.Equals(e.Name, "KaTaL", StringComparison.OrdinalIgnoreCase)); Assert.Equal(env.Name, cmdlet.Name); Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix), dict["AzureKeyVaultDnsSuffix"]); Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId), dict["AzureKeyVaultServiceEndpointResourceId"]); var cmdlet1 = new ConnectAzureRmAccountCommand(); cmdlet1.CommandRuntime = commandRuntimeMock; cmdlet1.Environment = "Katal"; dict.Clear(); dict = new Dictionary <string, object> { { "Environment", cmdlet1.Environment } }; cmdlet1.SetBoundParameters(dict); cmdlet1.InvokeBeginProcessing(); cmdlet1.ExecuteCmdlet(); cmdlet1.InvokeEndProcessing(); commandRuntimeMock = new MockCommandRuntime(); Assert.NotNull(AzureRmProfileProvider.Instance.Profile.DefaultContext); Assert.Equal(AzureRmProfileProvider.Instance.Profile.DefaultContext.Environment.Name, cmdlet1.Environment); var cmdlet2 = new AddAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock, Name = "Katal", ARMEndpoint = "https://management.azure.com/", AzureKeyVaultDnsSuffix = "adminvault.local.azurestack.external", AzureKeyVaultServiceEndpointResourceId = "https://adminvault.local.azurestack.external" }; dict.Clear(); dict = new Dictionary <string, object> { { "ARMEndpoint", "https://management.azure.com/" }, { "AzureKeyVaultDnsSuffix", "adminvault.local.azurestack.external" }, { "AzureKeyVaultServiceEndpointResourceId", "https://adminvault.local.azurestack.external" } }; cmdlet2.SetBoundParameters(dict); cmdlet2.SetParameterSet("ARMEndpoint"); cmdlet2.InvokeBeginProcessing(); cmdlet2.ExecuteCmdlet(); cmdlet2.InvokeEndProcessing(); profileClient = new RMProfileClient(AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>()); env = AzureRmProfileProvider.Instance.Profile.Environments.First((e) => string.Equals(e.Name, "KaTaL", StringComparison.OrdinalIgnoreCase)); Assert.Equal(env.Name, cmdlet.Name); Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix), dict["AzureKeyVaultDnsSuffix"]); Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId), dict["AzureKeyVaultServiceEndpointResourceId"]); var context = AzureRmProfileProvider.Instance.Profile.DefaultContext; Assert.NotNull(context); Assert.NotNull(context.Environment); Assert.Equal(context.Environment.Name, env.Name); Assert.Equal(context.Environment.AzureKeyVaultDnsSuffix, env.AzureKeyVaultDnsSuffix); Assert.Equal(context.Environment.AzureKeyVaultServiceEndpointResourceId, env.AzureKeyVaultServiceEndpointResourceId); }
/// <summary> /// Executes the set subscription cmdlet operation. /// </summary> public override void ExecuteCmdlet() { IAzureSubscription subscription = null; if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName)) { subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId)); Environment = subscription.GetEnvironment(); } else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName)) { subscription = ProfileClient.GetSubscription(SubscriptionName); Environment = subscription.GetEnvironment(); } else { subscription = new AzureSubscription(); subscription.Id = SubscriptionId; subscription.Name = SubscriptionName; } IAzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint); if (environment == null) { var profileClient = new ProfileClient(Profile); environment = profileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint); } if (environment == null) { throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not " + "match existing environment. Please use Environment parameter."); } else { subscription.SetEnvironment(environment.Name); } if (ServiceEndpoint != null || ResourceManagerEndpoint != null) { WriteWarning("Please use Environment parameter to specify subscription environment. This " + "warning will be converted into an error in the upcoming release."); } if (Certificate != null) { ProfileClient.ImportCertificate(Certificate); subscription.SetAccount(Certificate.Thumbprint); AzureAccount account = new AzureAccount { Id = Certificate.Thumbprint, Type = AzureAccount.AccountType.Certificate }; account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString()); ProfileClient.AddOrSetAccount(account); if (subscription.GetAccount() == null) { subscription.SetAccount(account.Id); } } if (subscription.GetAccount() == null) { throw new ArgumentException("Certificate is required for creating a new subscription."); } if (!string.IsNullOrEmpty(CurrentStorageAccountName) || Context != null) { ProfileClient.GetAccount(subscription.GetAccount()); if (Profile.Context != null && Profile.Context.Subscription != null && Profile.Context.Subscription.Id == subscription.Id) { GeneralUtilities.ClearCurrentStorageAccount(); } var context = new AzureContext(subscription, ProfileClient.GetAccount(subscription.GetAccount()), ProfileClient.GetEnvironmentOrDefault(subscription.GetEnvironment())); if (Context != null) { context.SetCurrentStorageAccount(Context); } else { var client = AzureSession.Instance.ClientFactory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement); var account = StorageUtilities.GenerateCloudStorageAccount(client, CurrentStorageAccountName); context.SetCurrentStorageAccount(account.ToString(true)); } } subscription = ProfileClient.AddOrSetSubscription(subscription); if (PassThru) { WriteObject(subscription); } }
public void SetEnvironmentForStack() { Mock <ICommandRuntime> commandRuntimeMock = new Mock <ICommandRuntime>(); SetupConfirmation(commandRuntimeMock); var cmdlet = new SetAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Stack", ARMEndpoint = "https://management.local.azurestack.external/" }; Mock <EnvironmentHelper> envHelperMock = new Mock <EnvironmentHelper>(); MetadataResponse metadataEndpoints = new MetadataResponse { GalleryEndpoint = "https://galleryendpoint", GraphEndpoint = "https://graphendpoint", PortalEndpoint = "https://portalendpoint", authentication = new Authentication { Audiences = new[] { "audience1", "audience2" }, LoginEndpoint = "https://loginendpoint" } }; envHelperMock.Setup(f => f.RetrieveMetaDataEndpoints(It.IsAny <string>())).ReturnsAsync(metadataEndpoints); envHelperMock.Setup(f => f.RetrieveDomain(It.IsAny <string>())).Returns("domain"); cmdlet.EnvHelper = envHelperMock.Object; cmdlet.SetParameterSet("ARMEndpoint"); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Once()); IAzureEnvironment env = AzureRmProfileProvider.Instance.Profile.GetEnvironment("Stack"); Assert.Equal(env.Name, cmdlet.Name); Assert.Equal(cmdlet.ARMEndpoint, env.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager)); Assert.Equal("https://loginendpoint/", env.GetEndpoint(AzureEnvironment.Endpoint.ActiveDirectory)); Assert.Equal("audience1", env.GetEndpoint(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)); Assert.Equal("https://graphendpoint", env.GetEndpoint(AzureEnvironment.Endpoint.GraphEndpointResourceId)); envHelperMock.Verify(f => f.RetrieveDomain(It.IsAny <string>()), Times.Once); envHelperMock.Verify(f => f.RetrieveMetaDataEndpoints(It.IsAny <string>()), Times.Once); // Update onpremise to true var cmdlet2 = new SetAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Stack", EnableAdfsAuthentication = true }; cmdlet2.MyInvocation.BoundParameters.Add("Name", "Stack"); cmdlet2.MyInvocation.BoundParameters.Add("EnableAdfsAuthentication", true); cmdlet2.InvokeBeginProcessing(); cmdlet2.ExecuteCmdlet(); cmdlet2.InvokeEndProcessing(); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Exactly(2)); IAzureEnvironment env2 = AzureRmProfileProvider.Instance.Profile.GetEnvironment("stack"); Assert.Equal(env2.Name, cmdlet2.Name); Assert.Equal(env2.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); Assert.True(env2.OnPremise); // Update gallery endpoint var cmdlet3 = new SetAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Stack", GalleryEndpoint = "http://galleryendpoint.com", }; cmdlet3.MyInvocation.BoundParameters.Add("Name", "stack"); cmdlet3.MyInvocation.BoundParameters.Add("GalleryEndpoint", "http://galleryendpoint.com"); cmdlet3.InvokeBeginProcessing(); cmdlet3.ExecuteCmdlet(); cmdlet3.InvokeEndProcessing(); // Ensure gallery endpoint is updated and OnPremise value is preserved commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Exactly(3)); IAzureEnvironment env3 = AzureRmProfileProvider.Instance.Profile.GetEnvironment("stack"); Assert.Equal(env3.Name, cmdlet3.Name); Assert.Equal(env3.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); Assert.True(env3.OnPremise); Assert.Equal(env3.GetEndpoint(AzureEnvironment.Endpoint.Gallery), cmdlet3.GalleryEndpoint); }
public AzureRmProfile Login( IAzureAccount account, IAzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, SecureString password, bool skipValidation, Action <string> promptAction, string name = null) { IAzureSubscription newSubscription = null; IAzureTenant newTenant = null; string promptBehavior = (password == null && account.Type != AzureAccount.AccountType.AccessToken && !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) ? ShowDialog.Always : ShowDialog.Never; if (skipValidation) { if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId)) { throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing); } newSubscription = new AzureSubscription { Id = subscriptionId }; newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId); newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id); newTenant = new AzureTenant { Id = tenantId }; } else { // (tenant and subscription are present) OR // (tenant is present and subscription is not provided) if (!string.IsNullOrEmpty(tenantId)) { var token = AcquireAccessToken( account, environment, tenantId, password, promptBehavior, promptAction); if (TryGetTenantSubscription( token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant)) { account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() }); } } // (tenant is not provided and subscription is present) OR // (tenant is not provided and subscription is not provided) else { var tenants = ListAccountTenants(account, environment, password, promptBehavior, promptAction) .Select(s => s.Id.ToString()).ToList(); account.SetProperty(AzureAccount.Property.Tenants, null); string accountId = null; foreach (var tenant in tenants) { IAzureTenant tempTenant; IAzureSubscription tempSubscription; IAccessToken token = null; try { token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null); if (accountId == null) { accountId = account.Id; account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase)) { account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else { // if account ID is different from the first tenant account id we need to ignore current tenant WriteWarningMessage(string.Format( ProfileMessages.AccountIdMismatch, account.Id, tenant, accountId)); account.Id = accountId; token = null; } } catch { WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant)); } if (token != null && newTenant == null && TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant)) { // If no subscription found for the given token/tenant // discard tempTenant value unless current token/tenant is the last one. if (tempSubscription != null || tenant.Equals(tenants[tenants.Count - 1])) { newTenant = tempTenant; newSubscription = tempSubscription; } } } } } if (newSubscription == null) { if (subscriptionId != null) { throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId)); } else if (subscriptionName != null) { throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName)); } var newContext = new AzureContext(account, environment, newTenant); if (!_profile.TrySetDefaultContext(name, newContext)) { WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString())); } } else { var newContext = new AzureContext(newSubscription, account, environment, newTenant); if (!_profile.TrySetDefaultContext(name, newContext)) { WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString())); } if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase)) { WriteWarningMessage(string.Format( ProfileMessages.SelectedSubscriptionNotActive, newSubscription.State)); } } _profile.DefaultContext.TokenCache = _cache; return(_profile.ToProfile()); }
/// <summary> /// Get the endpoint for the file service for the given storage account in this environment /// </summary> /// <param name="environment">The environment containing the storage account</param> /// <param name="storageAccountName">The name of the storage account</param> /// <param name="useHttps">True if https should be use din communicating with the storage service, otherwise false</param> /// <returns>The Uri of the file service for the given service in the given environment</returns> public static Uri GetStorageFileEndpoint(this IAzureEnvironment environment, string storageAccountName, bool useHttps = true) { return(new Uri(string.Format(environment.StorageFileEndpointFormat(), useHttps ? "https" : "http", storageAccountName))); }
/// <summary> /// The storage service file endpoint format. /// </summary> private static string StorageFileEndpointFormat(this IAzureEnvironment environment) { return(environment.EndpointFormatFor("file")); }
public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { IAccessToken token; var cache = tokenCache as TokenCache; if (cache == null) { cache = TokenCache.DefaultShared; } Task <IAccessToken> authToken; if (Builder.Authenticator.TryAuthenticate(account, environment, tenant, password, promptBehavior, Task.FromResult(promptAction), tokenCache, resourceId, out authToken)) { return(authToken.ConfigureAwait(false).GetAwaiter().GetResult()); } var configuration = GetAdalConfiguration(environment, tenant, resourceId, cache); TracingAdapter.Information( Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); if (account != null && account.Type == AzureAccount.AccountType.ManagedService) { token = GetManagedServiceToken(account, environment, tenant, resourceId); } else if (account != null && environment != null && account.Type == AzureAccount.AccountType.AccessToken) { var rawToken = new RawAccessToken { TenantId = tenant, UserId = account.Id, LoginType = AzureAccount.AccountType.AccessToken }; if ((string.Equals(resourceId, environment.AzureKeyVaultServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) || string.Equals(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) && account.IsPropertySet(AzureAccount.Property.KeyVaultAccessToken)) { rawToken.AccessToken = account.GetProperty(AzureAccount.Property.KeyVaultAccessToken); } else if ((string.Equals(resourceId, environment.GraphEndpointResourceId, StringComparison.OrdinalIgnoreCase) || string.Equals(AzureEnvironment.Endpoint.GraphEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) && account.IsPropertySet(AzureAccount.Property.GraphAccessToken)) { rawToken.AccessToken = account.GetProperty(AzureAccount.Property.GraphAccessToken); } else if ((string.Equals(resourceId, environment.ActiveDirectoryServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) || string.Equals(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) && account.IsPropertySet(AzureAccount.Property.AccessToken)) { rawToken.AccessToken = account.GetAccessToken(); } else { throw new InvalidOperationException(string.Format(Resources.AccessTokenResourceNotFound, resourceId)); } token = rawToken; } else if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) { var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint); token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type); } else { token = TokenProvider.GetAccessToken(configuration, promptBehavior, promptAction, account.Id, password, account.Type); } account.Id = token.UserId; return(token); }
/// <summary> /// Get non-endpoint values of the environment, such as resource strings and dns suffixes for servides. /// </summary> /// <param name="environment">The environment to check for the given property</param> /// <param name="endpointName">The name of the property to check for</param> /// <param name="propertyValue">The value of the property, if found in the environment, or null if not found</param> /// <returns>True if the property value is found in the environment, otherwise false.</returns> public static bool TryGetEndpointString(this IAzureEnvironment environment, string endpointName, out string propertyValue) { propertyValue = null; if (environment != null) { switch (endpointName) { case AzureEnvironment.Endpoint.AdTenant: propertyValue = environment.AdTenant; break; case AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId: propertyValue = environment.ActiveDirectoryServiceEndpointResourceId; break; case AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix: propertyValue = environment.AzureKeyVaultDnsSuffix; break; case AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId: propertyValue = environment.AzureKeyVaultServiceEndpointResourceId; break; case AzureEnvironment.Endpoint.GraphEndpointResourceId: propertyValue = environment.GraphEndpointResourceId; break; case AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix: propertyValue = environment.SqlDatabaseDnsSuffix; break; case AzureEnvironment.Endpoint.StorageEndpointSuffix: propertyValue = environment.StorageEndpointSuffix; break; case AzureEnvironment.Endpoint.TrafficManagerDnsSuffix: propertyValue = environment.TrafficManagerDnsSuffix; break; case AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix: propertyValue = environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix; break; case AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix: propertyValue = environment.AzureDataLakeStoreFileSystemEndpointSuffix; break; case AzureEnvironment.Endpoint.DataLakeEndpointResourceId: propertyValue = environment.DataLakeEndpointResourceId; break; case AzureEnvironment.Endpoint.ActiveDirectory: propertyValue = environment.ActiveDirectoryAuthority; break; case AzureEnvironment.Endpoint.Gallery: propertyValue = environment.GalleryUrl; break; case AzureEnvironment.Endpoint.Graph: propertyValue = environment.GraphUrl; break; case AzureEnvironment.Endpoint.ManagementPortalUrl: propertyValue = environment.ManagementPortalUrl; break; case AzureEnvironment.Endpoint.PublishSettingsFileUrl: propertyValue = environment.PublishSettingsFileUrl; break; case AzureEnvironment.Endpoint.ResourceManager: propertyValue = environment.ResourceManagerUrl; break; case AzureEnvironment.Endpoint.ServiceManagement: propertyValue = environment.ServiceManagementUrl; break; case AzureEnvironment.Endpoint.BatchEndpointResourceId: propertyValue = environment.BatchEndpointResourceId; break; default: // get property from the extended properties of the environment propertyValue = environment.GetProperty(endpointName); break; } } return(propertyValue != null); }
public void SetEnvironmentWithOnPremise() { // Setup a new environment Mock <ICommandRuntime> commandRuntimeMock = new Mock <ICommandRuntime>(); SetupConfirmation(commandRuntimeMock); var cmdlet = new SetAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Katal", PublishSettingsFileUrl = "http://microsoft.com", EnableAdfsAuthentication = false }; cmdlet.MyInvocation.BoundParameters.Add("Name", "Katal"); cmdlet.MyInvocation.BoundParameters.Add("PublishSettingsFileUrl", "http://microsoft.com"); cmdlet.MyInvocation.BoundParameters.Add("EnableAdfsAuthentication", false); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Once()); IAzureEnvironment env = AzureRmProfileProvider.Instance.Profile.GetEnvironment("KaTaL"); Assert.Equal(env.Name, cmdlet.Name); Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); Assert.False(env.OnPremise); // Update onpremise to true var cmdlet2 = new SetAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Katal", EnableAdfsAuthentication = true }; cmdlet2.MyInvocation.BoundParameters.Add("Name", "Katal"); cmdlet2.MyInvocation.BoundParameters.Add("EnableAdfsAuthentication", true); cmdlet2.InvokeBeginProcessing(); cmdlet2.ExecuteCmdlet(); cmdlet2.InvokeEndProcessing(); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Exactly(2)); IAzureEnvironment env2 = AzureRmProfileProvider.Instance.Profile.GetEnvironment("KaTaL"); Assert.Equal(env2.Name, cmdlet2.Name); Assert.Equal(env2.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); Assert.True(env2.OnPremise); // Update gallery endpoint var cmdlet3 = new SetAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Katal", GalleryEndpoint = "http://galleryendpoint.com", }; cmdlet3.MyInvocation.BoundParameters.Add("Name", "Katal"); cmdlet3.MyInvocation.BoundParameters.Add("GalleryEndpoint", "http://galleryendpoint.com"); cmdlet3.InvokeBeginProcessing(); cmdlet3.ExecuteCmdlet(); cmdlet3.InvokeEndProcessing(); // Ensure gallery endpoint is updated and OnPremise value is preserved commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Exactly(3)); IAzureEnvironment env3 = AzureRmProfileProvider.Instance.Profile.GetEnvironment("KaTaL"); Assert.Equal(env3.Name, cmdlet3.Name); Assert.Equal(env3.GetEndpoint(AzureEnvironment.Endpoint.PublishSettingsFileUrl), cmdlet.PublishSettingsFileUrl); Assert.True(env3.OnPremise); Assert.Equal(env3.GetEndpoint(AzureEnvironment.Endpoint.Gallery), cmdlet3.GalleryEndpoint); }
/// <summary> /// Set the given named endpoint in this environment to the provided value /// </summary> /// <param name="environment">The environment to change</param> /// <param name="endpointName">The named endpoint to update</param> /// <param name="propertyValue">The value to set the named endpoint to in the given environment</param> public static void SetEndpoint(this IAzureEnvironment environment, string endpointName, string propertyValue) { if (!string.IsNullOrWhiteSpace(propertyValue)) { switch (endpointName) { case AzureEnvironment.Endpoint.AdTenant: environment.AdTenant = propertyValue; break; case AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId: environment.ActiveDirectoryServiceEndpointResourceId = propertyValue; break; case AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix: environment.AzureKeyVaultDnsSuffix = propertyValue; break; case AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId: environment.AzureKeyVaultServiceEndpointResourceId = propertyValue; break; case AzureEnvironment.Endpoint.GraphEndpointResourceId: environment.GraphEndpointResourceId = propertyValue; break; case AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix: environment.SqlDatabaseDnsSuffix = propertyValue; break; case AzureEnvironment.Endpoint.StorageEndpointSuffix: environment.StorageEndpointSuffix = propertyValue; break; case AzureEnvironment.Endpoint.TrafficManagerDnsSuffix: environment.TrafficManagerDnsSuffix = propertyValue; break; case AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix: environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = propertyValue; break; case AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix: environment.AzureDataLakeStoreFileSystemEndpointSuffix = propertyValue; break; case AzureEnvironment.Endpoint.DataLakeEndpointResourceId: environment.DataLakeEndpointResourceId = propertyValue; break; case AzureEnvironment.Endpoint.BatchEndpointResourceId: environment.BatchEndpointResourceId = propertyValue; break; case AzureEnvironment.Endpoint.ActiveDirectory: environment.ActiveDirectoryAuthority = propertyValue; break; case AzureEnvironment.Endpoint.Gallery: environment.GalleryUrl = propertyValue; break; case AzureEnvironment.Endpoint.Graph: environment.GraphUrl = propertyValue; break; case AzureEnvironment.Endpoint.ManagementPortalUrl: environment.ManagementPortalUrl = propertyValue; break; case AzureEnvironment.Endpoint.PublishSettingsFileUrl: environment.PublishSettingsFileUrl = propertyValue; break; case AzureEnvironment.Endpoint.ResourceManager: environment.ResourceManagerUrl = propertyValue; break; case AzureEnvironment.Endpoint.ServiceManagement: environment.ServiceManagementUrl = propertyValue; break; case AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId: environment.SetProperty(AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId, propertyValue); break; case AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpoint: environment.SetProperty(AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpoint, propertyValue); break; case AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointSuffix: environment.SetProperty(AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointSuffix, propertyValue); break; } } }
public AzureRmProfile Login( IAzureAccount account, IAzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, SecureString password, bool skipValidation, Action <string> promptAction, string name = null, bool shouldPopulateContextList = true) { IAzureSubscription newSubscription = null; IAzureTenant newTenant = null; string promptBehavior = (password == null && account.Type != AzureAccount.AccountType.AccessToken && account.Type != AzureAccount.AccountType.ManagedService && !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) ? ShowDialog.Always : ShowDialog.Never; if (skipValidation) { if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId)) { throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing); } newSubscription = new AzureSubscription { Id = subscriptionId }; newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId); newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id); newTenant = new AzureTenant { Id = tenantId }; } else { // (tenant and subscription are present) OR // (tenant is present and subscription is not provided) if (!string.IsNullOrEmpty(tenantId)) { Guid tempGuid = Guid.Empty; if (!Guid.TryParse(tenantId, out tempGuid)) { var tenant = ListAccountTenants( account, environment, password, promptBehavior, promptAction)?.FirstOrDefault(); if (tenant == null || tenant.Id == null) { string baseMessage = string.Format(ProfileMessages.TenantDomainNotFound, tenantId); var typeMessageMap = new Dictionary <string, string> { { AzureAccount.AccountType.ServicePrincipal, string.Format(ProfileMessages.ServicePrincipalTenantDomainNotFound, account.Id) }, { AzureAccount.AccountType.User, ProfileMessages.UserTenantDomainNotFound }, { AzureAccount.AccountType.ManagedService, ProfileMessages.MSITenantDomainNotFound } }; string typeMessage = typeMessageMap.ContainsKey(account.Type) ? typeMessageMap[account.Type] : string.Empty; throw new ArgumentNullException(string.Format("{0} {1}", baseMessage, typeMessage)); } tenantId = tenant.Id; } var token = AcquireAccessToken( account, environment, tenantId, password, promptBehavior, promptAction); if (TryGetTenantSubscription( token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant)) { account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() }); } } // (tenant is not provided and subscription is present) OR // (tenant is not provided and subscription is not provided) else { var tenants = ListAccountTenants(account, environment, password, promptBehavior, promptAction) .Select(s => s.Id.ToString()).ToList(); account.SetProperty(AzureAccount.Property.Tenants, null); string accountId = null; foreach (var tenant in tenants) { IAzureTenant tempTenant; IAzureSubscription tempSubscription; IAccessToken token = null; try { token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null); if (accountId == null) { accountId = account.Id; account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase)) { account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else { // if account ID is different from the first tenant account id we need to ignore current tenant WriteWarningMessage(string.Format( ProfileMessages.AccountIdMismatch, account.Id, tenant, accountId)); account.Id = accountId; token = null; } } catch { WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant)); } if (token != null && newTenant == null && TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant)) { // If no subscription found for the given token/tenant // discard tempTenant value unless current token/tenant is the last one. if (tempSubscription != null || tenant.Equals(tenants[tenants.Count - 1])) { newTenant = tempTenant; newSubscription = tempSubscription; } } } } } shouldPopulateContextList &= _profile.DefaultContext?.Account == null; if (newSubscription == null) { if (subscriptionId != null) { throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId)); } else if (subscriptionName != null) { throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName)); } var newContext = new AzureContext(account, environment, newTenant); if (!_profile.TrySetDefaultContext(name, newContext)) { WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString())); } } else { var newContext = new AzureContext(newSubscription, account, environment, newTenant); if (!_profile.TrySetDefaultContext(name, newContext)) { WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString())); } if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase)) { WriteWarningMessage(string.Format( ProfileMessages.SelectedSubscriptionNotActive, newSubscription.State)); } } _profile.DefaultContext.TokenCache = _cache; if (shouldPopulateContextList) { var defaultContext = _profile.DefaultContext; var subscriptions = ListSubscriptions(tenantId).Take(25); foreach (var subscription in subscriptions) { IAzureTenant tempTenant = new AzureTenant() { Id = subscription.GetProperty(AzureSubscription.Property.Tenants) }; var tempContext = new AzureContext(subscription, account, environment, tempTenant); tempContext.TokenCache = _cache; string tempName = null; if (!_profile.TryGetContextName(tempContext, out tempName)) { WriteWarningMessage(string.Format(Resources.CannotGetContextName, subscription.Id)); continue; } if (!_profile.TrySetContext(tempName, tempContext)) { WriteWarningMessage(string.Format(Resources.CannotCreateContext, subscription.Id)); } } _profile.TrySetDefaultContext(defaultContext); _profile.TryRemoveContext("Default"); } return(_profile.ToProfile()); }
/// <summary> /// Try to get the uri from the environment mathcing the given name /// </summary> /// <param name="environment">The environment to get the value from</param> /// <param name="endpointName">The name of the endpoint to attempt to get</param> /// <param name="endpoint">The returned endpoint value as a Uri, or null if no endpoint was found</param> /// <returns>true if the endpoint was found, otherwise false</returns> public static bool TryGetEndpointUrl(this IAzureEnvironment environment, string endpointName, out Uri endpoint) { bool result = true; endpoint = null; switch (endpointName) { case AzureEnvironment.Endpoint.ActiveDirectory: endpoint = new Uri(environment.ActiveDirectoryAuthority); break; case AzureEnvironment.Endpoint.Gallery: endpoint = new Uri(environment.GalleryUrl); break; case AzureEnvironment.Endpoint.Graph: endpoint = new Uri(environment.GraphUrl); break; case AzureEnvironment.Endpoint.ManagementPortalUrl: endpoint = new Uri(environment.ManagementPortalUrl); break; case AzureEnvironment.Endpoint.PublishSettingsFileUrl: endpoint = new Uri(environment.PublishSettingsFileUrl); break; case AzureEnvironment.Endpoint.ResourceManager: endpoint = new Uri(environment.ResourceManagerUrl); break; case AzureEnvironment.Endpoint.ServiceManagement: endpoint = new Uri(environment.ServiceManagementUrl); break; case AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId: endpoint = new Uri(environment.ActiveDirectoryServiceEndpointResourceId); break; case AzureEnvironment.Endpoint.GraphEndpointResourceId: endpoint = new Uri(environment.GraphEndpointResourceId); break; case AzureEnvironment.Endpoint.DataLakeEndpointResourceId: endpoint = new Uri(environment.DataLakeEndpointResourceId); break; case AzureEnvironment.Endpoint.BatchEndpointResourceId: endpoint = new Uri(environment.BatchEndpointResourceId); break; default: result = environment.IsPropertySet(endpointName); if (result) { endpoint = new Uri(environment.GetProperty(endpointName)); } break; } return(result); }
private List <AzureTenant> ListAccountTenants( IAzureAccount account, IAzureEnvironment environment, SecureString password, string promptBehavior, Action <string> promptAction) { List <AzureTenant> result = new List <AzureTenant>(); var commonTenant = GetCommonTenant(account); try { var commonTenantToken = AcquireAccessToken( account, environment, commonTenant, password, promptBehavior, promptAction); SubscriptionClient subscriptionClient = null; try { subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(commonTenantToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers()); //TODO: Fix subscription client to not require subscriptionId result = account.MergeTenants(subscriptionClient.Tenants.List(), commonTenantToken); } finally { // In test mode, we are reusing the client since disposing of it will // fail some tests (due to HttpClient being null) if (subscriptionClient != null && !TestMockSupport.RunningMocked) { subscriptionClient.Dispose(); } } } catch { WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, commonTenant)); if (account.IsPropertySet(AzureAccount.Property.Tenants)) { result = account.GetPropertyAsArray(AzureAccount.Property.Tenants) .Select(ti => { var tenant = new AzureTenant(); Guid guid; if (Guid.TryParse(ti, out guid)) { tenant.Id = ti; tenant.Directory = AccessTokenExtensions.GetDomain(account.Id); } else { tenant.Directory = ti; } return(tenant); }).ToList(); } if (!result.Any()) { throw; } } return(result); }
/// <summary> /// Determine if the given endpoint is set in the given environment /// </summary> /// <param name="environment">The environment to check</param> /// <param name="endpoint">The named endpoint to search for</param> /// <returns>True if the endpoint is set to a non-null value in the environment, otherwise false</returns> public static bool IsEndpointSet(this IAzureEnvironment environment, string endpoint) { string endpointValue; return(environment.TryGetEndpointString(endpoint, out endpointValue)); }
public AzureSubscription GetSubscriptionById(string subscriptionId, IAccessToken accessToken, IAzureAccount account, IAzureEnvironment environment) { AzureSubscription result = null; SubscriptionClientFallBack((client) => result = client?.GetSubscriptionById(subscriptionId, accessToken, account, environment), WriteWarningMessage); return(result); }
public static void Update(this IAzureEnvironment environment, IAzureEnvironment other) { if (environment != null && other != null) { environment.OnPremise = other.OnPremise; if (other.IsEndpointSet(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)) { environment.ActiveDirectoryServiceEndpointResourceId = other.ActiveDirectoryServiceEndpointResourceId; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.AdTenant)) { environment.AdTenant = other.AdTenant; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.Gallery)) { environment.GalleryUrl = other.GalleryUrl; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.ManagementPortalUrl)) { environment.ManagementPortalUrl = other.ManagementPortalUrl; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement)) { environment.ServiceManagementUrl = other.ServiceManagementUrl; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.PublishSettingsFileUrl)) { environment.PublishSettingsFileUrl = other.PublishSettingsFileUrl; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager)) { environment.ResourceManagerUrl = other.ResourceManagerUrl; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix)) { environment.SqlDatabaseDnsSuffix = other.SqlDatabaseDnsSuffix; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.StorageEndpointSuffix)) { environment.StorageEndpointSuffix = other.StorageEndpointSuffix; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.ActiveDirectory)) { environment.ActiveDirectoryAuthority = other.ActiveDirectoryAuthority; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.Graph)) { environment.GraphUrl = other.GraphUrl; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.GraphEndpointResourceId)) { environment.GraphEndpointResourceId = other.GraphEndpointResourceId; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.TrafficManagerDnsSuffix)) { environment.TrafficManagerDnsSuffix = other.TrafficManagerDnsSuffix; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix)) { environment.AzureKeyVaultDnsSuffix = other.AzureKeyVaultDnsSuffix; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix)) { environment.AzureDataLakeStoreFileSystemEndpointSuffix = other.AzureDataLakeStoreFileSystemEndpointSuffix; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix)) { environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = other.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId)) { environment.AzureKeyVaultServiceEndpointResourceId = other.AzureKeyVaultServiceEndpointResourceId; } if (other.IsEndpointSet(AzureEnvironment.Endpoint.DataLakeEndpointResourceId)) { environment.DataLakeEndpointResourceId = other.DataLakeEndpointResourceId; } foreach (var profile in other.VersionProfiles) { if (!environment.VersionProfiles.Contains(profile)) { environment.VersionProfiles.Add(profile); } } environment.UpdateProperties(other); } }
/// <summary> /// Initializes a new Azure environment from the given internal representation. /// </summary> /// <param name="environment">The internal representation of the environment.</param> public PSAzureEnvironment(IAzureEnvironment environment) { this.CopyFrom(environment); }
public CertificateManager(IAzureEnvironment settings, IAcmeConfig acmeConfig, ICertificateServiceSettings certSettings, IAuthorizationChallengeProviderConfig authProviderConfig) : this(settings, acmeConfig, new CertificateService(settings, certSettings), new KuduFileSystemAuthorizationChallengeProvider(settings, authProviderConfig)) { }
public AzureSubscription GetSubscriptionById(string subscriptionId, IAccessToken accessToken, IAzureAccount account, IAzureEnvironment environment) { using (var subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers())) { var subscription = subscriptionClient.Subscriptions.Get(subscriptionId); if (null != subscription) { return(subscription.ToAzureSubscription(account, environment, accessToken.TenantId)); } } return(null); }
public LocalFileSystemAuthorizationChallengeProvider(IAzureEnvironment azureEnvironment, IAuthorizationChallengeProviderConfig config) { this.azureEnvironment = azureEnvironment; this.config = config; }
public void CanCreateEnvironmentWithAllProperties() { Mock <ICommandRuntime> commandRuntimeMock = new Mock <ICommandRuntime>(); SetupConfirmation(commandRuntimeMock); PSAzureEnvironment actual = null; commandRuntimeMock.Setup(f => f.WriteObject(It.IsAny <PSAzureEnvironment>())) .Callback((object output) => actual = (PSAzureEnvironment)output); var cmdlet = new AddAzureRMEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = "Katal", ActiveDirectoryEndpoint = "https://ActiveDirectoryEndpoint", AdTenant = "AdTenant", AzureKeyVaultDnsSuffix = "AzureKeyVaultDnsSuffix", ActiveDirectoryServiceEndpointResourceId = "https://ActiveDirectoryServiceEndpointResourceId", AzureKeyVaultServiceEndpointResourceId = "https://AzureKeyVaultServiceEndpointResourceId", EnableAdfsAuthentication = true, GalleryEndpoint = "https://GalleryEndpoint", GraphEndpoint = "https://GraphEndpoint", ManagementPortalUrl = "https://ManagementPortalUrl", PublishSettingsFileUrl = "https://PublishSettingsFileUrl", ResourceManagerEndpoint = "https://ResourceManagerEndpoint", ServiceEndpoint = "https://ServiceEndpoint", StorageEndpoint = "https://StorageEndpoint", SqlDatabaseDnsSuffix = "SqlDatabaseDnsSuffix", TrafficManagerDnsSuffix = "TrafficManagerDnsSuffix", GraphAudience = "GaraphAudience", BatchEndpointResourceId = "BatchResourceId", DataLakeAudience = "DataLakeAudience", AzureOperationalInsightsEndpointResourceId = "AzureOperationalInsightsEndpointResourceId", AzureOperationalInsightsEndpoint = "https://AzureOperationalInsights", AzureAttestationServiceEndpointResourceId = "AzureAttestationServiceEndpointResourceId", AzureAttestationServiceEndpointSuffix = "https://AzureAttestationService", AzureSynapseAnalyticsEndpointResourceId = "AzureSynapseAnalyticsEndpointResourceId", AzureSynapseAnalyticsEndpointSuffix = "https://AzureSynapseAnalytics", }; var dict = new Dictionary <string, object>(); dict["ActiveDirectoryEndpoint"] = "https://ActiveDirectoryEndpoint"; dict["AdTenant"] = "AdTenant"; dict["AzureKeyVaultDnsSuffix"] = "AzureKeyVaultDnsSuffix"; dict["ActiveDirectoryServiceEndpointResourceId"] = "https://ActiveDirectoryServiceEndpointResourceId"; dict["AzureKeyVaultServiceEndpointResourceId"] = "https://AzureKeyVaultServiceEndpointResourceId"; dict["EnableAdfsAuthentication"] = true; dict["GalleryEndpoint"] = "https://GalleryEndpoint"; dict["GraphEndpoint"] = "https://GraphEndpoint"; dict["ManagementPortalUrl"] = "https://ManagementPortalUrl"; dict["PublishSettingsFileUrl"] = "https://PublishSettingsFileUrl"; dict["ResourceManagerEndpoint"] = "https://ResourceManagerEndpoint"; dict["ServiceEndpoint"] = "https://ServiceEndpoint"; dict["StorageEndpoint"] = "https://StorageEndpoint"; dict["SqlDatabaseDnsSuffix"] = "SqlDatabaseDnsSuffix"; dict["TrafficManagerDnsSuffix"] = "TrafficManagerDnsSuffix"; dict["GraphAudience"] = "GaraphAudience"; dict["BatchEndpointResourceId"] = "BatchResourceId"; dict["DataLakeAudience"] = "DataLakeAudience"; dict["AzureOperationalInsightsEndpointResourceId"] = "AzureOperationalInsightsEndpointResourceId"; dict["AzureOperationalInsightsEndpoint"] = "https://AzureOperationalInsights"; dict["AzureAttestationServiceEndpointResourceId"] = "AzureAttestationServiceEndpointResourceId"; dict["AzureAttestationServiceEndpointSuffix"] = "https://AzureAttestationService"; dict["AzureSynapseAnalyticsEndpointResourceId"] = "AzureSynapseAnalyticsEndpointResourceId"; dict["AzureSynapseAnalyticsEndpointSuffix"] = "https://AzureSynapseAnalytics"; cmdlet.SetBoundParameters(dict); cmdlet.SetParameterSet("Name"); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); Assert.Equal(cmdlet.Name, actual.Name); Assert.Equal(cmdlet.EnableAdfsAuthentication.ToBool(), actual.EnableAdfsAuthentication); Assert.Equal(cmdlet.ActiveDirectoryEndpoint + "/", actual.ActiveDirectoryAuthority, StringComparer.OrdinalIgnoreCase); Assert.Equal(cmdlet.ActiveDirectoryServiceEndpointResourceId, actual.ActiveDirectoryServiceEndpointResourceId); Assert.Equal(cmdlet.AdTenant, actual.AdTenant); Assert.Equal(cmdlet.AzureKeyVaultDnsSuffix, actual.AzureKeyVaultDnsSuffix); Assert.Equal(cmdlet.AzureKeyVaultServiceEndpointResourceId, actual.AzureKeyVaultServiceEndpointResourceId); Assert.Equal(cmdlet.GalleryEndpoint, actual.GalleryUrl); Assert.Equal(cmdlet.GraphEndpoint, actual.GraphUrl); Assert.Equal(cmdlet.ManagementPortalUrl, actual.ManagementPortalUrl); Assert.Equal(cmdlet.PublishSettingsFileUrl, actual.PublishSettingsFileUrl); Assert.Equal(cmdlet.ResourceManagerEndpoint, actual.ResourceManagerUrl); Assert.Equal(cmdlet.ServiceEndpoint, actual.ServiceManagementUrl); Assert.Equal(cmdlet.StorageEndpoint, actual.StorageEndpointSuffix); Assert.Equal(cmdlet.SqlDatabaseDnsSuffix, actual.SqlDatabaseDnsSuffix); Assert.Equal(cmdlet.TrafficManagerDnsSuffix, actual.TrafficManagerDnsSuffix); Assert.Equal(cmdlet.GraphAudience, actual.GraphEndpointResourceId); Assert.Equal(cmdlet.BatchEndpointResourceId, actual.BatchEndpointResourceId); Assert.Equal(cmdlet.DataLakeAudience, actual.DataLakeEndpointResourceId); Assert.Equal(cmdlet.AzureOperationalInsightsEndpointResourceId, actual.AzureOperationalInsightsEndpointResourceId); Assert.Equal(cmdlet.AzureOperationalInsightsEndpoint, actual.AzureOperationalInsightsEndpoint); Assert.Equal(cmdlet.AzureAttestationServiceEndpointResourceId, actual.AzureAttestationServiceEndpointResourceId); Assert.Equal(cmdlet.AzureAttestationServiceEndpointSuffix, actual.AzureAttestationServiceEndpointSuffix); Assert.Equal(cmdlet.AzureSynapseAnalyticsEndpointResourceId, actual.AzureSynapseAnalyticsEndpointResourceId); Assert.Equal(cmdlet.AzureSynapseAnalyticsEndpointSuffix, actual.AzureSynapseAnalyticsEndpointSuffix); commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Once()); IAzureEnvironment env = AzureRmProfileProvider.Instance.Profile.GetEnvironment("KaTaL"); Assert.Equal(env.Name, cmdlet.Name); }
/// <summary> /// Copy constructor /// </summary> /// <param name="other"></param> public AzureEnvironment(IAzureEnvironment other) { this.CopyFrom(other); }