Пример #1
0
 public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment, AzureTenant tenant)
 {
     Subscription = subscription;
     Account      = account;
     Environment  = environment;
     Tenant       = tenant;
 }
Пример #2
0
 public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment, AzureTenant tenant)
 {
     Subscription = subscription;
     Account = account;
     Environment = environment;
     Tenant = tenant;
 }
        public void ProfileSerializeDeserializeWorks()
        {
            var dataStore = new MockDataStore();
            AzureSession.DataStore = dataStore;
            var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
            var currentProfile = new AzureRMProfile(profilePath);
            var tenantId = Guid.NewGuid().ToString();
            var environment = new AzureEnvironment
            {
                Name = "testCloud",
                Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } }
            };
            var account = new AzureAccount
            {
                Id = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
                Properties = { { AzureAccount.Property.Tenants, tenantId } }
            };
            var sub = new AzureSubscription
            {
                Account = account.Id,
                Environment = environment.Name,
                Id = new Guid(),
                Name = "Contoso Test Subscription",
                Properties = { { AzureSubscription.Property.Tenants, tenantId } }
            };
            var tenant = new AzureTenant
            {
                Id = new Guid(tenantId),
                Domain = "contoso.com"
            };

            currentProfile.Context = new AzureContext(sub, account, environment, tenant);
            currentProfile.Environments[environment.Name] = environment;
            currentProfile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 };

            AzureRMProfile deserializedProfile;
            // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                // "Save" object state
                bf.Serialize(ms, currentProfile);

                // Re-use the same stream for de-serialization
                ms.Seek(0, 0);

                // Replace the original exception with de-serialized one
                deserializedProfile = (AzureRMProfile)bf.Deserialize(ms);
            }
            Assert.NotNull(deserializedProfile);
            var jCurrentProfile = currentProfile.ToString();
            var jDeserializedProfile = deserializedProfile.ToString();
            Assert.Equal(jCurrentProfile, jDeserializedProfile);
        }
Пример #4
0
        /// <summary>
        /// Creates new instance of AzureContext.
        /// </summary>
        /// <param name="account">The azure account object</param>
        /// <param name="environment">The azure environment object</param>
        /// <param name="tenant">The azure tenant object</param>
        public AzureContext(AzureAccount account, AzureEnvironment environment, AzureTenant tenant)
            : this(null, account, environment, tenant)
        {

        }
Пример #5
0
 /// <summary>
 /// Creates new instance of AzureContext.
 /// </summary>
 /// <param name="account">The azure account object</param>
 /// <param name="environment">The azure environment object</param>
 /// <param name="tenant">The azure tenant object</param>
 public AzureContext(AzureAccount account, AzureEnvironment environment, AzureTenant tenant)
     : this(null, account, environment, tenant)
 {
 }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment currentEnvironment = null;
            if (mode == AzureModule.AzureResourceManager)
            {
                currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            }
            else
            {
                currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, currentEnvironment);

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = currentEnvironment.BaseUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Graph] = currentEnvironment.Endpoints.GraphUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix] = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix
            environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix] = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix

            if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }

            if (!AzureRmProfileProvider.Instance.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                AzureRmProfileProvider.Instance.Profile.Environments[testEnvironmentName] = environment;
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id = new Guid(currentEnvironment.SubscriptionId),
                    Name = testSubscriptionName,
                    Environment = testEnvironmentName,
                    Account = currentEnvironment.UserName,
                    Properties = new Dictionary<AzureSubscription.Property, string>
                    {
                        {AzureSubscription.Property.Default, "True"},
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                    }
                };

                testAccount = new AzureAccount()
                {
                    Id = currentEnvironment.UserName,
                    Type = AzureAccount.AccountType.User,
                    Properties = new Dictionary<AzureAccount.Property, string>
                    {
                        {AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                    }
                };

                ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                ProfileClient.Profile.Accounts[testAccount.Id] = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account);

                var testTenant = new AzureTenant() { Id = Guid.NewGuid() };
                if (!string.IsNullOrEmpty(currentEnvironment.Tenant))
                {
                    Guid tenant;
                    if (Guid.TryParse(currentEnvironment.Tenant, out tenant))
                    {
                        testTenant.Id = tenant;
                    }
                }
                AzureRmProfileProvider.Instance.Profile.Context = new AzureContext(testSubscription, testAccount, environment, testTenant);
            }
        }
        public void SavingProfileWorks()
        {
            string expected = @"{
  ""Environments"": {
    ""testCloud"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""Endpoints"": {
        ""ActiveDirectory"": ""http://contoso.com""
      }
    }
  },
  ""Context"": {
    ""Account"": {
      ""Id"": ""*****@*****.**"",
      ""Type"": 1,
      ""Properties"": {
        ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
      }
    },
    ""Subscription"": {
      ""Id"": ""00000000-0000-0000-0000-000000000000"",
      ""Name"": ""Contoso Test Subscription"",
      ""Environment"": ""testCloud"",
      ""Account"": ""*****@*****.**"",
      ""State"": ""Enabled"",
      ""Properties"": {
        ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
      }
    },
    ""Environment"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""Endpoints"": {
        ""ActiveDirectory"": ""http://contoso.com""
      }
    },
    ""Tenant"": {
      ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
      ""Domain"": ""contoso.com""
    },
    ""TokenCache"": ""AQIDBAUGCAkA""
  }
}";
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
            var dataStore = new MockDataStore();
            AzureSession.DataStore = dataStore;
            AzureRMProfile profile = new AzureRMProfile(path);
            var tenantId = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6");
            var environment = new AzureEnvironment
            {
                Name = "testCloud",
                Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } }
            };
            var account = new AzureAccount
            {
                Id = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
                Properties = { { AzureAccount.Property.Tenants, tenantId.ToString() } }
            };
            var sub = new AzureSubscription
            {
                Account = account.Id,
                Environment = environment.Name,
                Id = new Guid(),
                Name = "Contoso Test Subscription",
                State = "Enabled",
                Properties = { { AzureSubscription.Property.Tenants, tenantId.ToString() } }
            };
            var tenant = new AzureTenant
            {
                Id = tenantId,
                Domain = "contoso.com"
            };
            profile.Context = new AzureContext(sub, account, environment, tenant);
            profile.Environments[environment.Name] = environment;
            profile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 };
            profile.Save();
            string actual = dataStore.ReadFileAsText(path);
            Assert.Equal(expected, actual);
        }
Пример #8
0
        private static AzureTenant CreateTenantFromString(string tenantOrDomain, string accessTokenTenantId)
        {
            AzureTenant result = new AzureTenant();
            Guid id;
            if (Guid.TryParse(tenantOrDomain, out id))
            {
                result.Id = id;
            }
            else
            {
                result.Id = Guid.Parse(accessTokenTenantId);
                result.Domain = tenantOrDomain;
            }

            return result;
        }
Пример #9
0
        private List<AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            List<AzureTenant> result = new List<AzureTenant>();
            try
            {
                var commonTenantToken = AcquireAccessToken(account, environment, AuthenticationFactory.CommonAdTenant,
                    password, promptBehavior);

                using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>(
                    new TokenCloudCredentials(commonTenantToken.AccessToken),
                    environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    //TODO: Fix subscription client to not require subscriptionId
                    result = account.MergeTenants(subscriptionClient.Tenants.List().TenantIds, commonTenantToken);
                }
            }
            catch
            {
                WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, AuthenticationFactory.CommonAdTenant));
                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 = guid;
                                    tenant.Domain = AccessTokenExtensions.GetDomain(account.Id);
                                }
                                else
                                {
                                    tenant.Domain = ti;
                                }

                                return tenant;
                            }).ToList();
                }
                if (!result.Any())
                {
                    throw;
                }

            }

            return result;
        }
Пример #10
0
        private bool TryGetTenantSubscription(IAccessToken accessToken,
            AzureAccount account,
            AzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            out AzureSubscription subscription,
            out AzureTenant tenant)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>(
                new TokenCloudCredentials(accessToken.AccessToken),
                environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                Subscriptions.Models.Subscription subscriptionFromServer = null;

                try
                {
                    if (subscriptionId != null)
                    {
                        subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId).Subscription;
                    }
                    else
                    {
                        var subscriptions = (subscriptionClient.Subscriptions.List().Subscriptions ??
                                                new List<Microsoft.Azure.Subscriptions.Models.Subscription>())
                                            .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) ||
                                                        "warned".Equals(s.State, 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-AzureRmContext.",
                                        tenantId));
                                }
                                subscriptionFromServer = subscriptions.First();
                            }
                        }
                    }
                }
                catch (CloudException ex)
                {
                    WriteWarningMessage(ex.Message);
                }

                if (subscriptionFromServer != null)
                {
                    subscription = new AzureSubscription
                    {
                        Id = new Guid(subscriptionFromServer.SubscriptionId),
                        Account = accessToken.UserId,
                        Environment = environment.Name,
                        Name = subscriptionFromServer.DisplayName,
                        State = subscriptionFromServer.State,
                        Properties = new Dictionary<AzureSubscription.Property, string>
                        {
                            { AzureSubscription.Property.Tenants, accessToken.TenantId }
                        }
                    };

                    tenant = new AzureTenant();
                    tenant.Id = new Guid(accessToken.TenantId);
                    tenant.Domain = accessToken.GetDomain();
                    return true;
                }

                subscription = null;

                if (accessToken != null && accessToken.TenantId != null)
                {
                    tenant = new AzureTenant();
                    tenant.Id = Guid.Parse(accessToken.TenantId);
                    if (accessToken.UserId != null)
                    {
                        var domain = accessToken.UserId.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                        if (domain.Length == 2)
                        {
                            tenant.Domain = domain[1];
                        }
                    }
                    return true;
                }

                tenant = null;
                return false;
            }
        }
Пример #11
0
 private AzureTenant CreateTenant(string tenantIdOrDomain)
 {
     var tenant = new AzureTenant();
     Guid tenantIdGuid;
     if (Guid.TryParse(tenantIdOrDomain, out tenantIdGuid))
     {
         tenant.Id = tenantIdGuid;
     }
     else
     {
         tenant.Domain = tenantIdOrDomain;
     }
     return tenant;
 }
Пример #12
0
 public void CanConvertValidAzureTenants(string domain)
 {
     var oldTenant = new AzureTenant()
     {
         Domain = domain,
         Id = Guid.NewGuid(),
     };
     var tenant = (PSAzureTenant)oldTenant;
     Assert.Equal(oldTenant.Domain, tenant.Domain);
     Assert.Equal(oldTenant.Id.ToString(), tenant.TenantId);
     Assert.NotNull(tenant.ToString());
 }
Пример #13
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);
        }