/// <summary>
        /// Determines the API version.
        /// </summary>
        /// <param name="context">The azure profile.</param>
        /// <param name="providerNamespace">The provider namespace.</param>
        /// <param name="resourceType">The resource type.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
        internal static Task<string> DetermineApiVersion(AzureContext context, string providerNamespace, string resourceType, CancellationToken cancellationToken, bool? pre = null, Dictionary<string, string> cmdletHeaderValues = null)
        {
            var cacheKey = ApiVersionCache.GetCacheKey(providerNamespace: providerNamespace, resourceType: resourceType);
            var apiVersions = ApiVersionCache.Instance
                .AddOrGetExisting(cacheKey: cacheKey, getFreshData: () => ApiVersionHelper.GetApiVersionsForResourceType(
                    context,
                    providerNamespace: providerNamespace,
                    resourceType: resourceType,
                    cancellationToken: cancellationToken,
                    cmdletHeaderValues: cmdletHeaderValues));

            apiVersions = apiVersions.CoalesceEnumerable().ToArray();
            var apiVersionsToSelectFrom = apiVersions;
            if (pre == null || pre  == false)
            {
                apiVersionsToSelectFrom = apiVersions
                    .Where(apiVersion => apiVersion.IsDecimal(NumberStyles.AllowDecimalPoint) || apiVersion.IsDateTime("yyyy-mm-dd", DateTimeStyles.None))
                    .ToArray();
            }

            var selectedApiVersion = apiVersionsToSelectFrom.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();
            if (string.IsNullOrWhiteSpace(selectedApiVersion) && apiVersions.Any())
            {
                // fall back on pre-release APIs if they're the only ones available.
                selectedApiVersion = apiVersions.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();
            }

            var result = string.IsNullOrWhiteSpace(selectedApiVersion) 
                ? Constants.DefaultApiVersion
                : selectedApiVersion;

            return Task.FromResult(result);
        }
 private static RMProfileClient SetupTestEnvironment(List<string> tenants, params List<string>[] subscriptionLists)
 {
     AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(DefaultAccount,
         Guid.NewGuid().ToString(), DefaultTenant.ToString());
     var subscriptionList = new Queue<List<string>>(subscriptionLists);
     var clientFactory = new MockSubscriptionClientFactory(tenants, subscriptionList);
     var mock = new MockClientFactory(new List<object>
     {
         clientFactory.GetSubscriptionClient()
     }, true);
     mock.MoqClients = true;
     AzureSession.ClientFactory = mock;
     Context = new AzureContext(new AzureSubscription()
         {
             Account = DefaultAccount,
             Environment = EnvironmentName.AzureCloud,
             Id = DefaultSubscription,
             Name = DefaultSubscriptionName
         },
         new AzureAccount() { Id = DefaultAccount, Type = AzureAccount.AccountType.User },
         AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
         new AzureTenant() { Domain = DefaultDomain, Id = DefaultTenant });
     var profile = new AzureRMProfile();
     profile.Context = Context;
     return new RMProfileClient(profile);
 }
        private Tuple<IAccessToken, string> GetToken(IAuthenticationFactory authFactory, AzureContext context, AzureEnvironment.Endpoint resourceIdEndpoint)
        {
            if (context.Account == null)
                throw new ArgumentException(KeyVaultProperties.Resources.ArmAccountNotFound);

            if (context.Account.Type != AzureAccount.AccountType.User &&
                context.Account.Type != AzureAccount.AccountType.ServicePrincipal)
                throw new ArgumentException(string.Format(KeyVaultProperties.Resources.UnsupportedAccountType, context.Account.Type));

            if (context.Subscription != null && context.Account != null)
                TenantId = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                       .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                       .FirstOrDefault();

            if (string.IsNullOrWhiteSpace(TenantId) && context.Tenant != null && context.Tenant.Id != Guid.Empty)
                TenantId = context.Tenant.Id.ToString();

            if (string.IsNullOrWhiteSpace(TenantId))
                throw new ArgumentException(KeyVaultProperties.Resources.NoTenantInContext);

            try
            {
                var accesstoken = authFactory.Authenticate(context.Account, context.Environment, TenantId, null, ShowDialog.Auto,
                    resourceIdEndpoint);

                return Tuple.Create(accesstoken, context.Environment.Endpoints[resourceIdEndpoint]);
            }
            catch (Exception ex)
            {
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidSubscriptionState, ex);
            }
        }
        /// <summary>
        /// Creates new ActiveDirectoryClient using WindowsAzureSubscription.
        /// </summary>
        /// <param name="context"></param>
        public ActiveDirectoryClient(AzureContext context)
        {
            GraphClient = AzureSession.ClientFactory.CreateArmClient<GraphRbacManagementClient>(
                context, AzureEnvironment.Endpoint.Graph);

            GraphClient.TenantID = context.Tenant.Id.ToString();
        }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseAdapter(AzureContext context)
 {
     Context = context;
     _subscription = context.Subscription;
     Communicator = new AzureSqlDatabaseCommunicator(Context);
     ElasticPoolCommunicator = new AzureSqlElasticPoolCommunicator(Context);
 }
        public void DelegatingHandlersAreCloned()
        {
            string userAccount = "*****@*****.**";
            Guid subscriptionId = Guid.NewGuid();
             AzureContext context = new AzureContext
            (
                new AzureSubscription()
                {
                    Account = userAccount,
                    Environment = "AzureCloud",
                    Id = subscriptionId,
                    Properties = new Dictionary<AzureSubscription.Property, string>() { { AzureSubscription.Property.Tenants, "common" } }
                }, 
                new AzureAccount()
                {
                    Id = userAccount,
                    Type = AzureAccount.AccountType.User,
                    Properties = new Dictionary<AzureAccount.Property, string>() { { AzureAccount.Property.Tenants, "common" } }
                },
                AzureEnvironment.PublicEnvironments["AzureCloud"]
            );

            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(userAccount, Guid.NewGuid().ToString());
            var mockHandler = new MockDelegatingHandler();
            var factory = new ClientFactory();
            factory.AddHandler(mockHandler);
            var client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            Assert.Equal(5, MockDelegatingHandler.cloneCount); 
        }
 /// <summary>
 /// Creates new ActiveDirectoryClient using WindowsAzureSubscription.
 /// </summary>
 /// <param name="context"></param>
 public ActiveDirectoryClient(AzureContext context)
 {
     AccessTokenCredential creds = (AccessTokenCredential)AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context, AzureEnvironment.Endpoint.Graph);
     GraphClient = AzureSession.ClientFactory.CreateCustomClient<GraphRbacManagementClient>(
         creds.TenantID,
         creds,
         context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.Graph));
 }
        /// <summary>
        /// Creates new ResourceManagementClient
        /// </summary>
        /// <param name="context">Profile containing resources to manipulate</param>
        public ResourcesClient(AzureContext context)
            : this(
                AzureSession.ClientFactory.CreateClient<ResourceManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager),
                new GalleryTemplatesClient(context),
                AzureSession.ClientFactory.CreateClient<AuthorizationManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager))
        {

        }
 public SqlThreatDetectionAdapter(AzureContext context)
 {
     Context = context;
     Subscription = context.Subscription;
     ThreatDetectionCommunicator = new ThreatDetectionEndpointsCommunicator(Context);
     AzureCommunicator = new AzureEndpointsCommunicator(Context);
     AuditingAdapter = new SqlAuditAdapter(context);
 }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseReplicationAdapter(AzureContext context)
 {
     Context = context;
     _subscription = context.Subscription;
     ReplicationCommunicator = new AzureSqlDatabaseReplicationCommunicator(Context);
     DatabaseCommunicator = new AzureSqlDatabaseCommunicator(Context);
     ServerCommunicator = new AzureSqlServerCommunicator(Context);
 }
 public SqlAuditAdapter(AzureContext context)
 {
     Context = context;
     Subscription = context.Subscription;
     Communicator = new AuditingEndpointsCommunicator(Context);
     AzureCommunicator = new AzureEndpointsCommunicator(Context);
     IgnoreStorage = false;
 }
 public DataMaskingEndpointsCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlDatabaseIndexRecommendationCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 public WebServicesClient(AzureContext context)
 {
     this.apiClient = AzureSession.ClientFactory.
                                     CreateArmClient<APIClient>(
                                         context,
                                         AzureEnvironment.Endpoint.ResourceManager);
     this.apiClient.LongRunningOperationRetryTimeout =
             WebServicesClient.AsyncOperationPollingIntervalSeconds;
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Database backup REST endpoints.
 /// </summary>
 /// <param name="profile">Azure profile</param>
 /// <param name="subscription">Associated subscription</param>
 public AzureSqlDatabaseBackupCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Base class contructor for Advisor REST API Communicators.
 /// </summary>
 public AzureSqlAdvisorCommunicatorBase(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
        public ApiManagementClient(AzureContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("AzureProfile");
            }

            _context = context;
        }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases ServiceObjective
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServerServiceObjectiveCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases FirewallRules
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlCapabilitiesCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Elastic Pool
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlElasticPoolCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
        public NotificationHubsManagementClient(AzureContext azureContext)
        {
            if (azureContext == null)
            {
                throw new ArgumentNullException("azureContext");
            }

            _context = azureContext;
        }
 public ThreatDetectionEndpointsCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Elastic Pool
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServerCommunicationLinkCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases TransparentDataEncryption
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlDatabaseTransparentDataEncryptionCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Server Disaster Recovery Configuration
 /// </summary>
 /// <param name="context"></param>
 public AzureSqlServerDisasterRecoveryConfigurationCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Base class contructor for RecommendedAction REST API Communicators.
 /// </summary>
 public AzureSqlRecommendedActionCommunicatorBase(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public ImportExportDatabaseCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
        public DataServiceCredential(IAuthenticationFactory authFactory, AzureContext context, AzureEnvironment.Endpoint resourceIdEndpoint)
        {
            if (authFactory == null)
                throw new ArgumentNullException("authFactory");
            if (context == null)
                throw new ArgumentNullException("context");

            var bundle = GetToken(authFactory, context, resourceIdEndpoint);
            this.token = bundle.Item1;
        }
        /// <summary>
        /// Determines the API version.
        /// </summary>
        /// <param name="context">The azure profile.</param>
        /// <param name="resourceId">The resource Id.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
        internal static Task<string> DetermineApiVersion(AzureContext context, string resourceId, CancellationToken cancellationToken, bool? pre = null, Dictionary<string, string> cmdletHeaderValues = null)
        {
            var providerNamespace = ResourceIdUtility.GetExtensionProviderNamespace(resourceId)
                ?? ResourceIdUtility.GetProviderNamespace(resourceId);

            var resourceType = ResourceIdUtility.GetExtensionResourceType(resourceId: resourceId, includeProviderNamespace: false)
                ?? ResourceIdUtility.GetResourceType(resourceId: resourceId, includeProviderNamespace: false);

            return ApiVersionHelper.DetermineApiVersion(context: context, providerNamespace: providerNamespace, resourceType: resourceType, cancellationToken: cancellationToken, pre: pre, cmdletHeaderValues: cmdletHeaderValues);
        }
        public DataLakeStoreClient(AzureContext context)
        {
            if (context == null)
            {
                throw new ApplicationException(Resources.InvalidDefaultSubscription);
            }

            _subscriptionId = context.Subscription.Id;
            _client = DataLakeStoreCmdletBase.CreateAdlsClient<DataLakeStoreAccountManagementClient>(context,
                AzureEnvironment.Endpoint.ResourceManager);
        }
Example #31
0
        public void RefreshContextsFromCache()
        {
            // Authentication factory is already registered in `OnImport()`
            AzureSession.Instance.TryGetComponent(
                PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey,
                out PowerShellTokenCacheProvider tokenCacheProvider);

            string authority = null;

            if (TryGetEnvironment(AzureSession.Instance.GetProperty(AzureSession.Property.Environment), out IAzureEnvironment sessionEnvironment))
            {
                authority = $"{sessionEnvironment.ActiveDirectoryAuthority}organizations";
            }
            var accounts = tokenCacheProvider.ListAccounts(authority);

            if (!accounts.Any())
            {
                if (!Contexts.Any(c => c.Key != "Default" && c.Value.Account.Type == AzureAccount.AccountType.User))
                {
                    // If there are no accounts in the cache, but we never had any existing contexts, return
                    return;
                }

                WriteWarningMessage($"No accounts found in the shared token cache; removing all user contexts.");
                var removedContext = false;
                foreach (var contextName in Contexts.Keys)
                {
                    var context = Contexts[contextName];
                    if (context.Account.Type != AzureAccount.AccountType.User)
                    {
                        continue;
                    }

                    removedContext |= TryCacheRemoveContext(contextName);
                }

                // If no contexts were removed, return now to avoid writing to file later
                if (!removedContext)
                {
                    return;
                }
            }
            else
            {
                var removedUsers   = new HashSet <string>();
                var updatedContext = false;
                foreach (var contextName in Contexts.Keys)
                {
                    var context = Contexts[contextName];
                    if ((string.Equals(contextName, "Default") && context.Account == null) || context.Account.Type != AzureAccount.AccountType.User)
                    {
                        continue;
                    }

                    if (accounts.Any(a => string.Equals(a.Username, context.Account.Id, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    if (!removedUsers.Contains(context.Account.Id))
                    {
                        removedUsers.Add(context.Account.Id);
                        WriteWarningMessage(string.Format(Resources.UserMissingFromSharedTokenCache, context.Account.Id));
                    }

                    updatedContext |= TryCacheRemoveContext(contextName);
                }

                // Check to see if each account has at least one context
                foreach (var account in accounts)
                {
                    if (Contexts.Values.Where(v => v.Account != null && v.Account.Type == AzureAccount.AccountType.User)
                        .Any(v => string.Equals(v.Account.Id, account.Username, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    WriteWarningMessage(string.Format(Resources.CreatingContextsWarning, account.Username));
                    var environment = sessionEnvironment ?? AzureEnvironment.PublicEnvironments
                                      .Where(env => env.Value.ActiveDirectoryAuthority.Contains(account.Environment))
                                      .Select(env => env.Value)
                                      .FirstOrDefault();
                    var azureAccount = new AzureAccount()
                    {
                        Id   = account.Username,
                        Type = AzureAccount.AccountType.User
                    };

                    List <IAccessToken> tokens = null;
                    try
                    {
                        tokens = tokenCacheProvider.GetTenantTokensForAccount(account, environment, WriteWarningMessage);
                    }
                    catch (Exception e)
                    {
                        //In SSO scenario, if the account from token cache has multiple tenants, e.g. MSA account, MSAL randomly picks up
                        //one tenant to ask for token, MSAL will throw exception if MSA home tenant is chosen. The exception is swallowed here as short term fix.
                        WriteWarningMessage(string.Format(Resources.NoTokenFoundWarning, account.Username));
                        EnqueueDebugMessage(e.ToString());
                        continue;
                    }

                    foreach (var token in tokens)
                    {
                        var azureTenant = new AzureTenant()
                        {
                            Id = token.TenantId
                        };
                        azureAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, token.TenantId);
                        var subscriptions = tokenCacheProvider.GetSubscriptionsFromTenantToken(account, environment, token, WriteWarningMessage);
                        if (!subscriptions.Any())
                        {
                            subscriptions.Add(null);
                        }

                        foreach (var subscription in subscriptions)
                        {
                            var context = new AzureContext(subscription, azureAccount, environment, azureTenant);
                            if (!TryGetContextName(context, out string name))
                            {
                                WriteWarningMessage(string.Format(Resources.NoContextNameForSubscription, subscription.Id));
                                continue;
                            }

                            if (!TrySetContext(name, context))
                            {
                                WriteWarningMessage(string.Format(Resources.UnableToCreateContextForSubscription, subscription.Id));
                            }
                            else
                            {
                                updatedContext = true;
                            }
                        }
                    }
                }

                // If the context list was not updated, return now to avoid writing to file later
                if (!updatedContext)
                {
                    return;
                }
            }

            Save(ProfilePath, false);
        }