Exemple #1
0
        public void ValidateUser()
        {
            MockUser           mockUser = MockUser.CreateInitializedUser();
            MockAuthentication provider = new MockAuthentication();

            // Failure
            AuthenticationBaseTest.SetUserInProviders(null);
            MockUser user = provider.Login(string.Empty, string.Empty, false, null);

            Assert.IsTrue(provider.WasValidateUserInvoked,
                          "ValidateUser should have been invoked from Login.");

            Assert.IsFalse(provider.ValidateUserMock(string.Empty, string.Empty),
                           "ValidateUser should return false.");
            Assert.IsNull(user,
                          "Users should be null when ValidateUser returns false.");

            provider.WasValidateUserInvoked = false;

            // Success
            AuthenticationBaseTest.SetUserInProviders(mockUser);
            user = provider.Login(mockUser.Name, mockUser.Name, false, null);

            Assert.IsTrue(provider.WasValidateUserInvoked,
                          "ValidateUser should have been invoked from Login.");

            Assert.IsTrue(provider.ValidateUserMock(mockUser.Name, mockUser.Name),
                          "ValidateUser should return true.");
            Assert.IsNotNull(user,
                             "Users should not be null when ValidateUser returns true.");
        }
Exemple #2
0
        public void CreateUser()
        {
            MockUser           mockUser = MockUser.CreateDefaultUser();
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(mockUser);

            // GetUser(IIdentity)
            MockUser userGUM = provider.GetAuthenticatedUserMock(mockUser);

            Assert.IsTrue(provider.WasCreateUserInvoked,
                          "CreateUser should have been invoked from GetUser(IIdentity).");

            provider.WasCreateUserInvoked = false;

            // GetAnonymousUser
            MockUser userGAU = provider.GetAnonymousUserMock();

            Assert.IsTrue(provider.WasCreateUserInvoked,
                          "GetAnonymousUser should have been invoked from GetUser.");

            provider.WasGetAnonymousUserInvoked = false;

            Assert.IsNotNull(provider.CreateUserMock(),
                             "User should not be null.");
        }
        public async Task EnvironmentNotSupportedResultIs501NotSupported()
        {
            var validAuthentication = MockAuthentication.Get();
            var actionResponse      = new RegisterAction.Response
            {
                Type           = RegisterAction.ResponseType.EnvironmentNotSupported,
                ServerIdentity = new CaberIdentity {
                    Uuid = validAuthentication.ServerUuid.Value
                },
                Environment = new CaberSharedEnvironment()
            };
            var action = Mock.Of <RegisterAction>(a => a.Execute(It.IsAny <RegisterAction.Request>(), It.IsAny <ClaimsPrincipal>()) == actionResponse);

            using (var server = CreateServer(validAuthentication, action))
            {
                await server.StartAsync();

                var request = CreateMinimalValidRequest(validAuthentication);

                var response = await server.MakeClientRequest(validAuthentication,
                                                              $"/register/{validAuthentication.ClientUuid}",
                                                              HttpMethod.Post,
                                                              new StringContent(JsonConvert.SerializeObject(request)));

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotImplemented));
            }
        }
Exemple #4
0
        public void GetAnonymousUser()
        {
            MockUser           mockUser = MockUser.CreateDefaultUser();
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(mockUser);

            // Logout
            MockUser userL = provider.Logout();

            Assert.IsTrue(provider.WasGetAnonymousUserInvoked,
                          "GetAnonymousUser should have been invoked from Logout.");

            provider.WasGetAnonymousUserInvoked = false;

            // GetUser
            MockUser userGU = provider.GetUser();

            Assert.IsTrue(provider.WasGetAnonymousUserInvoked,
                          "GetAnonymousUser should have been invoked from GetUser.");

            provider.WasGetAnonymousUserInvoked = false;

            // Logout should return the same value as GetAnonymousUser
            AuthenticationBaseTest.CompareUsers(mockUser, provider.GetAnonymousUserMock(), true);
            AuthenticationBaseTest.CompareUsers(mockUser, userL, true);
            AuthenticationBaseTest.CompareUsers(mockUser, userGU, true);
        }
 private TestServer CreateServer(MockAuthentication authentication, ICaberRequestRouter router = null) =>
 new TestServer(
     new CaberServerBuilder {
     ServerUrl      = "https://localhost:0",
     Authentication = authentication,
     RequestRouter  = router ?? Mock.Of <ICaberRequestRouter>(r =>
                                                              r.Route(It.IsAny <CaberRequestContext>()) == new CaberRouteData {
         Route = new StatusCodeRoute(200), Parameters = new RouteValueDictionary()
     })
 });
Exemple #6
0
        private static HttpClient CreateClient(MockAuthentication authentication)
        {
            var clientHandler = new HttpClientHandler();

            if (authentication.ClientCertificate != null)
            {
                clientHandler.ClientCertificates.Add(authentication.ClientCertificate);
            }
            clientHandler.ServerCertificateCustomValidationCallback =
                (request, certificate, chain, policyErrors) => authentication.ValidateServerPeerCertificate(default, certificate, chain, policyErrors);
Exemple #7
0
        public void UpdateUserThrows()
        {
            MockUser           original = MockUser.CreateDefaultUser();
            MockUser           user     = MockUser.CreateInitializedUser();
            MockAuthentication provider =
                ServerTestHelper.CreateInitializedDomainService <MockAuthentication>(DomainOperationType.Submit);

            ExceptionHelper.ExpectException <UnauthorizedAccessException>(
                () => provider.UpdateUser(user));
        }
Exemple #8
0
        public void Logout()
        {
            MockUser           mockUser = MockUser.CreateDefaultUser();
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(mockUser);
            MockUser user = provider.Logout();

            AuthenticationBaseTest.CompareUsers(mockUser, user, true);
        }
Exemple #9
0
        public void LoginAndGetUser()
        {
            MockUser           mockUser = MockUser.CreateInitializedUser();
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(mockUser);
            MockUser user = provider.Login(mockUser.Name, mockUser.Name, false, null);

            AuthenticationBaseTest.CompareUsers(mockUser, user, true);
        }
Exemple #10
0
        public void LoginFailure()
        {
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(null);
            MockUser user = provider.Login(string.Empty, string.Empty, false, null);

            Assert.IsNull(user,
                          "The user should be null to indicate the Login was unsuccessful.");
        }
Exemple #11
0
        public void UpdateUser()
        {
            MockUser           original = MockUser.CreateDefaultUser();
            MockUser           user     = MockUser.CreateInitializedUser();
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(original);
            provider.UpdateUser(user);

            AuthenticationBaseTest.CompareUsers(user, original, false);
        }
Exemple #12
0
        public void ClearAuthenticationToken()
        {
            MockUser           mockUser = MockUser.CreateDefaultUser();
            MockAuthentication provider = new MockAuthentication();

            // Failure
            AuthenticationBaseTest.SetUserInProviders(null);
            MockUser user = provider.Logout();

            Assert.IsTrue(provider.WasClearAuthenticationTokenInvoked,
                          "ClearAuthenticationToken should have been invoked from Logout.");
        }
        private TestServer CreateServer(MockAuthentication authentication, RegisterAction action)
        {
            var server = new TestServer(
                new CaberServerBuilder
            {
                ServerUrl      = "https://localhost:0",
                Authentication = authentication
            });

            server.AddService(action);
            return(server);
        }
        public async Task RequestWithCertificatesAndHeaders_Yields200OK()
        {
            var validAuthentication = MockAuthentication.Get();

            using (var server = CreateServer(validAuthentication))
            {
                await server.StartAsync();

                var response = await server.MakeClientRequest(validAuthentication, "/Test/Default");

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            }
        }
 private static RegisterRoute.RequestDto CreateMinimalValidRequest(MockAuthentication validAuthentication)
 {
     return(new RegisterRoute.RequestDto
     {
         clientIdentity = new RegisterRoute.CaberIdentityDto {
             uuid = validAuthentication.ClientUuid.Value
         },
         serverIdentity = new RegisterRoute.CaberUuidDto {
             uuid = validAuthentication.ServerUuid.Value
         },
         environment = new RegisterRoute.EnvironmentDto(),
         roots = new RegisterRoute.RootDto[0]
     });
 }
Exemple #16
0
        public void ConvertSqlExceptions()
        {
            MockUser           mockUser = MockUser.CreateInitializedUser();
            MockAuthentication provider = new MockAuthentication();

            SqlException sqlEx = null;

            try
            {
                using (SqlConnection badConnection = new SqlConnection("Data Source=Nosource"))
                {
                    badConnection.Open();
                }
            }
            catch (SqlException sqlEx2)
            {
                sqlEx = sqlEx2;
            }

            // Membership
            string message = string.Format(
                CultureInfo.InvariantCulture,
                Resources.ApplicationServices_ProviderError,
                "Membership", sqlEx.Message);

            ((MockMembershipProvider)Membership.Provider).Error = sqlEx;
            ExceptionHelper.ExpectException <DomainException>(() =>
                                                              provider.Login(mockUser.Name, mockUser.Name, false, null), message);
            ((MockMembershipProvider)Membership.Provider).Error = null;

            // Roles
            message = string.Format(
                CultureInfo.InvariantCulture,
                Resources.ApplicationServices_ProviderError,
                "Role", sqlEx.Message);
            ((MockRoleProvider)Roles.Provider).Error = sqlEx;
            ExceptionHelper.ExpectException <DomainException>(() =>
                                                              provider.GetAuthenticatedUserMock(mockUser), message);
            ((MockRoleProvider)Roles.Provider).Error = null;

            // Profile
            message = string.Format(
                CultureInfo.InvariantCulture,
                Resources.ApplicationServices_ProviderError,
                "Profile", sqlEx.Message);
            ((MockProfileProvider)ProfileManager.Provider).Error = sqlEx;
            ExceptionHelper.ExpectException <DomainException>(() =>
                                                              provider.GetAuthenticatedUserMock(mockUser), message);
            ((MockProfileProvider)ProfileManager.Provider).Error = null;
        }
        public async Task NotKnownClientUuidAndCertificate_Yields200OK()
        {
            var authentication = MockAuthentication.Get();

            authentication.ValidatePeerIdentityResult = PeerIdentityValidationResult.NotOnRecord;

            using (var server = CreateServer(authentication))
            {
                await server.StartAsync();

                var response = await server.MakeClientRequest(authentication, "/Test/Default");

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            }
        }
Exemple #18
0
 public async Task <HttpResponseMessage> MakeClientRequest(MockAuthentication clientAuthentication, string relativeUri, HttpMethod method = null, HttpContent content = null)
 {
     using (var client = CreateClient(clientAuthentication))
     {
         return(await client.SendAsync(new HttpRequestMessage
         {
             RequestUri = new Uri(RootUri, relativeUri),
             Method = method ?? HttpMethod.Get,
             Headers =
             {
                 { CaberHeaders.RecipientUuid, clientAuthentication.ServerUuid.ToString() }
             },
             Content = content
         }));
     }
 }
        public async Task MismatchedClientUuidAndCertificate_Yields401Unauthorized()
        {
            var authentication = MockAuthentication.Get();

            authentication.ValidatePeerIdentityResult = PeerIdentityValidationResult.Mismatch;

            using (var server = CreateServer(authentication))
            {
                await server.StartAsync();

                var response = await server.MakeClientRequest(authentication, "/Test/Default");

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
                var message = JsonConvert.DeserializeObject <CaberAuthenticationFailureMessage>(await response.Content.ReadAsStringAsync());
                Assert.That(message.Reason, Is.EqualTo(CaberMutualAuthenticationFailureReason.ClientCertificateDoesNotMatchAnyKnownForTheClaimedUUID.ToString()));
            }
        }
        public async Task InvalidServerCertificate_YieldsClientError()
        {
            var authentication = MockAuthentication.Get();

            authentication.ServerCertificateIsValid = false;

            var router = Mock.Of <ICaberRequestRouter>();

            using (var server = CreateServer(authentication, router))
            {
                await server.StartAsync();

                var exception = Assert.CatchAsync <HttpRequestException>(() => server.MakeClientRequest(authentication, "/Test/Default"));
                Assert.That(exception.InnerException?.InnerException, Is.InstanceOf <AuthenticationException>());
                Assert.That(exception.InnerException?.InnerException?.Message, Does.Contain("remote certificate is invalid"));
                Mock.Get(router).Verify(r => r.Route(It.IsAny <CaberRequestContext>()), Times.Never);
            }
        }
        public async Task MissingClientCertificate_Yields401Unauthorized()
        {
            var validAuthentication = MockAuthentication.Get();

            using (var server = CreateServer(validAuthentication))
            {
                await server.StartAsync();

                var invalid = validAuthentication.Copy();
                invalid.ClientCertificate = null;

                var response = await server.MakeClientRequest(invalid, "/Test/Default");

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
                var message = JsonConvert.DeserializeObject <CaberAuthenticationFailureMessage>(await response.Content.ReadAsStringAsync());
                Assert.That(message.Reason, Is.EqualTo(CaberMutualAuthenticationFailureReason.NoClientCertificateProvided.ToString()));
            }
        }
        public async Task IncorrectXCaberRecipientHeader_Yields401Unauthorized()
        {
            var validAuthentication = MockAuthentication.Get();

            using (var server = CreateServer(validAuthentication))
            {
                await server.StartAsync();

                var invalid = validAuthentication.Copy();
                invalid.ServerUuid = Guid.NewGuid();

                var response = await server.MakeClientRequest(invalid, "/Test/Default");

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
                var message = JsonConvert.DeserializeObject <CaberAuthenticationFailureMessage>(await response.Content.ReadAsStringAsync());
                Assert.That(message.Reason, Is.EqualTo(CaberMutualAuthenticationFailureReason.ServerUUIDDoesNotReferToThisInstance.ToString()));
            }
        }
        public async Task UriClientUuidMismatchIs400BadRequest()
        {
            var validAuthentication = MockAuthentication.Get();
            var action = Mock.Of <RegisterAction>();

            using (var server = CreateServer(validAuthentication, action))
            {
                await server.StartAsync();

                var request = CreateMinimalValidRequest(validAuthentication);

                var response = await server.MakeClientRequest(validAuthentication,
                                                              $"/register/{Guid.NewGuid()}",
                                                              HttpMethod.Post,
                                                              new StringContent(JsonConvert.SerializeObject(request)));

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
            }
        }
        public async Task InvalidClientCertificate_YieldsErrorBeforeRouting()
        {
            var authentication = MockAuthentication.Get();

            authentication.ClientCertificateIsValid = false;

            var router = Mock.Of <ICaberRequestRouter>();

            using (var server = CreateServer(authentication, router))
            {
                await server.StartAsync();

                var exception = Assert.CatchAsync <HttpRequestException>(() => server.MakeClientRequest(authentication, "/Test/Default"));
                Assert.That(exception, Has.InnerException);
                Assert.That(exception, Has.InnerException.InnerException);
                Assert.That(exception, Has.InnerException.InnerException.Message.Contains("decryption"));
                Mock.Get(router).Verify(r => r.Route(It.IsAny <CaberRequestContext>()), Times.Never);
            }
        }
        public async Task MinimalValidRequestInvokesAction()
        {
            var validAuthentication = MockAuthentication.Get();
            var action = Mock.Of <RegisterAction>();

            using (var server = CreateServer(validAuthentication, action))
            {
                await server.StartAsync();

                var request = CreateMinimalValidRequest(validAuthentication);

                await server.MakeClientRequest(validAuthentication,
                                               $"/register/{validAuthentication.ClientUuid}",
                                               HttpMethod.Post,
                                               new StringContent(JsonConvert.SerializeObject(request)));

                Mock.Get(action).Verify(a => a.Execute(It.IsAny <RegisterAction.Request>(), It.IsAny <ClaimsPrincipal>()));
            }
        }
Exemple #26
0
        public void IssueAuthenticationToken()
        {
            MockUser           mockUser = MockUser.CreateInitializedUser();
            MockAuthentication provider = new MockAuthentication();

            // Failure
            AuthenticationBaseTest.SetUserInProviders(null);
            MockUser user = provider.Login(string.Empty, string.Empty, false, null);

            Assert.IsFalse(provider.WasIssueAuthenticationTokenInvoked,
                           "IssueAuthenticationToken should not have been invoked from a failed Login.");

            provider.WasIssueAuthenticationTokenInvoked = false;

            // Success
            AuthenticationBaseTest.SetUserInProviders(mockUser);
            user = provider.Login(mockUser.Name, mockUser.Name, false, null);

            Assert.IsTrue(provider.WasIssueAuthenticationTokenInvoked,
                          "ValidateUser should have been invoked from Login.");
        }
Exemple #27
0
        public void GetAuthenticatedUser()
        {
            MockUser           mockUser = MockUser.CreateInitializedUser();
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(mockUser);

            // Login
            MockUser user = provider.Login(mockUser.Name, mockUser.Name, false, null);

            Assert.IsTrue(provider.WasGetAuthenticatedUserInvoked,
                          "GetAuthenticatedUser should have been invoked from Login.");

            provider.WasGetAuthenticatedUserInvoked = false;

            // GetUser will always invoke GetAnonymousUser when testing

            // Login (and GetUser. See explanation on LoginAndGetUser) should return the same value as GetUser(IIdentity)
            AuthenticationBaseTest.CompareUsers(mockUser, provider.GetAuthenticatedUserMock(mockUser), true);
            AuthenticationBaseTest.CompareUsers(mockUser, user, true);
        }
Exemple #28
0
        public void UpdateUserCore()
        {
            MockUser           original = MockUser.CreateDefaultUser();
            MockUser           user     = MockUser.CreateInitializedUser();
            MockAuthentication provider = new MockAuthentication();

            AuthenticationBaseTest.SetUserInProviders(original);
            provider.UpdateUserCoreMock(user);

            AuthenticationBaseTest.CompareUsers(user, original, false);

            // These tests are only valid when we can call SetUser directly
            //MockUser originalUU = MockUser.CreateDefaultUser();

            //AspNetUserDomainServiceTest.SetUserInProviders(originalUU);
            //provider.UpdateUser(user, originalUU);

            //Assert.IsTrue(provider.WasUpdateUserCoreInvoked,
            //    "UpdateUserCore should have been invoked from UpdateUser.");

            //AspNetUserDomainServiceTest.CompareUsers(original, originalUU, false);
        }