Esempio n. 1
0
        public void NullArgs()
        {
            using (var harness = new MockHttpAndServiceBundle())
            {
                var bundle = harness.ServiceBundle;

                AuthenticationRequestParameters requestParams = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityHomeTenant,
                    TestConstants.s_scope,
                    new TokenCache(harness.ServiceBundle, false));

                var interactiveParameters = new AcquireTokenInteractiveParameters
                {
                    Prompt = Prompt.SelectAccount,
                    ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(),
                };

                var webUi = NSubstitute.Substitute.For <IWebUI>();

                AssertException.Throws <ArgumentNullException>(() =>
                                                               new InteractiveRequest(null, requestParams, interactiveParameters, webUi));
                AssertException.Throws <ArgumentNullException>(() =>
                                                               new InteractiveRequest(bundle, null, interactiveParameters, webUi));
                AssertException.Throws <ArgumentNullException>(() =>
                                                               new InteractiveRequest(bundle, requestParams, null, webUi));
            }
        }
Esempio n. 2
0
        public void WithTenantIdExceptions()
        {
            var app1 = ConfidentialClientApplicationBuilder
                       .Create(TestConstants.ClientId)
                       .WithAdfsAuthority(TestConstants.ADFSAuthority)
                       .WithClientSecret("secret")
                       .Build();

            var ex1 = AssertException.Throws <MsalClientException>(() =>
                                                                   app1
                                                                   .AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code")
                                                                   .WithTenantId(TestConstants.TenantId));

            var app2 = ConfidentialClientApplicationBuilder
                       .Create(TestConstants.ClientId)
                       .WithB2CAuthority(TestConstants.B2CAuthority)
                       .WithClientSecret("secret")
                       .Build();

            var ex2 = AssertException.Throws <MsalClientException>(() =>
                                                                   app2
                                                                   .AcquireTokenByAuthorizationCode(TestConstants.s_scope, "code")
                                                                   .WithTenantId(TestConstants.TenantId));

            Assert.AreEqual(ex1.ErrorCode, MsalError.TenantOverrideNonAad);
            Assert.AreEqual(ex2.ErrorCode, MsalError.TenantOverrideNonAad);
        }
        public void AuthorityMismatchTest()
        {
            var ex = AssertException.Throws <MsalClientException>(() =>
                                                                  Authority.CreateAuthorityForRequest(s_utidAuthority, s_b2cAuthority, null));

            Assert.AreEqual(MsalError.AuthorityTypeMismatch, ex.ErrorCode);
        }
Esempio n. 4
0
        public void MalformedAuthorityInitTest()
        {
            PublicClientApplication publicClient = null;
            var expectedAuthority = String.Concat("https://", TestConstants.ProductionPrefNetworkEnvironment, "/", TestConstants.TenantId, "/");

            //Check bad URI format
            var host          = String.Concat("test", TestConstants.ProductionPrefNetworkEnvironment, "/");
            var fullAuthority = String.Concat(host, TestConstants.TenantId);

            AssertException.Throws <UriFormatException>(() =>
            {
                publicClient = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                               .WithAuthority(fullAuthority)
                               .BuildConcrete();
            });

            //Check empty path segments
            host          = String.Concat("https://", TestConstants.ProductionPrefNetworkEnvironment, "/");
            fullAuthority = String.Concat(host, TestConstants.TenantId, "//");

            publicClient = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                           .WithAuthority(host, new Guid(TestConstants.TenantId))
                           .BuildConcrete();

            Assert.AreEqual(publicClient.Authority, expectedAuthority);

            //Check additional path segments
            fullAuthority = String.Concat(host, TestConstants.TenantId, "/ABCD!@#$TEST//");

            publicClient = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                           .WithAuthority(new Uri(fullAuthority))
                           .BuildConcrete();

            Assert.AreEqual(publicClient.Authority, expectedAuthority);
        }
Esempio n. 5
0
        public void NoAuthPrefix()
        {
            var scheme             = new SSHCertAuthenticationScheme("kid", "jwk");
            MsalClientException ex = AssertException.Throws <MsalClientException>(() => scheme.AuthorizationHeaderPrefix);

            Assert.AreEqual(MsalError.SSHCertUsedAsHttpHeader, ex.ErrorCode);
        }
Esempio n. 6
0
 public void NullArgs()
 {
     AssertException.Throws <ArgumentNullException>(() => new SSHCertAuthenticationScheme(null, "jwk"));
     AssertException.Throws <ArgumentNullException>(() => new SSHCertAuthenticationScheme("", "jwk"));
     AssertException.Throws <ArgumentNullException>(() => new SSHCertAuthenticationScheme("kid", ""));
     AssertException.Throws <ArgumentNullException>(() => new SSHCertAuthenticationScheme("kid", null));
 }
Esempio n. 7
0
        public void TestConstructor_BadInstanceMetadata()
        {
            var ex = AssertException.Throws <MsalClientException>(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                                                                  .WithInstanceDicoveryMetadata("{bad_json_metadata")
                                                                  .Build());

            Assert.AreEqual(ex.ErrorCode, MsalError.InvalidUserInstanceMetadata);
        }
            public void Start_Throws_InvalidOperationException_When_ServiceAlreadyStarted()
            {
                _liveStreamMonitor = new LiveStreamMonitorService(_api);
                _liveStreamMonitor.SetChannelsById(Utils.CreateListWithEmptyString());
                _liveStreamMonitor.Start();

                AssertException.Throws <InvalidOperationException>(AlreadyStartedExceptionMessage, () => _liveStreamMonitor.Start());
            }
Esempio n. 9
0
            public void Start_Throws_InvalidOperationException_When_ServiceAlreadyStarted()
            {
                _followerService = new FollowerService(_api);
                _followerService.SetChannelsById(Utils.CreateListWithEmptyString());
                _followerService.Start();

                AssertException.Throws <InvalidOperationException>(AlreadyStartedExceptionMessage, () => _followerService.Start());
            }
        private static void RunAuthenticationParametersNegative(string authenticateHeader)
        {
            var ex = AssertException.Throws <ArgumentException>(() =>
                                                                AuthenticationParameters.CreateFromResponseAuthenticateHeader(authenticateHeader),
                                                                allowDerived: true);

            Assert.AreEqual("authenticateHeader", ex.ParamName);
            Assert.IsTrue(string.IsNullOrWhiteSpace(authenticateHeader) || ex.Message.Contains("header format"));
        }
Esempio n. 11
0
        public void TestConstructor_InstanceMetadataUri_ValidateAuthority_MutuallyExclusive()
        {
            var ex = AssertException.Throws <MsalClientException>(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                                                  .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com"))
                                                                  .WithAuthority("https://some.authority/bogus/", true)
                                                                  .Build());

            Assert.AreEqual(ex.ErrorCode, MsalError.ValidateAuthorityOrCustomMetadata);
        }
Esempio n. 12
0
 public void NetFwkPlatformNotAvailable()
 {
     AssertException.Throws <PlatformNotSupportedException>(() =>
                                                            PublicClientApplicationBuilder
                                                            .Create(TestConstants.ClientId)
                                                            .WithExperimentalFeatures(true)
                                                            .WithBroker()
                                                            .Build());
 }
        public void AddParametersForLookupField_FieldNull_Throws()
        {
            // Arrange
            // Act
            Action action = () => _controlDataBuilder.AddParametersForLookupField(null);

            // Assert
            AssertException.Throws <ArgumentNullException>(action);
        }
Esempio n. 14
0
        public void ConcurrentDictionary_TestExceptions()
        {
            var dictionary = new ConcurrentDictionary <string, int>();

            AssertException.Throws <ArgumentNullException>(
                () => dictionary.TryAdd(null, 0));
            //  "TestExceptions:  FAILED.  TryAdd didn't throw ANE when null key is passed");

            AssertException.Throws <ArgumentNullException>(
                () => dictionary.ContainsKey(null));
            // "TestExceptions:  FAILED.  Contains didn't throw ANE when null key is passed");

            int item;

            AssertException.Throws <ArgumentNullException>(
                () => dictionary.TryRemove(null, out item));
            //  "TestExceptions:  FAILED.  TryRemove didn't throw ANE when null key is passed");
            AssertException.Throws <ArgumentNullException>(
                () => dictionary.TryGetValue(null, out item));
            // "TestExceptions:  FAILED.  TryGetValue didn't throw ANE when null key is passed");

            AssertException.Throws <ArgumentNullException>(
                () => { var x = dictionary[null]; });
            // "TestExceptions:  FAILED.  this[] didn't throw ANE when null key is passed");
            AssertException.Throws <KeyNotFoundException>(
                () => { var x = dictionary["1"]; });
            // "TestExceptions:  FAILED.  this[] TryGetValue didn't throw KeyNotFoundException!");

            AssertException.Throws <ArgumentNullException>(
                () => dictionary[null] = 1);
            // "TestExceptions:  FAILED.  this[] didn't throw ANE when null key is passed");

            AssertException.Throws <ArgumentNullException>(
                () => dictionary.GetOrAdd(null, (k) => 0));
            // "TestExceptions:  FAILED.  GetOrAdd didn't throw ANE when null key is passed");
            AssertException.Throws <ArgumentNullException>(
                () => dictionary.GetOrAdd("1", null));
            // "TestExceptions:  FAILED.  GetOrAdd didn't throw ANE when null valueFactory is passed");
            AssertException.Throws <ArgumentNullException>(
                () => dictionary.GetOrAdd(null, 0));
            // "TestExceptions:  FAILED.  GetOrAdd didn't throw ANE when null key is passed");

            AssertException.Throws <ArgumentNullException>(
                () => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0));
            // "TestExceptions:  FAILED.  AddOrUpdate didn't throw ANE when null key is passed");
            AssertException.Throws <ArgumentNullException>(
                () => dictionary.AddOrUpdate("1", null, (k, v) => 0));
            // "TestExceptions:  FAILED.  AddOrUpdate didn't throw ANE when null updateFactory is passed");
            AssertException.Throws <ArgumentNullException>(
                () => dictionary.AddOrUpdate(null, (k) => 0, null));
            // "TestExceptions:  FAILED.  AddOrUpdate didn't throw ANE when null addFactory is passed");

            dictionary.TryAdd("1", 1);
            AssertException.Throws <ArgumentException>(
                () => ((IDictionary <string, int>)dictionary).Add("1", 2));
            // "TestExceptions:  FAILED.  IDictionary didn't throw AE when duplicate key is passed");
        }
Esempio n. 15
0
 public void RequestParamsNullArg()
 {
     using (var harness = new MockHttpTestHarness(TestConstants.AuthorityHomeTenant))
     {
         AssertException.Throws <ArgumentNullException>(() => harness.CreateRequestParams(
                                                            null,
                                                            TestConstants.s_scope,
                                                            authorityOverride: AuthorityInfo.FromAuthorityUri(TestConstants.AuthorityHomeTenant, false)));
     }
 }
Esempio n. 16
0
        public void TestConstructor_InstanceMetadata_ValidateAuthority_MutuallyExclusive()
        {
            string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json"));
            var    ex = AssertException.Throws <MsalClientException>(() => ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                                                                     .WithInstanceDicoveryMetadata(instanceMetadataJson)
                                                                     .WithAuthority("https://some.authority/bogus/", true)
                                                                     .Build());

            Assert.AreEqual(ex.ErrorCode, MsalError.ValidateAuthorityOrCustomMetadata);
        }
Esempio n. 17
0
        public void NullArgsTest()
        {
            Uri                uri               = new Uri("https://www.contoso.com/path1/path2?queryParam1=a&queryParam2=b");
            HttpMethod         method            = HttpMethod.Post;
            HttpRequestMessage httpRequest       = new HttpRequestMessage(method, uri);
            var                popCryptoProvider = Substitute.For <IPoPCryptoProvider>();

            AssertException.Throws <ArgumentNullException>(() => new PoPAuthenticationScheme(null, popCryptoProvider));
            AssertException.Throws <ArgumentNullException>(() => new PoPAuthenticationScheme(httpRequest, null));
        }
Esempio n. 18
0
        public void ParamValidation()
        {
            AssertException.Throws <ArgumentNullException>(() => MsalExceptionFactory.GetClientException(null, ExMessage));
            AssertException.Throws <ArgumentNullException>(() => MsalExceptionFactory.GetClientException("", ExMessage));

            AssertException.Throws <ArgumentNullException>(
                () => MsalExceptionFactory.GetServiceException(ExCode, "", new ExceptionDetail()));

            AssertException.Throws <ArgumentNullException>(
                () => MsalExceptionFactory.GetServiceException(ExCode, null, new ExceptionDetail()));
        }
        public void ParamValidation()
        {
            AssertException.Throws <ArgumentNullException>(() => new MsalClientException(null, ExMessage));
            AssertException.Throws <ArgumentNullException>(() => new MsalClientException(string.Empty, ExMessage));

            AssertException.Throws <ArgumentNullException>(
                () => new MsalServiceException(ExCode, string.Empty));

            AssertException.Throws <ArgumentNullException>(
                () => new MsalServiceException(ExCode, null));
        }
Esempio n. 20
0
        public void VendingMachine_AcceptCoin_NullCoinEntered()
        {
            // Arrange
            _coinService.Setup(mock => mock.GetCoin(It.IsAny <decimal>(), It.IsAny <decimal>(), It.IsAny <decimal>())).Returns(() => null);

            // Act
            var vendingMachine = new VendingMachine(_coinService.Object, _productService.Object);

            // Assert
            AssertException.Throws <ArgumentNullException>(() => vendingMachine.AcceptCoin(null), "Value cannot be null.\r\nParameter name: Coin parameter null!");
        }
Esempio n. 21
0
        public void VendingMachine_SelectProduct_InvalidCode_ExceptionThrown()
        {
            // Arrange
            _coinService.Setup(mock => mock.GetCoin(It.IsAny <decimal>(), It.IsAny <decimal>(), It.IsAny <decimal>())).Returns(() => null);

            // Act
            var vendingMachine = new VendingMachine(_coinService.Object, _productService.Object);

            // Assert
            AssertException.Throws <ArgumentNullException>(() => vendingMachine.SelectProduct(""), "Value cannot be null.\r\nParameter name: Code parameter empty!");
        }
Esempio n. 22
0
        public void TestConstructor_WithInstanceDiscoveryMetadata_OnlyOneOverload()
        {
            string instanceMetadataJson = File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("CustomInstanceMetadata.json"));
            var    ex = AssertException.Throws <MsalClientException>(() => PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                                                     .WithInstanceDiscoveryMetadata(instanceMetadataJson)
                                                                     .WithInstanceDiscoveryMetadata(new Uri("https://some_uri.com"))
                                                                     .WithAuthority("https://some.authority/bogus/", true)
                                                                     .Build());

            Assert.AreEqual(ex.ErrorCode, MsalError.CustomMetadataInstanceOrUri);
        }
        public void OptionsAndExternalCacheAreExclusive()
        {
            var app =
                ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                .WithClientSecret(TestConstants.ClientSecret)
                .WithCacheOptions(CacheOptions.EnableSharedCacheOptions)
                .Build();

            AssertExclusivity(app.UserTokenCache);
            AssertExclusivity(app.AppTokenCache);

            var app2 =
                ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                .WithClientSecret(TestConstants.ClientSecret)
                .Build();

            app2.AppTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions);
            app2.UserTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions);

            AssertExclusivity(app2.AppTokenCache);
            AssertExclusivity(app2.UserTokenCache);

            var app3 =
                ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                .WithClientSecret(TestConstants.ClientSecret)
                .Build();

            app3.UserTokenCache.SetAfterAccess((n) => { });
            app3.AppTokenCache.SetBeforeAccess((n) => { });
            var ex = AssertException.Throws <MsalClientException>(() => app3.UserTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions));

            Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);
            ex = AssertException.Throws <MsalClientException>(() => app3.AppTokenCache.SetCacheOptions(CacheOptions.EnableSharedCacheOptions));
            Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);

            void AssertExclusivity(ITokenCache tokenCache)
            {
                var ex = AssertException.Throws <MsalClientException>(() => tokenCache.SetAfterAccess((n) => { }));

                Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);
                ex = AssertException.Throws <MsalClientException>(() => tokenCache.SetBeforeAccess((n) => { }));
                Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);
                ex = AssertException.Throws <MsalClientException>(() => tokenCache.SetBeforeWrite((n) => { }));
                Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);

                ex = AssertException.Throws <MsalClientException>(() => tokenCache.SetBeforeAccessAsync((n) => Task.CompletedTask));
                Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);
                ex = AssertException.Throws <MsalClientException>(() => tokenCache.SetAfterAccessAsync((n) => Task.CompletedTask));
                Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);
                ex = AssertException.Throws <MsalClientException>(() => tokenCache.SetBeforeWriteAsync((n) => Task.CompletedTask));
                Assert.AreEqual(MsalError.StaticCacheWithExternalSerialization, ex.ErrorCode);
            }
        }
Esempio n. 24
0
        private void AssertBadTcpMeesage(string message)
        {
            // Arrange
            var logger = Substitute.For <ICoreLogger>();

            // Act
            var ex = AssertException.Throws <MsalClientException>(
                () => HttpResponseParser.ExtractUriFromHttpRequest(message, logger));

            // Assert
            Assert.AreEqual(MsalError.InvalidAuthorizationUri, ex.ErrorCode);
            logger.Received(1).ErrorPii(Arg.Any <string>(), Arg.Any <string>());
        }
        public void AddParameter_ExistingKey_Throws()
        {
            // Arrange
            const string newKey   = "test-key";
            object       newValue = 1;

            // Act
            _controlDataBuilder.AddParameter(newKey, newValue);
            Action action = () => _controlDataBuilder.AddParameter(newKey, newValue);

            // Assert
            AssertException.Throws <ArgumentException>(action);
        }
        public void ValidateAuthorityTest()
        {
            var ex = AssertException.Throws <MsalClientException>(
                () => ConfidentialClientApplicationBuilder
                .Create(TestConstants.ClientId)
                .WithAuthority(
                    new System.Uri(ClientApplicationBase.DefaultAuthority) /* validate is true by default */)
                .WithClientSecret(TestConstants.ClientSecret)
                .WithAzureRegion()
                .Build());

            Assert.AreEqual(MsalError.RegionalAuthorityValidation, ex.ErrorCode);
        }
        public void NetCoreFactory_Embedded()
        {
            // Arrange

            // Act
            var ex = AssertException.Throws <MsalClientException>(
                () => _webUIFactory.CreateAuthenticationDialog(
                    _parent,
                    WebViewPreference.Embedded,
                    _requestContext));

            // Assert
            Assert.AreEqual(MsalError.WebviewUnavailable, ex.ErrorCode);
        }
        public void StringReplace()
        {
            Assert.AreEqual("hi common !", "hi {tenant} !".Replace("{tenant}", "common", StringComparison.OrdinalIgnoreCase));
            Assert.AreEqual("hi commoncommon !", "hi {tenant}{tenant} !".Replace("{tenant}", "common", StringComparison.OrdinalIgnoreCase));
            Assert.AreEqual("hi common--common !", "hi {tenant}--{tenant} !".Replace("{tenant}", "common", StringComparison.OrdinalIgnoreCase));
            Assert.AreEqual("hi common !", "hi {tenaNt} !".Replace("{tEnant}", "common", StringComparison.OrdinalIgnoreCase));

            Assert.AreEqual("hi common !", "hi {tenant_id} !".Replace("{tenant_ID}", "common", StringComparison.OrdinalIgnoreCase));
            Assert.AreEqual("hi {tenant_id} !", "hi {tenant_id} !".Replace("nothing", "common", StringComparison.OrdinalIgnoreCase));

            Assert.AreEqual("", "".Replace("nothing", "common", StringComparison.OrdinalIgnoreCase));
            AssertException.Throws <ArgumentException>(() =>
                                                       "hi {tenant} !".Replace("", "common", StringComparison.OrdinalIgnoreCase));
        }
Esempio n. 29
0
        public void TestExecuteWithRetry_OperationFails()
        {
            //Arrange
            const int numberOfRetriesToAttempt   = 3;
            const int numberOfFailuresToSimulate = 3;

            var operationSimulator   = new OperationSimulator(numberOfFailuresToSimulate);
            Func <Task <bool> > func = () => operationSimulator.SimulateOperationWithFailuresAsync();

            //Act
            Exception ex = AssertException.Throws <AggregateException>(
                () => RetryOperationHelper.ExecuteWithRetryAsync(func, numberOfRetriesToAttempt).Wait());

            Assert.AreEqual(ex.InnerException.Message, "OperationSimulator: Simulating Operation Failure");
        }
Esempio n. 30
0
        public void RemoveAtTest()
        {
            ISchedule scheduleToRemove = theScheduler.Add(new TimeSpan(0, 0, 12), true);

            Assert.IsTrue(theScheduler.Contains(scheduleToRemove));
            int scheduleIndex = theScheduler.IndexOf(scheduleToRemove);

            theScheduler.RemoveAt(scheduleIndex);
            Assert.IsFalse(theScheduler.Contains(scheduleToRemove));

            scheduleIndex = -1;
            AssertException.Throws <ArgumentOutOfRangeException, int>(new ArgumentOutOfRangeException(), theScheduler.RemoveAt, scheduleIndex);
            scheduleIndex = theScheduler.Count + 1;
            AssertException.Throws <ArgumentOutOfRangeException, int>(new ArgumentOutOfRangeException(), theScheduler.RemoveAt, scheduleIndex);
        }