public async Task ApplySecurityContractAsync_WithApplicationServiceThrowingException_ExceptionThrown() { //Arrange var securityContractClientService = Substitute.For <ISecurityContractClientService>(); var securityContractDefaultConfigurationService = Substitute.For <ISecurityContractDefaultConfigurationService>(); var securityContractApplicationService = Substitute.For <ISecurityContractApplicationService>(); // A security contract with all it's sub components set to null is a valid security contract. var securityContract = new SecurityContract(); securityContract.DefaultConfigurations = new List <SecurityContractDefaultConfiguration> { new SecurityContractDefaultConfiguration { Name = "test default configuration" } }; securityContractDefaultConfigurationService.ApplyDefaultConfigurationDefinitionAsync(Arg.Any <SecurityContractDefaultConfiguration>(), Arg.Any <Guid>(), Arg.Any <bool>(), Arg.Any <SecurityContractDryRunResult>()).Returns(x => throw new Exception()); var securityContractService = new SecurityContractService(securityContractApplicationService, securityContractClientService, securityContractDefaultConfigurationService); Exception caughtException = null; try { await securityContractService.ApplySecurityContractDefinitionAsync(securityContract, Guid.NewGuid()); } catch (Exception ex) { caughtException = ex; } Assert.True(caughtException is Exception); }
public async Task <ActionResult> SetRoleFunctions(int roleId, string strFuncIds) { var funcIds = JsonToEntity <Guid[]>(strFuncIds); var result = await SecurityContract.SetRoleFunctions(roleId, funcIds); return(Json(result.ToAjaxResult())); }
public ActionResult EditEntityInfoData(EntityInfoDto[] dtos) { dtos.CheckNotNull("dtos"); OperationResult result = SecurityContract.EditEntityInfos(dtos); return(Json(result.ToAjaxResult())); }
public async Task <ActionResult> DeleteFunctions(Guid[] ids) { ids.CheckNotNull("ids"); OperationResult result = await SecurityContract.DeleteFunctions(ids); return(Json(result.ToAjaxResult())); }
public async Task <ActionResult> EditFunctionData(FunctionDto[] dtos) { dtos.CheckNotNull("dtos"); OperationResult result = await SecurityContract.EditFunctions(dtos); return(Json(result.ToAjaxResult())); }
public async Task ApplySecurityContractDefaultsAsync_WithValidNoSectionsInput_NoExceptionsThrown() { // Set up the required security contract defaults service with all its dependencies mocked. var roleRepository = Substitute.For <IRoleRepository>(); var userRepository = Substitute.For <IUserRepository>(); var functionRepository = Substitute.For <IFunctionRepository>(); var teamRepository = Substitute.For <ITeamRepository>(); var applicationRepository = Substitute.For <IApplicationRepository>(); var applicationDataPolicyRepository = Substitute.For <IApplicationDataPolicyRepository>(); var ldapAuthenticationModeRepository = Substitute.For <ILdapAuthenticationModeRepository>(); securityContractDefaultConfigurationService = new SecurityContractDefaultConfigurationService(roleRepository, userRepository, functionRepository, teamRepository, applicationRepository, applicationDataPolicyRepository, ldapAuthenticationModeRepository); // Create a security contract with a default configuration section, but dont set any of the sub components. var securityContract = new SecurityContract(); securityContract.DefaultConfigurations = new List <SecurityContractDefaultConfiguration> { new SecurityContractDefaultConfiguration { Name = "Test without sub sections" } }; try { await securityContractDefaultConfigurationService.ApplyDefaultConfigurationDefinitionAsync(securityContract.DefaultConfigurations.First(), Guid.NewGuid(), false, new SecurityContractDryRunResult()); Assert.True(true); } catch (Exception e) { Assert.True(false, $"Unexpected Exception: '{e.Message}' thrown when applying security contract"); } }
public async Task ApplySecurityContractDefinitionAsync(SecurityContract securityContract, Guid updatedById, bool dryRun = false) { // Start transactions to allow complete rollback in case of an error BeginAllTransactions(); try { SecurityContractDryRunResult securityContractDryRunResult = new SecurityContractDryRunResult(); // First apply all of the application(micro-service) definitions that present within the Security Contract. // All the components of a security contract are optional, so check for this here. if (securityContract.Applications != null && securityContract.Applications.Count > 0) { foreach (var applicationSecurityContractDefinition in securityContract.Applications) { await securityContractApplicationService.ApplyResourceServerDefinitionAsync(applicationSecurityContractDefinition, updatedById, dryRun, securityContractDryRunResult); } } // Apply any clients that may be defined within the security contract. if (securityContract.Clients != null && securityContract.Clients.Count > 0) { foreach (var clientSecurityContractDefinition in securityContract.Clients) { await clientService.ApplyClientDefinitionAsync(clientSecurityContractDefinition, dryRun, securityContractDryRunResult); } } // Apply any default configurations that may be defined within the security contract. if (securityContract.DefaultConfigurations != null && securityContract.DefaultConfigurations.Count > 0) { foreach (var defaultConfiguration in securityContract.DefaultConfigurations) { await securityContractDefaultConfigurationService.ApplyDefaultConfigurationDefinitionAsync(defaultConfiguration, updatedById, dryRun, securityContractDryRunResult); } } if (!dryRun) { // All successful CommitAllTransactions(); } else { var securityContractDryRunException = new SecurityContractDryRunException { ValidationErrors = securityContractDryRunResult.ValidationErrors, ValidationWarnings = securityContractDryRunResult.ValidationWarnings }; throw securityContractDryRunException; } } catch { RollbackAllTransactions(); throw; } }
public async override Task <IActionResult> ApplySecurityContractAsync([FromBody] SecurityContract securityContract) { if (securityContract == null) { return(BadRequest()); } var loggedOnUser = ClaimsHelper.GetScalarClaimValue <Guid>(User, ClaimTypes.NameIdentifier, Guid.Empty); await securityContractService.ApplySecurityContractDefinitionAsync(securityContract, loggedOnUser); return(NoContent()); }
public async override Task <IActionResult> ValidateSecurityContractAsync([FromBody] SecurityContract securityContract) { if (securityContract == null) { return(BadRequest()); } var loggedOnUser = ClaimsHelper.GetScalarClaimValue <Guid>(User, ClaimTypes.NameIdentifier, Guid.Empty); // This service will throw a custom exception (which is not really an exception) for returning the response. await securityContractService.ApplySecurityContractDefinitionAsync(securityContract, loggedOnUser, true); return(NoContent()); }
public async Task ApplySecurityContractAsync_WithValidNoSectionsInput_ReturnsNoContent() { // Arrange var securityContractService = Substitute.For <ISecurityContractService>(); var controller = new SecurityContractController(securityContractService); // A security contract with all it's sub components set to null is a valid security contract. var securityContract = new SecurityContract(); // Act var actionResult = await controller.ApplySecurityContractAsync(securityContract); // Assert var NoContent = actionResult as NoContentResult; Assert.NotNull(NoContent); }
public async Task ApplySecurityContractDefinitionAsync(SecurityContract securityContract, Guid updatedById) { // Start transactions to allow complete rollback in case of an error BeginAllTransactions(); try { // First apply all of the application(micro-service) definitions that present within the Security Contract. // All the components of a security contract are optional, so check for this here. if (securityContract.Applications != null && securityContract.Applications.Count > 0) { foreach (var applicationSecurityContractDefinition in securityContract.Applications) { await securityContractApplicationService.ApplyResourceServerDefinitionAsync(applicationSecurityContractDefinition, updatedById); } } // Apply any clients that may be defined within the security contract. if (securityContract.Clients != null && securityContract.Clients.Count > 0) { foreach (var clientSecurityContractDefinition in securityContract.Clients) { await clientService.ApplyClientDefinitionAsync(clientSecurityContractDefinition); } } // Apply any default configurations that may be defined within the security contract. if (securityContract.DefaultConfigurations != null && securityContract.DefaultConfigurations.Count > 0) { foreach (var defaultConfiguration in securityContract.DefaultConfigurations) { await securityContractDefaultConfigurationService.ApplyDefaultConfigurationDefinitionAsync(defaultConfiguration, updatedById); } } // All successful CommitAllTransactions(); } catch (Exception ex) { logger.Error(ex); RollbackAllTransactions(); throw; } }
public async Task <SecurityContract> GetSecurityContractDefinitionAsync() { var securityContract = new SecurityContract() { Applications = new List <SecurityContractApplication>(), Clients = new List <Oauth2ClientSubmit>(), DefaultConfigurations = new List <SecurityContractDefaultConfiguration>() }; // Retrieve all Application definitions securityContract.Applications.AddRange(await securityContractApplicationService.GetResourceServerDefinitionsAsync()); // Retrieve all Client definitions securityContract.Clients.AddRange(await clientService.GetClientDefinitionsAsync()); // Retrieve all Default Configuration definitions securityContract.DefaultConfigurations.Add(await securityContractDefaultConfigurationService.GetDefaultConfigurationDefinitionAsync()); return(securityContract); }
private void InitializeMainSecurities() { using (ISession session = DBSessionFactory.Instance.OpenSession()) { List <ManagedSecurity> managedSecuritiesList = session.Query <ManagedSecurity>().Where(ms => ms.IsActive).ToList(); Securities = new Dictionary <string, SecurityData>(); foreach (var security in managedSecuritiesList) { var stockContract = new SecurityContract(security.Symbol, security.SecurityType, security.Exchange, security.Currency); Securities.Add(stockContract.Symbol, new SecurityData() { SecurityContract = stockContract }); } } }
public async Task ApplySecurityContractAsync_WithValidNoSectionsInput_NoExceptionsThrown() { //Arrange var securityContractClientService = Substitute.For <ISecurityContractClientService>(); var securityContractDefaultConfigurationService = Substitute.For <ISecurityContractDefaultConfigurationService>(); var securityContractApplicationService = Substitute.For <ISecurityContractApplicationService>(); // A security contract with all it's sub components set to null is a valid security contract. var securityContract = new SecurityContract(); var securityContractService = new SecurityContractService(securityContractApplicationService, securityContractClientService, securityContractDefaultConfigurationService); try { await securityContractService.ApplySecurityContractDefinitionAsync(securityContract, Guid.NewGuid()); Assert.True(true); } catch (Exception e) { Assert.True(false, $"Unexpected Exception: '{e.Message}' thrown when applying security contract"); } }
public async Task ApplySecurityContractAsync_WithValidHighLevelSecurityContractInput_NoExceptionsThrown() { //Arrange var securityContractClientService = Substitute.For <ISecurityContractClientService>(); var securityContractDefaultConfigurationService = Substitute.For <ISecurityContractDefaultConfigurationService>(); var securityContractApplicationService = Substitute.For <ISecurityContractApplicationService>(); // A security contract with all it's sub components set to null is a valid security contract. var securityContract = new SecurityContract(); securityContract.Applications = new List <SecurityContractApplication> { new SecurityContractApplication { Fullname = "Test application" } }; securityContract.Clients = new List <Oauth2ClientSubmit> { new Oauth2ClientSubmit { ClientId = "test-client-id", Name = "Test-Client-Name", AllowedOfflineAccess = true, AllowedCorsOrigins = new List <string> { "http://test-cors-origin.com" }, ClientSecrets = new List <string> { "test-client-secret" }, PostLogoutRedirectUris = new List <string> { "http://test-post-logout-uri.com" }, AllowedGrantTypes = new List <string> { "password" }, AllowedScopes = new List <string> { "test-client-scope" }, RedirectUris = new List <string> { "http://test-redirect-uri.com" } } }; securityContract.DefaultConfigurations = new List <SecurityContractDefaultConfiguration> { new SecurityContractDefaultConfiguration { Name = "test default configuration" } }; var securityContractService = new SecurityContractService(securityContractApplicationService, securityContractClientService, securityContractDefaultConfigurationService); try { await securityContractService.ApplySecurityContractDefinitionAsync(securityContract, Guid.NewGuid()); Assert.True(true); } catch (Exception e) { Assert.True(false, $"Unexpected Exception: '{e.Message}' thrown when applying security contract"); } }
public async Task GetSecurityContractAsync_WithValidHighLevelSecurityContractInput_NoExceptionsThrown() { //Arrange var securityContractClientService = Substitute.For <ISecurityContractClientService>(); var securityContractDefaultConfigurationService = Substitute.For <ISecurityContractDefaultConfigurationService>(); var securityContractApplicationService = Substitute.For <ISecurityContractApplicationService>(); var securityContractService = new SecurityContractService(securityContractApplicationService, securityContractClientService, securityContractDefaultConfigurationService); securityContractClientService.GetClientDefinitionsAsync().Returns(new List <Oauth2ClientSubmit> { new Oauth2ClientSubmit { ClientId = "test-client-id", Name = "Test-Client-Name", AllowedOfflineAccess = true, AllowedCorsOrigins = new List <string> { "http://test-cors-origin.com" }, ClientSecrets = new List <string> { "test-client-secret" }, PostLogoutRedirectUris = new List <string> { "http://test-post-logout-uri.com" }, AllowedGrantTypes = new List <string> { "password" }, AllowedScopes = new List <string> { "test-client-scope" }, RedirectUris = new List <string> { "http://test-redirect-uri.com" } } }); securityContractApplicationService.GetResourceServerDefinitionsAsync().Returns(new List <SecurityContractApplication> { new SecurityContractApplication { Fullname = "Test application" } }); securityContractDefaultConfigurationService.GetDefaultConfigurationDefinitionAsync().Returns(new SecurityContractDefaultConfiguration { Name = "test default configuration" }); // Act SecurityContract retrievedSecurityContract = null; try { retrievedSecurityContract = await securityContractService.GetSecurityContractDefinitionAsync(); Assert.True(true); } catch (Exception e) { Assert.True(false, $"Unexpected Exception: '{e.Message}' thrown when retrieving security contract"); } // Assert Assert.True(retrievedSecurityContract != null, "Retrieved security contract should not be null"); Assert.True(retrievedSecurityContract.Clients != null && retrievedSecurityContract.Clients.Count > 0, "Retrieved security contract Clients should not be null or empty"); Assert.True(retrievedSecurityContract.Applications != null && retrievedSecurityContract.Applications.Count > 0, "Retrieved security contract Applications should not be null or empty"); Assert.True(retrievedSecurityContract.DefaultConfigurations != null && retrievedSecurityContract.DefaultConfigurations.Count > 0, "Retrieved security contract DefaultConfigurations should not be null or empty"); Assert.True(retrievedSecurityContract.Clients[0].Name == "Test-Client-Name", "Retrieved client Name should be 'Test-Client-Name'"); Assert.True(retrievedSecurityContract.Applications[0].Fullname == "Test application", "Retrieved Applications Fullname should be 'Test application'"); Assert.True(retrievedSecurityContract.DefaultConfigurations[0].Name == "test default configuration", "Retrieved DefaultConfigurations name should be 'test default configuration'"); }
public abstract Task <IActionResult> ValidateSecurityContractAsync([FromBody] SecurityContract securityContract);
public abstract Task <IActionResult> ApplySecurityContractAsync([FromBody] SecurityContract securityContract);
public async Task ApplySecurityContractDefaultsAsync_UsersWithRolesInInput_UsersAndRolesExistInDB_NoExceptionsThrown() { // Set up the required security contract defaults service with all its dependencies mocked. var roleRepository = Substitute.For <IRoleRepository>(); var userRepository = Substitute.For <IUserRepository>(); var functionRepository = Substitute.For <IFunctionRepository>(); var teamRepository = Substitute.For <ITeamRepository>(); var applicationRepository = Substitute.For <IApplicationRepository>(); var applicationDataPolicyRepository = Substitute.For <IApplicationDataPolicyRepository>(); var ldapAuthenticationModeRepository = Substitute.For <ILdapAuthenticationModeRepository>(); // The service will check for existing roles within the database, we want a result to test existing role. roleRepository.GetByNameAsync(Arg.Any <string>()).Returns(new RoleModel { Name = "Test Role Model", RoleFunctions = new List <RoleFunctionModel> { new RoleFunctionModel { Function = new FunctionModel { Name = "Function in role test" } } } }); // The service will also check that the users exist. Ensure the repo returns one to test that flow. userRepository.GetByUsernameAsync(Arg.Any <string>(), Arg.Any <bool>()).Returns(new UserModel { UserName = "******", Email = "*****@*****.**" }); // The service should attempt an update on the users, ensure this is possible. userRepository.UpdateAsync(Arg.Any <UserModel>()).Returns(new UserModel { UserName = "******", Email = "*****@*****.**" }); securityContractDefaultConfigurationService = new SecurityContractDefaultConfigurationService(roleRepository, userRepository, functionRepository, teamRepository, applicationRepository, applicationDataPolicyRepository, ldapAuthenticationModeRepository); // Create a security contract with a default configuration section, but dont set any of the sub components. var securityContract = new SecurityContract(); securityContract.DefaultConfigurations = new List <SecurityContractDefaultConfiguration> { new SecurityContractDefaultConfiguration { Name = "Test with application section", Users = new List <SecurityContractDefaultConfigurationUser> { new SecurityContractDefaultConfigurationUser { Username = "******", Email = "*****@*****.**" } } } }; try { await securityContractDefaultConfigurationService.ApplyDefaultConfigurationDefinitionAsync(securityContract.DefaultConfigurations.First(), Guid.NewGuid(), false, new SecurityContractDryRunResult()); Assert.True(true); } catch (Exception e) { Assert.True(false, $"Unexpected Exception: '{e.Message}' thrown when applying security contract"); } }
public async Task ApplySecurityContractDefaultsAsync_RolesWithFunctionsInInput_FunctionsExistInDBRoleIsNew_NoExceptionsThrown() { // Set up the required security contract defaults service with all its dependencies mocked. var roleRepository = Substitute.For <IRoleRepository>(); var userRepository = Substitute.For <IUserRepository>(); var functionRepository = Substitute.For <IFunctionRepository>(); var teamRepository = Substitute.For <ITeamRepository>(); var applicationRepository = Substitute.For <IApplicationRepository>(); var applicationDataPolicyRepository = Substitute.For <IApplicationDataPolicyRepository>(); var ldapAuthenticationModeRepository = Substitute.For <ILdapAuthenticationModeRepository>(); // The service will check for existing roles within the database, we a null here to test new role creation. roleRepository.GetByNameAsync(Arg.Any <string>()).Returns((RoleModel)null); // Owing to the fact that all roles are found, the service will update model. Ensure that this can happen. roleRepository.CreateAsync(Arg.Any <RoleModel>()).Returns(new RoleModel { Name = "Test Role Model", RoleFunctions = new List <RoleFunctionModel> { new RoleFunctionModel { Function = new FunctionModel { Name = "Function in role test" } } } }); // The service will also check that the functions attached to the roles exist. Ensure the repo returns one to test that flow. functionRepository.GetByNameAsync(Arg.Any <string>()).Returns(new FunctionModel { Name = "Test Role Model", }); securityContractDefaultConfigurationService = new SecurityContractDefaultConfigurationService(roleRepository, userRepository, functionRepository, teamRepository, applicationRepository, applicationDataPolicyRepository, ldapAuthenticationModeRepository); // Create a security contract with a default configuration section, but dont set any of the sub components. var securityContract = new SecurityContract(); securityContract.DefaultConfigurations = new List <SecurityContractDefaultConfiguration> { new SecurityContractDefaultConfiguration { Name = "Test with application section", Roles = new List <SecurityContractDefaultConfigurationRole> { new SecurityContractDefaultConfigurationRole { Name = "Test security contract role", Functions = new List <string> { "Test function in contract" } } } } }; try { await securityContractDefaultConfigurationService.ApplyDefaultConfigurationDefinitionAsync(securityContract.DefaultConfigurations.First(), Guid.NewGuid(), false, new SecurityContractDryRunResult()); Assert.True(true); } catch (Exception e) { Assert.True(false, $"Unexpected Exception: '{e.Message}' thrown when applying security contract"); } }
public async Task GetSecurityContractAsync_Executed_ReturnsSecurityContract() { // Arrange var securityContractService = Substitute.For <ISecurityContractService>(); var controller = new SecurityContractController(securityContractService); // A security contract with all it's sub components set to null is a valid security contract. var securityContract = new SecurityContract(); securityContract.Applications = new List <SecurityContractApplication> { new SecurityContractApplication { Fullname = "Test application" } }; securityContract.Clients = new List <Oauth2ClientSubmit> { new Oauth2ClientSubmit { ClientId = "test-client-id", Name = "Test-Client-Name", AllowedOfflineAccess = true, AllowedCorsOrigins = new List <string> { "http://test-cors-origin.com" }, ClientSecrets = new List <string> { "test-client-secret" }, PostLogoutRedirectUris = new List <string> { "http://test-post-logout-uri.com" }, AllowedGrantTypes = new List <string> { "password" }, AllowedScopes = new List <string> { "test-client-scope" }, RedirectUris = new List <string> { "http://test-redirect-uri.com" } } }; securityContract.DefaultConfigurations = new List <SecurityContractDefaultConfiguration> { new SecurityContractDefaultConfiguration { Name = "test default configuration" } }; securityContractService.GetSecurityContractDefinitionAsync().Returns(securityContract); // Act var actionResult = await controller.GetSecurityContractAsync(); // Assert var okResult = actionResult as OkObjectResult; Assert.NotNull(okResult); var outContract = okResult.Value as SecurityContract; Assert.NotNull(outContract); Assert.True(outContract != null, "Retrieved security contract should not be null"); Assert.True(outContract.Clients != null && outContract.Clients.Count > 0, "Retrieved security contract Clients should not be null or empty"); Assert.True(outContract.Applications != null && outContract.Applications.Count > 0, "Retrieved security contract Applications should not be null or empty"); Assert.True(outContract.DefaultConfigurations != null && outContract.DefaultConfigurations.Count > 0, "Retrieved security contract DefaultConfigurations should not be null or empty"); Assert.True(outContract.Clients[0].Name == "Test-Client-Name", "Retrieved client Name should be 'Test-Client-Name'"); Assert.True(outContract.Applications[0].Fullname == "Test application", "Retrieved Applications Fullname should be 'Test application'"); Assert.True(outContract.DefaultConfigurations[0].Name == "test default configuration", "Retrieved DefaultConfigurations name should be 'test default configuration'"); }
public async Task ApplySecurityContractDefaultsAsync_TeamsWithUsersInInput_UsersAndTeamsExistInDB_NoExceptionsThrown() { // Set up the required security contract defaults service with all its dependencies mocked. var roleRepository = Substitute.For <IRoleRepository>(); var userRepository = Substitute.For <IUserRepository>(); var functionRepository = Substitute.For <IFunctionRepository>(); var teamRepository = Substitute.For <ITeamRepository>(); var applicationRepository = Substitute.For <IApplicationRepository>(); var applicationDataPolicyRepository = Substitute.For <IApplicationDataPolicyRepository>(); var ldapAuthenticationModeRepository = Substitute.For <ILdapAuthenticationModeRepository>(); // The service will check for existing teams within the database, we a null here to test new role creation. teamRepository.GetByNameAsync(Arg.Any <string>(), Arg.Any <bool>()).Returns(new TeamModel { Name = "Test existing team model" }); // Owing to the fact that all roles are found, the service will update the team model. Ensure that this can happen. teamRepository.UpdateAsync(Arg.Any <TeamModel>()).Returns(new TeamModel { Name = "Test existing team model" }); // The service will also check that the users attached to the teams exist. Ensure the repo returns one to test that flow. userRepository.GetByUsernameAsync(Arg.Any <string>(), Arg.Any <bool>()).Returns(new UserModel { UserName = "******", }); securityContractDefaultConfigurationService = new SecurityContractDefaultConfigurationService(roleRepository, userRepository, functionRepository, teamRepository, applicationRepository, applicationDataPolicyRepository, ldapAuthenticationModeRepository); // Create a security contract with a default configuration section, but dont set any of the sub components. var securityContract = new SecurityContract(); securityContract.DefaultConfigurations = new List <SecurityContractDefaultConfiguration> { new SecurityContractDefaultConfiguration { Name = "Test with application section", Teams = new List <SecurityContractDefaultConfigurationTeam> { new SecurityContractDefaultConfigurationTeam { Name = "Test Team", Users = new List <string> { "test user name" } } } } }; try { await securityContractDefaultConfigurationService.ApplyDefaultConfigurationDefinitionAsync(securityContract.DefaultConfigurations.First(), Guid.NewGuid(), false, new SecurityContractDryRunResult()); Assert.True(true); } catch (Exception e) { Assert.True(false, $"Unexpected Exception: '{e.Message}' thrown when applying security contract"); } }