Exemple #1
0
        public async Task ValidateAuthorityFalse_SkipsNetworkCall_Async()
        {
            // Arrange
            var validationException = new MsalServiceException(MsalError.InvalidInstance, "authority validation failed");

            // Inject authority in service bundle
            var httpManager = new MockHttpManager();
            var appConfig   = new ApplicationConfiguration()
            {
                HttpManager   = httpManager,
                AuthorityInfo = AuthorityInfo.FromAuthorityUri(Authority, false)
            };

            var serviceBundle = ServiceBundle.Create(appConfig);

            RequestContext requestContext = new RequestContext(serviceBundle, Guid.NewGuid());

            // network fails with invalid_instance exception
            _networkMetadataProvider
            .When(x => x.GetMetadataAsync(Arg.Any <Uri>(), requestContext))
            .Do(x => throw validationException);

            InstanceDiscoveryMetadataEntry actualResult = await _discoveryManager.GetMetadataEntryAsync(
                AuthorityInfo.FromAuthorityUri("https://some_env.com/tid", true),
                requestContext).ConfigureAwait(false);

            // Since the validateAuthority is set to false, proceed without alias.
            ValidateSingleEntryMetadata(new Uri(Authority), actualResult);
        }
Exemple #2
0
        public override void TestInitialize()
        {
            base.TestInitialize();

            _networkMetadataProvider      = Substitute.For <INetworkMetadataProvider>();
            _knownMetadataProvider        = Substitute.For <IKnownMetadataProvider>();
            _networkCacheMetadataProvider = Substitute.For <INetworkCacheMetadataProvider>();
            _userMetadataProvider         = Substitute.For <IUserMetadataProvider>();

            _expectedResult = new InstanceDiscoveryMetadataEntry()
            {
                Aliases          = new[] { "some_env.com", "some_env2.com" },
                PreferredCache   = "env",
                PreferredNetwork = "env"
            };

            _harness = base.CreateTestHarness();

            _testRequestContext = new RequestContext(_harness.ServiceBundle, Guid.NewGuid());
            _discoveryManager   = new InstanceDiscoveryManager(
                _harness.HttpManager,
                false,
                null,
                null,
                _knownMetadataProvider,
                _networkCacheMetadataProvider,
                _networkMetadataProvider);
        }
Exemple #3
0
        public async Task <InstanceDiscoveryMetadataEntry> TryGetMetadataAsync(Uri authority, RequestContext requestContext)
        {
            Uri regionalizedAuthority = await BuildAuthorityWithRegionAsync(authority, requestContext).ConfigureAwait(false);

            if (regionalizedAuthority == null && requestContext.ServiceBundle.Config.AuthorityInfo.FallbackToGlobal)
            {
                requestContext.Logger.Verbose($"[Region discovery] Unable to determine region. Falling back to global.");
                return(null);
            }

            InstanceDiscoveryMetadataEntry cachedEntry = _networkCacheMetadataProvider.GetMetadata(regionalizedAuthority.Host, requestContext.Logger);

            if (cachedEntry == null)
            {
                CacheInstanceDiscoveryMetadata(CreateEntry(authority, regionalizedAuthority));

                cachedEntry = _networkCacheMetadataProvider.GetMetadata(regionalizedAuthority.Host, requestContext.Logger);
                requestContext.Logger.Verbose($"[Region discovery] Created metadata for the regional environment {regionalizedAuthority.Host} ? {cachedEntry != null}");
            }
            else
            {
                requestContext.Logger.Verbose($"[Region discovery] The network provider found an entry for {regionalizedAuthority.Host}");
                LogTelemetryData(cachedEntry.PreferredNetwork.Split('.')[0], RegionSource.Cache, requestContext);
            }

            return(cachedEntry);
        }
        public async Task StaticProviderIsUsedFirst_Async()
        {
            // Arrange
            _staticMetadataProvider.GetMetadata("some_env.com").Returns(_expectedResult);

            // Act
            InstanceDiscoveryMetadataEntry actualResult1 = await _discoveryManager.GetMetadataEntryTryAvoidNetworkAsync(
                Authority,
                new[] { "env1", "env2" },
                _testRequestContext)
                                                           .ConfigureAwait(false);

            _staticMetadataProvider.Received(1).GetMetadata("some_env.com");

            InstanceDiscoveryMetadataEntry actualResult2 = await _discoveryManager.GetMetadataEntryAsync(
                "https://some_env.com/tid",
                _testRequestContext)
                                                           .ConfigureAwait(false);

            _staticMetadataProvider.Received(2).GetMetadata("some_env.com");
            _staticMetadataProvider.AddMetadata(null, null);

            // Assert
            Assert.AreSame(_expectedResult, actualResult1, "The static provider should be queried first");
            Assert.AreSame(_expectedResult, actualResult2, "The static provider should be queried first");
        }
 private void CacheInstanceDiscoveryMetadata(InstanceDiscoveryMetadataEntry metadataEntry)
 {
     foreach (string aliasedEnvironment in metadataEntry.Aliases ?? Enumerable.Empty <string>())
     {
         _networkCacheMetadataProvider.AddMetadata(aliasedEnvironment, metadataEntry);
     }
 }
Exemple #6
0
        public void UserMetadataProvider_RespondsIfEnvironmentsAreKnown()
        {
            // Arrange
            string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json"));
            InstanceDiscoveryResponse instanceDiscovery = JsonHelper.DeserializeFromJson <InstanceDiscoveryResponse>(instanceMetadataJson);

            UserMetadataProvider userMetadataProvider = new UserMetadataProvider(instanceDiscovery);

            // Act
            InstanceDiscoveryMetadataEntry result = userMetadataProvider.GetMetadataOrThrow("login.microsoftonline.com", _logger);

            // Assert
            Assert.AreEqual("login.microsoftonline.com", result.PreferredNetwork);
            Assert.AreEqual("login.windows.net", result.PreferredCache);
            Assert.IsTrue(Enumerable.SequenceEqual
                              (new[] { "login.microsoftonline.com", "login.windows.net" },
                              result.Aliases));

            InstanceDiscoveryMetadataEntry result2 = userMetadataProvider.GetMetadataOrThrow("login.windows.net", _logger);

            Assert.AreSame(result, result2);

            InstanceDiscoveryMetadataEntry result3 = userMetadataProvider.GetMetadataOrThrow("login.partner.microsoftonline.cn", _logger);

            Assert.IsNotNull(result3);

            MsalClientException ex;

            ex = Assert.ThrowsException <MsalClientException>(() => userMetadataProvider.GetMetadataOrThrow("non_existent", _logger));
            Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode);
            ex = Assert.ThrowsException <MsalClientException>(() => userMetadataProvider.GetMetadataOrThrow(null, _logger));
            Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode);
            ex = Assert.ThrowsException <MsalClientException>(() => userMetadataProvider.GetMetadataOrThrow("", _logger));
            Assert.AreEqual(MsalError.InvalidUserInstanceMetadata, ex.ErrorCode);
        }
        private async Task ValidateSelfEntryAsync(Uri authority)
        {
            using (MockHttpAndServiceBundle harness = CreateTestHarness())
            {
                InstanceDiscoveryMetadataEntry entry = await harness.ServiceBundle.InstanceDiscoveryManager
                                                       .GetMetadataEntryAsync(
                    authority.AbsoluteUri,
                    new RequestContext(harness.ServiceBundle, Guid.NewGuid()))
                                                       .ConfigureAwait(false);

                InstanceDiscoveryMetadataEntry entry2 = await harness.ServiceBundle.InstanceDiscoveryManager
                                                        .GetMetadataEntryTryAvoidNetworkAsync(
                    authority.AbsoluteUri,
                    new[] { "some_env" },
                    new RequestContext(harness.ServiceBundle, Guid.NewGuid()))
                                                        .ConfigureAwait(false);

                Assert.AreEqual(authority.Host, entry.PreferredCache);
                Assert.AreEqual(authority.Host, entry.PreferredNetwork);
                Assert.AreEqual(authority.Host, entry.Aliases.Single());

                Assert.AreEqual(authority.Host, entry2.PreferredCache);
                Assert.AreEqual(authority.Host, entry2.PreferredNetwork);
                Assert.AreEqual(authority.Host, entry2.Aliases.Single());
            }
        }
        public async Task SuccessfulResponseFromLocalImdsAsync()
        {
            AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(TestConstants.Region));

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            validateInstanceMetadata(regionalMetadata);
        }
        public async Task SuccessfulResponseFromEnvironmentVariableAsync()
        {
            Environment.SetEnvironmentVariable(TestConstants.RegionName, TestConstants.Region);

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.TryGetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            ValidateInstanceMetadata(regionalMetadata);
        }
Exemple #10
0
        public async Task SuccessfulResponseFromLocalImdsAsync()
        {
            AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(TestConstants.Region));

            IRegionDiscoveryProvider       regionDiscoveryProvider = new RegionDiscoveryProvider(_httpManager, new NetworkCacheMetadataProvider());
            InstanceDiscoveryMetadataEntry regionalMetadata        = await regionDiscoveryProvider.GetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            Assert.IsNotNull(regionalMetadata);
            Assert.AreEqual("centralus.login.microsoft.com", regionalMetadata.PreferredNetwork);
        }
Exemple #11
0
        private string GetPreferredEnvironmentHost(string environmentHost, InstanceDiscoveryMetadataEntry metadata)
        {
            string preferredEnvironmentHost = environmentHost;

            if (metadata != null)
            {
                preferredEnvironmentHost = metadata.PreferredCache;
            }

            return(preferredEnvironmentHost);
        }
        public async Task InvalidImdsAsync(string region)
        {
            AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(region)); // IMDS will return an invalid region

            _testRequestContext.ServiceBundle.Config.AzureRegion =
                ConfidentialClientApplication.AttemptRegionDiscovery;

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(
                new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            Assert.IsNull(regionalMetadata, "Discovery requested, but it failed.");
        }
Exemple #13
0
        public async Task SuccessfulResponseFromEnvironmentVariableAsync()
        {
            Environment.SetEnvironmentVariable(TestConstants.RegionName, TestConstants.Region);

            _testRequestContext.ServiceBundle.Config.AzureRegion = null; // not configured

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(
                new Uri("https://login.microsoftonline.com/common/"), _testRequestContext)
                                                              .ConfigureAwait(false);

            Assert.IsNull(regionalMetadata);
        }
        public async Task SuccessfulResponseFromUserProvidedRegionAsync()
        {
            AddMockedResponse(MockHelpers.CreateNullMessage(System.Net.HttpStatusCode.NotFound));
            _testRequestContext.ServiceBundle.Config.AuthorityInfo.RegionToUse = TestConstants.Region;

            IRegionDiscoveryProvider       regionDiscoveryProvider = new RegionDiscoveryProvider(_httpManager, new NetworkCacheMetadataProvider());
            InstanceDiscoveryMetadataEntry regionalMetadata        = await regionDiscoveryProvider.TryGetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            Assert.IsNotNull(regionalMetadata);
            Assert.AreEqual("centralus.login.microsoft.com", regionalMetadata.PreferredNetwork);
            regionDiscoveryProvider.Clear();
        }
        public async Task ResponseFromUserProvidedRegionDifferentFromRegionDetectedAsync()
        {
            Environment.SetEnvironmentVariable(TestConstants.RegionName, "eastus");
            _testRequestContext.ServiceBundle.Config.AuthorityInfo.RegionToUse = TestConstants.Region;

            IRegionDiscoveryProvider       regionDiscoveryProvider = new RegionDiscoveryProvider(_httpManager, new NetworkCacheMetadataProvider());
            InstanceDiscoveryMetadataEntry regionalMetadata        = await regionDiscoveryProvider.TryGetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            Assert.IsNotNull(regionalMetadata);
            Assert.AreEqual("eastus.login.microsoft.com", regionalMetadata.PreferredNetwork);
            regionDiscoveryProvider.Clear();
        }
        private async Task UpdateAuthorityWithPreferredNetworkHostAsync()
        {
            InstanceDiscoveryMetadataEntry metadata = await
                                                      ServiceBundle.InstanceDiscoveryManager.GetMetadataEntryAsync(
                AuthenticationRequestParameters.AuthorityInfo.CanonicalAuthority,
                AuthenticationRequestParameters.RequestContext)
                                                      .ConfigureAwait(false);

            AuthenticationRequestParameters.Authority = Authority.CreateAuthorityWithEnvironment(
                AuthenticationRequestParameters.AuthorityInfo,
                metadata.PreferredNetwork);
        }
Exemple #17
0
        private void ValidateInstanceMetadata(InstanceDiscoveryMetadataEntry entry)
        {
            InstanceDiscoveryMetadataEntry expectedEntry = new InstanceDiscoveryMetadataEntry()
            {
                Aliases          = new[] { "centralus.login.microsoft.com", "login.microsoftonline.com" },
                PreferredCache   = "login.microsoftonline.com",
                PreferredNetwork = "centralus.login.microsoft.com"
            };

            CollectionAssert.AreEquivalent(expectedEntry.Aliases, entry.Aliases);
            Assert.AreEqual(expectedEntry.PreferredCache, entry.PreferredCache);
            Assert.AreEqual(expectedEntry.PreferredNetwork, entry.PreferredNetwork);
        }
        public async Task SuccessfulResponseFromRegionalizedAuthorityAsync()
        {
            var regionalizedAuthority = new Uri($"https://{TestConstants.Region}.login.microsoft.com/common/");

            Environment.SetEnvironmentVariable(TestConstants.RegionName, TestConstants.Region);

            // In the instance discovery flow, TryGetMetadataAsync is always called with a known authority first, then with regionalized.
            await _regionDiscoveryProvider.TryGetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.TryGetMetadataAsync(regionalizedAuthority, _testRequestContext).ConfigureAwait(false);

            ValidateInstanceMetadata(regionalMetadata);
        }
Exemple #19
0
        public async Task NonPublicCloudTestAsync()
        {
            // Arrange
            Environment.SetEnvironmentVariable(TestConstants.RegionName, TestConstants.Region);
            _testRequestContext.ServiceBundle.Config.AzureRegion = ConfidentialClientApplication.AttemptRegionDiscovery;

            // Act
            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(new Uri("https://login.someenv.com/common/"), _testRequestContext).ConfigureAwait(false);

            // Assert
            Assert.IsNotNull(regionalMetadata);
            Assert.AreEqual("centralus.login.someenv.com", regionalMetadata.PreferredNetwork);
        }
        public async Task FetchRegionFromLocalImdsThenGetMetadataFromCacheAsync()
        {
            AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(TestConstants.Region));

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.TryGetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            ValidateInstanceMetadata(regionalMetadata);

            //get metadata from the instance metadata cache
            regionalMetadata = await _regionDiscoveryProvider.TryGetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            ValidateInstanceMetadata(regionalMetadata);
        }
        private void ValidateInstanceMetadata(InstanceDiscoveryMetadataEntry entry, string region = "centralus")
        {
            InstanceDiscoveryMetadataEntry expectedEntry = new InstanceDiscoveryMetadataEntry()
            {
                Aliases          = new[] { $"{region}.{RegionDiscoveryProvider.PublicEnvForRegional}", "login.microsoftonline.com" },
                PreferredCache   = "login.microsoftonline.com",
                PreferredNetwork = $"{region}.{RegionDiscoveryProvider.PublicEnvForRegional}"
            };

            CollectionAssert.AreEquivalent(expectedEntry.Aliases, entry.Aliases);
            Assert.AreEqual(expectedEntry.PreferredCache, entry.PreferredCache);
            Assert.AreEqual(expectedEntry.PreferredNetwork, entry.PreferredNetwork);
        }
        public async Task ResponseFromUserProvidedRegionSameAsRegionDetectedAsync()
        {
            Environment.SetEnvironmentVariable(TestConstants.RegionName, TestConstants.Region);
            _testRequestContext.ServiceBundle.Config.AzureRegion = TestConstants.Region;

            //            IRegionDiscoveryProvider regionDiscoveryProvider = new RegionDiscoveryProvider(_httpManager);
            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            Assert.IsNotNull(regionalMetadata);
            Assert.AreEqual($"centralus.{RegionDiscoveryProvider.PublicEnvForRegional}", regionalMetadata.PreferredNetwork);
            Assert.AreEqual(TestConstants.Region, _testRequestContext.ApiEvent.RegionUsed);
            Assert.AreEqual((int)RegionAutodetectionSource.EnvVariable, _testRequestContext.ApiEvent.RegionAutodetectionSource);
            Assert.AreEqual((int)RegionOutcome.UserProvidedValid, _testRequestContext.ApiEvent.RegionOutcome);
        }
        public async Task InvalidRegionEnvVariableAsync(string region)
        {
            Environment.SetEnvironmentVariable(TestConstants.RegionName, region);

            AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(TestConstants.Region)); // IMDS will return a valid region

            _testRequestContext.ServiceBundle.Config.AzureRegion =
                ConfidentialClientApplication.AttemptRegionDiscovery;

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(
                new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            ValidateInstanceMetadata(regionalMetadata);
        }
Exemple #24
0
        public async Task UpdateApiversionWhenCurrentVersionExpiresForImdsAsync()
        {
            AddMockedResponse(MockHelpers.CreateNullMessage(System.Net.HttpStatusCode.BadRequest));
            AddMockedResponse(MockHelpers.CreateFailureMessage(System.Net.HttpStatusCode.BadRequest, File.ReadAllText(
                                                                   ResourceHelper.GetTestResourceRelativePath("local-imds-error-response.json"))), expectedParams: false);
            AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(File.ReadAllText(
                                                                           ResourceHelper.GetTestResourceRelativePath("local-imds-response.json"))), apiVersion: "2020-10-01");

            IRegionDiscoveryProvider       regionDiscoveryProvider = new RegionDiscoveryProvider(_httpManager, new NetworkCacheMetadataProvider());
            InstanceDiscoveryMetadataEntry regionalMetadata        = await regionDiscoveryProvider.GetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            Assert.IsNotNull(regionalMetadata);
            Assert.AreEqual("centralus.login.microsoft.com", regionalMetadata.PreferredNetwork);
        }
        public async Task ErrorResponseFromLocalImdsAsync()
        {
            AddMockedResponse(MockHelpers.CreateNullMessage(System.Net.HttpStatusCode.NotFound));
            _testRequestContext.ServiceBundle.Config.AzureRegion = ConfidentialClientApplication.AttemptRegionDiscovery;

            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.
                                                              GetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext)
                                                              .ConfigureAwait(false);

            Assert.IsNull(regionalMetadata, "Discovery requested, but it failed.");

            Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed);
            Assert.AreEqual((int)RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource);
            Assert.AreEqual((int)RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome);
        }
Exemple #26
0
        private async Task <Account> ConvertToMsalAccountOrNullAsync(
            string clientId,
            WebAccount webAccount,
            InstanceDiscoveryMetadataEntry envMetadata,
            ICacheSessionManager cacheManager,
            IEnumerable <IAccount> accountsFromCache)
        {
            webAccount.Properties.TryGetValue("TenantId", out string realm);

            if (!_wamProxy.TryGetAccountProperty(webAccount, "Authority", out string accountAuthority))
            {
                _logger.WarningPii(
                    $"[WAM AAD Provider] Could not convert the WAM account {webAccount.UserName} (id: {webAccount.Id}) to an MSAL account because the Authority could not be found",
                    $"[WAM AAD Provider] Could not convert the WAM account {webAccount.Id} to an MSAL account because the Authority could not be found");

                return(null);
            }

            string accountEnv = (new Uri(accountAuthority)).Host;

            if (!envMetadata.Aliases.ContainsOrdinalIgnoreCase(accountEnv))
            {
                _logger.InfoPii(
                    $"[WAM AAD Provider] Account {webAccount.UserName} enviroment {accountEnv} does not match input authority env {envMetadata.PreferredNetwork} or an alias",
                    $"[WAM AAD Provider] Account enviroment {accountEnv} does not match input authority env {envMetadata.PreferredNetwork}");

                return(null);
            }

            if (MatchCacheAccount(webAccount, accountsFromCache, out AccountId homeAccountId))
            {
                _logger.VerbosePii(
                    $"[WAM AAD Provider] ConvertToMsalAccountOrNullAsync account {webAccount.UserName} matched a cached account",
                    $"[WAM AAD Provider] Account matched a cache account");


                return(new Account(
                           homeAccountId.Identifier,
                           webAccount.UserName,
                           envMetadata.PreferredNetwork,
                           new Dictionary <string, string>()
                {
                    { clientId, webAccount.Id }
                }));
            }

            return(await GetIdFromWebResponseAsync(clientId, webAccount, envMetadata, cacheManager).ConfigureAwait(false));
        }
Exemple #27
0
        public async Task ResponseMissingRegionFromLocalImdsAsync()
        {
            // Arrange
            AddMockedResponse(MockHelpers.CreateSuccessResponseMessage(string.Empty));
            _testRequestContext.ServiceBundle.Config.AzureRegion = ConfidentialClientApplication.AttemptRegionDiscovery;

            // Act
            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            // Assert
            Assert.IsNull(regionalMetadata, "Discovery requested, but it failed.");
            Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed);
            Assert.AreEqual(RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource);
            Assert.AreEqual(RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome);
            Assert.IsTrue(_testRequestContext.ApiEvent.RegionDiscoveryFailureReason.Contains(TestConstants.RegionAutoDetectOkFailureMessage));
        }
Exemple #28
0
        public async Task ResponseFromUserProvidedRegionDifferentFromRegionDetectedAsync()
        {
            Environment.SetEnvironmentVariable(TestConstants.RegionName, "detected_region");
            _testRequestContext.ServiceBundle.Config.AzureRegion = "user_region";

            //IRegionDiscoveryProvider regionDiscoveryProvider = new RegionDiscoveryProvider(_httpManager, new NetworkCacheMetadataProvider());
            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(
                new Uri("https://login.microsoftonline.com/common/"),
                _testRequestContext).ConfigureAwait(false);

            Assert.IsNotNull(regionalMetadata);
            Assert.AreEqual("user_region.login.microsoft.com", regionalMetadata.PreferredNetwork);
            Assert.AreEqual("user_region", _testRequestContext.ApiEvent.RegionUsed);
            Assert.AreEqual((int)RegionAutodetectionSource.EnvVariable, _testRequestContext.ApiEvent.RegionAutodetectionSource);
            Assert.AreEqual((int)RegionOutcome.UserProvidedInvalid, _testRequestContext.ApiEvent.RegionOutcome);
        }
        public async Task UpdateApiversionFailsWithEmptyResponseBodyAsync()
        {
            // Arrange
            AddMockedResponse(MockHelpers.CreateNullMessage(System.Net.HttpStatusCode.BadRequest));
            AddMockedResponse(MockHelpers.CreateNullMessage(System.Net.HttpStatusCode.BadRequest), expectedParams: false);
            _testRequestContext.ServiceBundle.Config.AzureRegion = ConfidentialClientApplication.AttemptRegionDiscovery;

            // Act
            InstanceDiscoveryMetadataEntry regionalMetadata = await _regionDiscoveryProvider.GetMetadataAsync(new Uri("https://login.microsoftonline.com/common/"), _testRequestContext).ConfigureAwait(false);

            // Assert
            Assert.IsNull(regionalMetadata, "Discovery requested, but it failed.");
            Assert.AreEqual(null, _testRequestContext.ApiEvent.RegionUsed);
            Assert.AreEqual((int)RegionAutodetectionSource.FailedAutoDiscovery, _testRequestContext.ApiEvent.RegionAutodetectionSource);
            Assert.AreEqual((int)RegionOutcome.FallbackToGlobal, _testRequestContext.ApiEvent.RegionOutcome);
        }
Exemple #30
0
        private InstanceDiscoveryMetadataEntry GetCachedAuthorityMetaData(string authority)
        {
            if (ServiceBundle?.AadInstanceDiscovery == null)
            {
                return(null);
            }

            InstanceDiscoveryMetadataEntry instanceDiscoveryMetadata = null;
            var authorityType = Authority.GetAuthorityType(authority);

            if (authorityType == AuthorityType.Aad || authorityType == AuthorityType.B2C)
            {
                ServiceBundle.AadInstanceDiscovery.TryGetValue(new Uri(authority).Host, out instanceDiscoveryMetadata);
            }
            return(instanceDiscoveryMetadata);
        }