diff --git a/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamApiSecurityConfig.java b/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamApiSecurityConfig.java index 71a14dd2b..7ba39077a 100644 --- a/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamApiSecurityConfig.java +++ b/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamApiSecurityConfig.java @@ -27,6 +27,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter; import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint; @@ -60,7 +61,8 @@ public static class IamProxyCertificateApiConfig extends WebSecurityConfigurerAd @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService); + auth.userDetailsService(userDetailsService) + .passwordEncoder(NoOpPasswordEncoder.getInstance()); } @Override diff --git a/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamTokenEndointSecurityConfig.java b/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamTokenEndointSecurityConfig.java index c9b7bdc09..b1bc9947c 100644 --- a/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamTokenEndointSecurityConfig.java +++ b/iam-login-service/src/main/java/it/infn/mw/iam/config/security/IamTokenEndointSecurityConfig.java @@ -32,6 +32,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter; import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint; @@ -68,7 +69,9 @@ public class IamTokenEndointSecurityConfig extends WebSecurityConfigurerAdapter @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService); + + auth.userDetailsService(userDetailsService) + .passwordEncoder(NoOpPasswordEncoder.getInstance()); } @Bean diff --git a/iam-login-service/src/main/java/it/infn/mw/iam/config/security/MitreSecurityConfig.java b/iam-login-service/src/main/java/it/infn/mw/iam/config/security/MitreSecurityConfig.java index c2260723c..1c214b56e 100644 --- a/iam-login-service/src/main/java/it/infn/mw/iam/config/security/MitreSecurityConfig.java +++ b/iam-login-service/src/main/java/it/infn/mw/iam/config/security/MitreSecurityConfig.java @@ -27,6 +27,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter; import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter; import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint; @@ -183,7 +184,8 @@ public static class IntrospectEndpointAuthorizationConfig extends WebSecurityCon @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService); + auth.userDetailsService(userDetailsService) + .passwordEncoder(NoOpPasswordEncoder.getInstance()); } @Override @@ -224,7 +226,8 @@ public static class RevokeEndpointAuthorizationConfig extends WebSecurityConfigu @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService); + auth.userDetailsService(userDetailsService) + .passwordEncoder(NoOpPasswordEncoder.getInstance()); } private ClientCredentialsTokenEndpointFilter clientCredentialsEndpointFilter() diff --git a/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultLoginPageConfiguration.java b/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultLoginPageConfiguration.java index 0604298b1..07ffe5367 100644 --- a/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultLoginPageConfiguration.java +++ b/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultLoginPageConfiguration.java @@ -17,7 +17,6 @@ import static it.infn.mw.iam.api.account_linking.AccountLinkingConstants.ACCOUNT_LINKING_DISABLE_PROPERTY; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -27,6 +26,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; import org.springframework.stereotype.Component; import com.google.common.base.Strings; @@ -69,20 +69,15 @@ public DefaultLoginPageConfiguration(OidcValidatedProviders providers, IamProper public void init() { oidcEnabled = !providers.getValidatedProviders().isEmpty(); - githubEnabled = activeProfilesContains("github"); - samlEnabled = activeProfilesContains("saml"); - registrationEnabled = activeProfilesContains("registration"); + githubEnabled = env.acceptsProfiles(Profiles.of("github")); + samlEnabled = env.acceptsProfiles(Profiles.of("saml")); + registrationEnabled = env.acceptsProfiles(Profiles.of("registration")); localAuthenticationVisible = IamProperties.LocalAuthenticationLoginPageMode.VISIBLE .equals(iamProperties.getLocalAuthn().getLoginPageVisibility()); showLinkToLocalAuthn = IamProperties.LocalAuthenticationLoginPageMode.HIDDEN_WITH_LINK .equals(iamProperties.getLocalAuthn().getLoginPageVisibility()); } - private boolean activeProfilesContains(String val) { - - return Arrays.asList(env.getActiveProfiles()).contains(val); - } - @Override public boolean isOidcEnabled() { diff --git a/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultStartRegistrationController.java b/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultStartRegistrationController.java index 37dbc1625..4397eb309 100644 --- a/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultStartRegistrationController.java +++ b/iam-login-service/src/main/java/it/infn/mw/iam/core/web/DefaultStartRegistrationController.java @@ -20,6 +20,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -34,13 +35,7 @@ public class DefaultStartRegistrationController { @Autowired public DefaultStartRegistrationController(Environment env) { - registrationProfileEnabled = false; - - for (String ap : env.getActiveProfiles()) { - if (REGISTRATION_PROFILE.equals(ap)) { - registrationProfileEnabled = true; - } - } + registrationProfileEnabled = env.acceptsProfiles(Profiles.of(REGISTRATION_PROFILE)); } @RequestMapping(method = RequestMethod.GET, path = "/start-registration") @@ -50,7 +45,7 @@ public String startRegistration(Authentication authentication) { && !authentication.getAuthorities().contains(EXT_AUTHN_UNREGISTERED_USER_AUTH)) { return "iam/dashboard"; } - + if (registrationProfileEnabled) { return "iam/register"; } else { diff --git a/iam-login-service/src/main/resources/application-mysql-test.yml b/iam-login-service/src/main/resources/application-mysql-test.yml index ad755999d..ebcb92672 100644 --- a/iam-login-service/src/main/resources/application-mysql-test.yml +++ b/iam-login-service/src/main/resources/application-mysql-test.yml @@ -15,8 +15,6 @@ # spring: - profiles: - include: mysql,registration,saml datasource: url: jdbc:mysql://${IAM_DB_HOST:dev.local.io}:${IAM_DB_PORT:3306}/${IAM_DB_NAME:iam}?useSSL=${IAM_DB_USE_SSL:false} diff --git a/iam-login-service/src/main/resources/application-prod.yml b/iam-login-service/src/main/resources/application-prod.yml index 3e7c0c807..3e8d61bea 100644 --- a/iam-login-service/src/main/resources/application-prod.yml +++ b/iam-login-service/src/main/resources/application-prod.yml @@ -15,8 +15,6 @@ # spring: - profiles: - include: mysql,flyway-repair flyway: locations: diff --git a/iam-login-service/src/main/resources/application.yml b/iam-login-service/src/main/resources/application.yml index 1acba4815..98ee373a3 100644 --- a/iam-login-service/src/main/resources/application.yml +++ b/iam-login-service/src/main/resources/application.yml @@ -44,6 +44,8 @@ spring: default: h2-test group: "h2-test": "h2,saml,registration" + "mysql-test": "mysql,saml,registration" + "prod": "mysql,flyway-repair" jpa: generate-ddl: true diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/actuator/ExternalServiceActuatorEndpointTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/actuator/ExternalServiceActuatorEndpointTests.java index 271ce682f..f1dc0d44a 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/actuator/ExternalServiceActuatorEndpointTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/actuator/ExternalServiceActuatorEndpointTests.java @@ -23,6 +23,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -42,6 +43,7 @@ @IamMockMvcIntegrationTest @IfProfileValue(name = "iam.offline", values = {"false", ""}) @ProfileValueSourceConfiguration(NullSafeSystemProfileValueSource.class) +@Ignore("We no longer have a dedicated health endpoint for external connectivity tests") public class ExternalServiceActuatorEndpointTests { private static final String ADMIN_USERNAME = "admin"; diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/api/account/find/FindAccountIntegrationTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/api/account/find/FindAccountIntegrationTests.java index f9a39d342..f2c2982c1 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/api/account/find/FindAccountIntegrationTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/api/account/find/FindAccountIntegrationTests.java @@ -256,6 +256,8 @@ public void findNotInGroupWorks() throws Exception { // Cleanup all group memberships and groups accountRepo.deleteAllAccountGroupMemberships(); + + groupRepo.deleteAll(); // Create group hierarchy @@ -275,9 +277,11 @@ public void findNotInGroupWorks() throws Exception { sibling = groupService.createGroup(sibling); + final long allUserCount = accountRepo.count(); + mvc.perform(get(FIND_NOT_IN_GROUP_RESOURCE, rootGroup.getUuid()).param("count", "10")) .andExpect(OK) - .andExpect(jsonPath("$.totalResults", is(253))); + .andExpect(jsonPath("$.totalResults", is((int) allUserCount))); mvc.perform(get(FIND_NOT_IN_GROUP_RESOURCE, rootGroup.getUuid()).param("filter", "admin")) .andExpect(OK) diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/ext_authn/saml/validator/SamlValidatorIntegrationTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/ext_authn/saml/validator/SamlValidatorIntegrationTests.java index 6d29d9987..c14c017f3 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/ext_authn/saml/validator/SamlValidatorIntegrationTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/ext_authn/saml/validator/SamlValidatorIntegrationTests.java @@ -53,7 +53,7 @@ @RunWith(SpringRunner.class) @IamMockMvcIntegrationTest -@SpringBootTest(classes = {IamLoginService.class}, +@SpringBootTest(classes = {IamLoginService.class, SamlValidatorIntegrationTests.TestConfig.class}, webEnvironment = WebEnvironment.MOCK) @WebAppConfiguration public class SamlValidatorIntegrationTests extends SamlAuthenticationTestSupport { diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTests.java index 1f7a76b67..0ce52f842 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTests.java @@ -29,6 +29,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; @@ -37,17 +38,21 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; +import it.infn.mw.iam.IamLoginService; import it.infn.mw.iam.core.lifecycle.ExpiredAccountsHandler; import it.infn.mw.iam.persistence.model.IamAccount; import it.infn.mw.iam.persistence.model.IamLabel; import it.infn.mw.iam.persistence.repository.IamAccountRepository; import it.infn.mw.iam.test.api.TestSupport; +import it.infn.mw.iam.test.core.CoreControllerTestSupport; import it.infn.mw.iam.test.lifecycle.cern.LifecycleTestSupport; import it.infn.mw.iam.test.util.annotation.IamMockMvcIntegrationTest; @RunWith(SpringRunner.class) @IamMockMvcIntegrationTest +@SpringBootTest(classes = {IamLoginService.class, CoreControllerTestSupport.class, + AccountLifecycleTests.TestConfig.class}) @TestPropertySource( properties = {"lifecycle.account.expiredAccountPolicy.suspensionGracePeriodDays=7", "lifecycle.account.expiredAccountPolicy.removalGracePeriodDays=30"}) diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTestsNoSuspensionGracePeriod.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTestsNoSuspensionGracePeriod.java index 8c767f3cf..d2945e51a 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTestsNoSuspensionGracePeriod.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/lifecycle/AccountLifecycleTestsNoSuspensionGracePeriod.java @@ -31,22 +31,30 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; +import it.infn.mw.iam.IamLoginService; import it.infn.mw.iam.core.lifecycle.ExpiredAccountsHandler; import it.infn.mw.iam.persistence.model.IamAccount; import it.infn.mw.iam.persistence.model.IamLabel; import it.infn.mw.iam.persistence.repository.IamAccountRepository; import it.infn.mw.iam.test.api.TestSupport; +import it.infn.mw.iam.test.core.CoreControllerTestSupport; import it.infn.mw.iam.test.lifecycle.cern.LifecycleTestSupport; import it.infn.mw.iam.test.util.annotation.IamMockMvcIntegrationTest; @RunWith(SpringRunner.class) @IamMockMvcIntegrationTest +@SpringBootTest( + classes = {IamLoginService.class, CoreControllerTestSupport.class, + AccountLifecycleTestsNoSuspensionGracePeriod.TestConfig.class}, + webEnvironment = WebEnvironment.MOCK) @TestPropertySource( properties = {"lifecycle.account.expiredAccountPolicy.suspensionGracePeriodDays=0", "lifecycle.account.expiredAccountPolicy.removalGracePeriodDays=30"}) diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/ImplicitFlowTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/ImplicitFlowTests.java index 8a6cfe5a4..69e4989c9 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/ImplicitFlowTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/ImplicitFlowTests.java @@ -149,7 +149,7 @@ public void testImplicitFlowSucceeds() throws Exception { .param("authorize", "Authorize") .param("remember", "until-revoked") .session(session)) - .andExpect(status().isFound()) + .andExpect(status().is3xxRedirection()) .andReturn().getResponse().getRedirectedUrl(); assertThat(redirectedUrl, startsWith(IMPLICIT_CLIENT_REDIRECT_URL+"#")); diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/TokenExchangeTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/TokenExchangeTests.java index 95900ef38..9fdc8f62f 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/TokenExchangeTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/TokenExchangeTests.java @@ -45,6 +45,7 @@ import org.springframework.test.context.junit4.SpringRunner; import com.fasterxml.jackson.databind.ObjectMapper; +import com.nimbusds.jose.shaded.json.JSONObject; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; @@ -53,7 +54,7 @@ import it.infn.mw.iam.persistence.model.IamAup; import it.infn.mw.iam.persistence.repository.IamAupRepository; import it.infn.mw.iam.test.util.annotation.IamMockMvcIntegrationTest; -import net.minidev.json.JSONObject; + diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/jwk/JWKEndpointTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/jwk/JWKEndpointTests.java index b1dde9b42..96c86a44b 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/jwk/JWKEndpointTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/jwk/JWKEndpointTests.java @@ -48,7 +48,7 @@ public void testKeys() throws Exception { .andExpect(jsonPath("$.keys[0].kty").value("RSA")) .andExpect(jsonPath("$.keys[0].e").value("AQAB")) .andExpect(jsonPath("$.keys[0].kid").value("rsa1")) - .andExpect(jsonPath("$.keys[0].n").value("nuvTJO-6RxIbIyYpPvAWeLSZ4o8o9T_lFU0ltiqAlp5eR-ID36aPqMvBGnNOcTVPcoFpfmQL5INgoWNJGTUm7pWTpV1wZjZe7PX6dFBhRe8SQQ0yb5SVc29-sX1QK-Cg7gKTe0l7Wrhve2vazHH1uYEqLUoTVnGsAx1nzL66M-M")); + .andExpect(jsonPath("$.keys[0].n").value("4GRvJuFantVV3JdjwQOAkfREnwUFp2znRBTOIJhPamyH4gf4YlI5PQT79415NV4_HrWYzgooH5AK6-7WE-TLLGEAVK5vdk4vv79bG7ukvjvBPxAjEhQn6-Amln88iXtvicEGbh--3CKbQj1jryVU5aWM6jzweaabFSeCILVEd6ZT7ofXaAqan9eLzU5IEtTPy5MfrrOvWw5Q7D2yzMqc5LksmaQSw8XtmhA8gnENnIqjAMmPtRltf93wjtmiamgVENOVPdN-93Nd5w-pnMwEyoO6Q9JqXxV6lD6qBRxI7_5t4_vmVxcbbxcZbSAMoHqA2pbSMJ4Jcw-27Hct9jesLQ")); // @formatter:on } diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/profile/WLCGProfileIntegrationTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/profile/WLCGProfileIntegrationTests.java index 4d8b518d1..3ea0c573f 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/profile/WLCGProfileIntegrationTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/profile/WLCGProfileIntegrationTests.java @@ -54,6 +54,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; +import com.nimbusds.jose.shaded.json.JSONObject; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; @@ -68,9 +69,10 @@ import it.infn.mw.iam.test.util.annotation.IamMockMvcIntegrationTest; import it.infn.mw.iam.test.util.oauth.MockOAuth2Filter; import it.infn.mw.iam.test.util.oauth.MockOAuth2Request; -import net.minidev.json.JSONObject; + +@SuppressWarnings("deprecation") @RunWith(SpringRunner.class) @IamMockMvcIntegrationTest @TestPropertySource(properties = { diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationLifecycleTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationLifecycleTests.java index b57532f7c..20f9a3f0f 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationLifecycleTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationLifecycleTests.java @@ -57,7 +57,8 @@ @RunWith(SpringRunner.class) @IamMockMvcIntegrationTest @SpringBootTest( - classes = {IamLoginService.class, OidcTestConfig.class, CoreControllerTestSupport.class}, + classes = {IamLoginService.class, OidcTestConfig.class, CoreControllerTestSupport.class, + RegistrationLifecycleTests.TestConfig.class}, webEnvironment = WebEnvironment.MOCK) @TestPropertySource(properties = { // @formatter:off diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationPrivilegedTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationPrivilegedTests.java index e4b211a98..83aa6cb8f 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationPrivilegedTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/registration/RegistrationPrivilegedTests.java @@ -21,10 +21,10 @@ import static it.infn.mw.iam.core.IamRegistrationRequestStatus.NEW; import static it.infn.mw.iam.core.IamRegistrationRequestStatus.REJECTED; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -47,6 +47,7 @@ import it.infn.mw.iam.api.scim.exception.IllegalArgumentException; import it.infn.mw.iam.persistence.model.IamAccount; import it.infn.mw.iam.persistence.repository.IamAccountRepository; +import it.infn.mw.iam.persistence.repository.IamRegistrationRequestRepository; import it.infn.mw.iam.registration.PersistentUUIDTokenGenerator; import it.infn.mw.iam.registration.RegistrationRequestDto; import it.infn.mw.iam.registration.RegistrationRequestService; @@ -74,9 +75,24 @@ public class RegistrationPrivilegedTests { @Autowired private RegistrationRequestService registrationService; + @Autowired + private IamRegistrationRequestRepository requestRepo; + @Autowired private IamAccountRepository repo; + @Before + public void setup() { + requestRepo.deleteAll(); + mockOAuth2Filter.cleanupSecurityContext(); + } + + @After + public void teardown() { + requestRepo.deleteAll(); + mockOAuth2Filter.cleanupSecurityContext(); + } + private Supplier assertionError(String message) { return () -> new AssertionError(message); } @@ -125,15 +141,7 @@ protected RegistrationRequestDto approveRequest(String uuid) throws Exception { return objectMapper.readValue(response, RegistrationRequestDto.class); } - @Before - public void setup() { - mockOAuth2Filter.cleanupSecurityContext(); - } - @After - public void teardown() { - mockOAuth2Filter.cleanupSecurityContext(); - } @Test @WithMockOAuthUser(clientId = "registration-client", scopes = {"registration:read"}) diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/RestUtils.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/RestUtils.java index 23d4b00cc..213bb748d 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/RestUtils.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/RestUtils.java @@ -45,6 +45,17 @@ public RestUtils(MockMvc mvc, ObjectMapper mapper) { this.mapper = mapper; } + public ResultActions doPost(String location, B contentObj, + String requestContentType, String expectedContentType, HttpStatus expectedStatus) + throws Exception { + + String contentJson = mapper.writeValueAsString(contentObj); + + return mvc.perform(post(location).contentType(requestContentType).content(contentJson)) + .andExpect(status().is(expectedStatus.value())) + .andExpect(content().contentType(expectedContentType)); + } + public ResultActions doPost(String location, B contentObj, String contentType, HttpStatus expectedStatus) throws Exception { diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/ScimRestUtilsMvc.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/ScimRestUtilsMvc.java index ef2a24dfd..c3df85dbd 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/ScimRestUtilsMvc.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/ScimRestUtilsMvc.java @@ -56,6 +56,8 @@ public ResultActions postUser(ScimUser user, HttpStatus expectedStatus) throws E return doPost(getUsersLocation(), user, SCIM_CONTENT_TYPE, expectedStatus); } + + public ScimUser getUser(String uuid) throws Exception { return mapper.readValue(getUser(uuid, OK).andReturn().getResponse().getContentAsString(), diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimGroupProvisioningTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimGroupProvisioningTests.java index 021ece449..b408a40ac 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimGroupProvisioningTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimGroupProvisioningTests.java @@ -20,6 +20,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; +import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -86,7 +87,7 @@ public void testGetGroupNotFoundResponse() throws Exception { mvc.perform(get(GROUP_URI + "/{uuid}", randomUuid).contentType(SCIM_CONTENT_TYPE)) .andExpect(status().isNotFound()) - .andExpect(content().contentType(SCIM_CONTENT_TYPE)) + .andExpect(content().contentType(APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.status", equalTo("404"))) .andExpect(jsonPath("$.detail", equalTo("No group mapped to id '" + randomUuid + "'"))); } @@ -101,7 +102,7 @@ public void testUpdateGroupNotFoundResponse() throws Exception { .perform(put(GROUP_URI + "/{uuid}", randomUuid).contentType(SCIM_CONTENT_TYPE) .content(objectMapper.writeValueAsString(group))) .andExpect(status().isNotFound()) - .andExpect(content().contentType(SCIM_CONTENT_TYPE)) + .andExpect(content().contentType(APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.status", equalTo("404"))) .andExpect(jsonPath("$.detail", equalTo("No group mapped to id '" + randomUuid + "'"))); } @@ -188,7 +189,7 @@ public void testCreateGroupEmptyDisplayNameValidationError() throws Exception { .perform(post(GROUP_URI).contentType(SCIM_CONTENT_TYPE) .content(objectMapper.writeValueAsString(group))) .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.detail", containsString("scimGroup.displayName : may not be empty"))); + .andExpect(jsonPath("$.detail", containsString("scimGroup.displayName : must not be blank"))); } @Test diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimNestedGroupTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimNestedGroupTests.java index e9ae085e4..cb32e9316 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimNestedGroupTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/group/ScimNestedGroupTests.java @@ -18,12 +18,10 @@ import static it.infn.mw.iam.api.scim.model.ScimConstants.INDIGO_GROUP_SCHEMA; import static it.infn.mw.iam.api.scim.model.ScimConstants.SCIM_CONTENT_TYPE; import static java.lang.String.format; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.NOT_FOUND; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -106,7 +104,7 @@ public void testCreateGroupWithNotExistingParent() throws Exception { .contentType(SCIM_CONTENT_TYPE) .content(objectMapper.writeValueAsString(ScimGroup.builder("mammals").indigoGroup(scimFakeParentGroup).build()))) .andExpect(status().isNotFound()) - .andExpect(jsonPath("$.status", equalTo(NOT_FOUND.toString()))) + .andExpect(jsonPath("$.status", equalTo("404"))) .andExpect(jsonPath("$.detail", equalTo(format("Parent group '%s' not found", uuid)))); // @formatter:on } @@ -120,7 +118,7 @@ public void testDeleteParentGroupWithChildren() throws Exception { // @formatter:off mvc.perform(delete(animals.getMeta().getLocation())) .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.status", equalTo(BAD_REQUEST.toString()))) + .andExpect(jsonPath("$.status", equalTo("400"))) .andExpect(jsonPath("$.detail", equalTo("Group is not empty"))); // @formatter:on } diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/updater/factory/DefaultAccountUpdaterFactoryTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/updater/factory/DefaultAccountUpdaterFactoryTests.java index 44e09cd31..3d93edb82 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/updater/factory/DefaultAccountUpdaterFactoryTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/updater/factory/DefaultAccountUpdaterFactoryTests.java @@ -31,12 +31,13 @@ import static it.infn.mw.iam.api.scim.updater.UpdaterType.ACCOUNT_REPLACE_PICTURE; import static it.infn.mw.iam.api.scim.updater.UpdaterType.ACCOUNT_REPLACE_USERNAME; import static it.infn.mw.iam.authn.saml.util.Saml2Attribute.EPUID; -import static it.infn.mw.iam.test.X509Utils.x509Certs; +import static java.lang.String.format; import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.isIn; +import static org.hamcrest.Matchers.in; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -123,8 +124,7 @@ private IamAccount newAccount(String username) { public void init() { factory = new DefaultAccountUpdaterFactory(encoder, repo, accountService, oidcConverter, - samlConverter, - sshKeyConverter, x509Converter); + samlConverter, sshKeyConverter, x509Converter); } @Test @@ -254,19 +254,18 @@ public void testPatchAddOpMultipleParsing() { when(repo.findBySamlId(any())).thenReturn(Optional.empty()); when(repo.findBySshKeyValue(NEW)).thenReturn(Optional.empty()); - when(repo.findByCertificate(x509Certs.get(0).certificate)).thenReturn(Optional.empty()); - // when(accountService.addSshKey(Mockito.any(), Mockito.any())) - // .thenAnswer(new Answer() { - // @Override - // public IamAccount answer(InvocationOnMock invocation) throws Throwable { - // IamAccount account = invocation.getArgument(0, IamAccount.class); - // IamSshKey key = invocation.getArgument(1, IamSshKey.class); - // account.getSshKeys().add(key); - // key.setAccount(account); - // when(repo.findBySshKeyValue(key.getValue())).thenReturn(Optional.of(account)); - // return account; - // } - // }); + + when(accountService.addSshKey(Mockito.any(), Mockito.any())) + .thenAnswer(new Answer() { + @Override + public IamAccount answer(InvocationOnMock invocation) throws Throwable { + IamAccount account = invocation.getArgument(0, IamAccount.class); + IamSshKey key = invocation.getArgument(1, IamSshKey.class); + account.getSshKeys().add(key); + key.setAccount(account); + return account; + } + }); ScimUser user = ScimUser.builder() .buildName(NEW, NEW) @@ -289,9 +288,11 @@ public void testPatchAddOpMultipleParsing() { assertThat(updaters.size(), equalTo(expectedUpdatersType.size())); - updaters.forEach(u -> assertThat(u.getType(), isIn(expectedUpdatersType))); - updaters.forEach(u -> assertThat(u.update(), equalTo(true))); - updaters.forEach(u -> assertThat(u.update(), equalTo(false))); + updaters.forEach(u -> assertThat(u.getType(), is(in(expectedUpdatersType)))); + updaters.forEach(u -> assertThat(format("%s does not update even if it should", u.getType()), + u.update(), equalTo(true))); + updaters.forEach(u -> assertThat(format("%s updates even if it should not", u.getType()), + u.update(), equalTo(false))); assertThat(account.getUsername(), equalTo(NEW)); assertThat(account.isActive(), equalTo(true)); @@ -344,7 +345,7 @@ public void testPatchReplaceOpMultipleParsing() { assertThat(updaters.size(), equalTo(expectedUpdatersType.size())); - updaters.forEach(u -> assertThat(u.getType(), isIn(expectedUpdatersType))); + updaters.forEach(u -> assertThat(u.getType(), is(in(expectedUpdatersType)))); updaters.forEach(u -> assertThat(u.update(), equalTo(true))); updaters.forEach(u -> assertThat(u.update(), equalTo(false))); @@ -365,16 +366,10 @@ public void testPatchRemoveOpMultipleParsing() { IamAccount account = newAccount(OLD); account.setOidcIds(newHashSet(new IamOidcId(OLD, OLD))); - account.setSamlIds( - newHashSet(new IamSamlId(OLD, Saml2Attribute.EPUID.getAttributeName(), OLD))); - - account.setSshKeys(Sets.newHashSet(new IamSshKey(OLD))); + account + .setSamlIds(newHashSet(new IamSamlId(OLD, Saml2Attribute.EPUID.getAttributeName(), OLD))); - IamSamlId oldId = new IamSamlId(OLD, Saml2Attribute.EPUID.getAttributeName(), OLD); - - - - when(repo.findBySshKeyValue(OLD)).thenReturn(Optional.of(account)); + account.setSshKeys(Sets.newHashSet(new IamSshKey(OLD))); when(accountService.removeSshKey(Mockito.any(), Mockito.any())) .thenAnswer(new Answer() { @@ -403,7 +398,7 @@ public IamAccount answer(InvocationOnMock invocation) throws Throwable { assertThat(updaters.size(), equalTo(expectedUpdatersType.size())); - updaters.forEach(u -> assertThat(u.getType(), isIn(expectedUpdatersType))); + updaters.forEach(u -> assertThat(u.getType(), is(in(expectedUpdatersType)))); updaters.forEach(u -> assertThat(u.update(), equalTo(true))); updaters.forEach(u -> assertThat(u.update(), equalTo(false))); diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserCreationTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserCreationTests.java index 147612c8a..e70cd2095 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserCreationTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserCreationTests.java @@ -16,18 +16,21 @@ package it.infn.mw.iam.test.scim.user; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_CLIENT_ID; +import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_CONTENT_TYPE; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_READ_SCOPE; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_WRITE_SCOPE; import static it.infn.mw.iam.test.scim.ScimUtils.buildUser; import static it.infn.mw.iam.test.scim.ScimUtils.buildUserWithPassword; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; import java.util.Optional; @@ -40,9 +43,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.HttpStatus; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.fasterxml.jackson.databind.ObjectMapper; import it.infn.mw.iam.IamLoginService; import it.infn.mw.iam.api.scim.model.ScimIndigoUser; @@ -55,6 +60,7 @@ import it.infn.mw.iam.test.X509Utils; import it.infn.mw.iam.test.core.CoreControllerTestSupport; import it.infn.mw.iam.test.scim.ScimRestUtilsMvc; +import it.infn.mw.iam.test.scim.ScimUtils; import it.infn.mw.iam.test.util.WithMockOAuthUser; import it.infn.mw.iam.test.util.annotation.IamMockMvcIntegrationTest; import it.infn.mw.iam.test.util.oauth.MockOAuth2Filter; @@ -75,6 +81,12 @@ public class ScimUserCreationTests extends ScimUserTestSupport { @Autowired private ScimRestUtilsMvc scimUtils; + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + @Autowired private MockOAuth2Filter mockOAuth2Filter; @@ -172,8 +184,13 @@ public void testUserCreationWithStolenOidcAccountFailure() throws Exception { .active(true) .build(); - scimUtils.postUser(anotherUser, HttpStatus.CONFLICT) + + mvc + .perform(post(ScimUtils.getUsersLocation()).content(mapper.writeValueAsBytes(anotherUser)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isConflict()) .andExpect(jsonPath("$.detail", containsString("already bound to a user"))); + } @Test @@ -267,8 +284,12 @@ public void testUserCreationWithStolenSshKeyFailure() throws Exception { .active(true) .build(); - scimUtils.postUser(anotherUser, HttpStatus.CONFLICT) + mvc + .perform(post(ScimUtils.getUsersLocation()).content(mapper.writeValueAsBytes(anotherUser)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isConflict()) .andExpect(jsonPath("$.detail", containsString("already bound to a user"))); + } @Test diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningPatchReplaceTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningPatchReplaceTests.java index 18de26c2b..293df74bb 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningPatchReplaceTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningPatchReplaceTests.java @@ -19,10 +19,10 @@ import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_CLIENT_ID; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_READ_SCOPE; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_WRITE_SCOPE; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.CONFLICT; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -78,7 +78,7 @@ public void testReplaceEmailWithEmptyValue() throws Exception { ScimUser updates = ScimUser.builder().buildEmail("").build(); scimUtils.patchUser(testUser.getId(), replace, updates, BAD_REQUEST) - .andExpect(jsonPath("$.detail", containsString(": may not be empty"))); + .andExpect(jsonPath("$.detail", containsString(": must not be empty"))); } @Test @@ -88,7 +88,7 @@ public void testReplaceEmailWithNullValue() throws Exception { ScimUser updates = ScimUser.builder().buildEmail(null).build(); scimUtils.patchUser(testUser.getId(), replace, updates, BAD_REQUEST) - .andExpect(jsonPath("$.detail", containsString(": may not be empty"))); + .andExpect(jsonPath("$.detail", containsString(": must not be empty"))); } @Test diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningTests.java index 983c9af0e..d54c42b24 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/scim/user/ScimUserProvisioningTests.java @@ -16,21 +16,23 @@ package it.infn.mw.iam.test.scim.user; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_CLIENT_ID; +import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_CONTENT_TYPE; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_READ_SCOPE; import static it.infn.mw.iam.test.scim.ScimUtils.SCIM_WRITE_SCOPE; import static it.infn.mw.iam.test.scim.ScimUtils.buildUser; import static it.infn.mw.iam.test.scim.ScimUtils.buildUserWithUUID; import static it.infn.mw.iam.test.scim.ScimUtils.getUserLocation; import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.CONFLICT; import static org.springframework.http.HttpStatus.NOT_FOUND; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.hamcrest.Matchers; import org.junit.After; @@ -42,6 +44,9 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.fasterxml.jackson.databind.ObjectMapper; import it.infn.mw.iam.IamLoginService; import it.infn.mw.iam.api.scim.model.ScimEmail.ScimEmailType; @@ -63,10 +68,16 @@ public class ScimUserProvisioningTests extends ScimUserTestSupport { @Autowired private ScimRestUtilsMvc scimUtils; - + @Autowired private MockOAuth2Filter mockOAuth2Filter; - + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + @Before public void setup() throws Exception { mockOAuth2Filter.cleanupSecurityContext(); @@ -95,7 +106,11 @@ public void testUpdateUserNotFoundResponse() throws Exception { String randomUuid = getRandomUUid(); ScimUser user = ScimUtils.buildUser("john_lennon", "lennon@email.test", "John", "Lennon"); - scimUtils.putUser(randomUuid, user, HttpStatus.NOT_FOUND) + mvc + .perform(put(ScimUtils.getUsersLocation() + "/" + randomUuid) + .content(mapper.writeValueAsBytes(user)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isNotFound()) .andExpect(jsonPath("$.status", equalTo("404"))) .andExpect(jsonPath("$.detail", equalTo("No user mapped to id '" + randomUuid + "'"))); } @@ -150,9 +165,12 @@ public void testEmptyUsernameValidationError() throws Exception { ScimUser user = buildUser("", "test@email.test", "Paul", "McCartney"); - scimUtils.postUser(user, HttpStatus.BAD_REQUEST) + mvc + .perform(post(ScimUtils.getUsersLocation()).content(mapper.writeValueAsBytes(user)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status", equalTo("400"))) - .andExpect(jsonPath("$.detail", containsString("scimUser.userName : may not be empty"))); + .andExpect(jsonPath("$.detail", containsString("scimUser.userName : must not be blank"))); } @Test @@ -161,9 +179,12 @@ public void testEmptyEmailValidationError() throws Exception { ScimUser user = ScimUser.builder("paul").buildName("Paul", "McCartney").build(); - scimUtils.postUser(user, HttpStatus.BAD_REQUEST) + mvc + .perform(post(ScimUtils.getUsersLocation()).content(mapper.writeValueAsBytes(user)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status", equalTo("400"))) - .andExpect(jsonPath("$.detail", containsString("scimUser.emails : may not be empty"))); + .andExpect(jsonPath("$.detail", containsString("scimUser.emails : must not be empty"))); } @Test @@ -172,10 +193,13 @@ public void testInvalidEmailValidationError() throws Exception { ScimUser user = buildUser("paul", "this_is_not_an_email", "Paul", "McCartney"); - scimUtils.postUser(user, HttpStatus.BAD_REQUEST) + + mvc + .perform(post(ScimUtils.getUsersLocation()).content(mapper.writeValueAsBytes(user)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status", equalTo("400"))) - .andExpect(jsonPath("$.detail", - containsString("Please provide a valid email address"))); + .andExpect(jsonPath("$.detail", containsString("Please provide a valid email address"))); } @Test @@ -210,8 +234,12 @@ public void testUpdateUserValidation() throws Exception { ScimUser userWithUpdates = ScimUser.builder("j.lennon").id(user.getId()).active(true).build(); - scimUtils.putUser(user.getId(), userWithUpdates, BAD_REQUEST) - .andExpect(jsonPath("$.detail", containsString("scimUser.emails : may not be empty"))); + mvc + .perform(put(ScimUtils.getUsersLocation() + "/" + user.getId()) + .content(mapper.writeValueAsBytes(userWithUpdates)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail", containsString("scimUser.emails : must not be empty"))); } @Test @@ -237,19 +265,34 @@ public void testReplaceUserWithAlreadyUsedUsername() throws Exception { mccartney.getUserName(), mccartney.getEmails().get(0).getValue(), mccartney.getName().getGivenName(), mccartney.getName().getFamilyName()); - scimUtils.putUser(lennonCreationResult.getId(), lennonWantsToBeMcCartney, CONFLICT) + + mvc + .perform(put(ScimUtils.getUsersLocation() + "/" + lennonCreationResult.getId()) + .content(mapper.writeValueAsBytes(lennonWantsToBeMcCartney)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isConflict()) .andExpect(jsonPath("$.detail", containsString("username paul_mccartney already assigned to another user"))); + } @Test @WithMockOAuthUser(clientId = SCIM_CLIENT_ID, scopes = {SCIM_READ_SCOPE, SCIM_WRITE_SCOPE}) public void testUniqueUsernameCreationCheck() throws Exception { - ScimUser user = buildUser("john_lennon", "lennon@email.test", "John", "Lennon"); + ScimUser user1 = buildUser("john_lennon", "lennon@email.test", "John", "Lennon"); + ScimUser user2 = buildUser("john_lennon", "another_lennon@email.test", "John", "Lennon"); + + scimUtils.postUser(user1); + + mvc + .perform(post(ScimUtils.getUsersLocation()).content(mapper.writeValueAsBytes(user2)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.detail", + containsString("A user with username 'john_lennon' already exists"))); + - scimUtils.postUser(user); - scimUtils.postUser(user, HttpStatus.CONFLICT); } @Test @@ -261,10 +304,13 @@ public void testEmailIsNotAlreadyLinkedOnCreate() throws Exception { user0 = scimUtils.postUser(user0); - //@formatter:off - scimUtils.postUser(user1, HttpStatus.CONFLICT) - .andExpect(jsonPath("$.detail", containsString("A user linked with email 'same_email@test.org' already exists"))); - //@formatter:on + mvc + .perform(post(ScimUtils.getUsersLocation()).content(mapper.writeValueAsBytes(user1)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.detail", + containsString("A user linked with email 'same_email@test.org' already exists"))); + } @Test @@ -280,7 +326,14 @@ public void testEmailIsNotAlreadyLinkedOnUpdate() throws Exception { ScimUser updatedUser0 = buildUserWithUUID(user0.getId(), "user0", "user1@test.org", "Test", "User 0"); - scimUtils.putUser(user0.getId(), updatedUser0, CONFLICT).andExpect(jsonPath("$.detail", - containsString("email user1@test.org already assigned to another user"))); + mvc + .perform(put(ScimUtils.getUsersLocation() + "/" + user0.getId()) + .content(mapper.writeValueAsBytes(updatedUser0)) + .contentType(SCIM_CONTENT_TYPE)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.detail", + containsString("email user1@test.org already assigned to another user"))); + + } } diff --git a/iam-login-service/src/test/java/it/infn/mw/iam/test/service/JavamailNotificationDeliveryTests.java b/iam-login-service/src/test/java/it/infn/mw/iam/test/service/JavamailNotificationDeliveryTests.java index b728567f0..dafa61468 100644 --- a/iam-login-service/src/test/java/it/infn/mw/iam/test/service/JavamailNotificationDeliveryTests.java +++ b/iam-login-service/src/test/java/it/infn/mw/iam/test/service/JavamailNotificationDeliveryTests.java @@ -28,9 +28,6 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import java.util.Date; -import java.util.UUID; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -103,19 +100,16 @@ public void testNoMessageDelivery() { @Test public void testMessageIsDelivered() { - // String randomUuid = UUID.randomUUID().toString(); - // Date currentTime = new Date(); + IamEmailNotification notification = mock(IamEmailNotification.class); IamNotificationReceiver receiver = mock(IamNotificationReceiver.class); - when(receiver.getIamEmailNotification()).thenReturn(notification); - // when(receiver.getEmailAddress()).thenReturn(TEST_0_EMAIL); + // when(receiver.getIamEmailNotification()).thenReturn(notification); + when(receiver.getEmailAddress()).thenReturn(TEST_0_EMAIL); when(notification.getBody()).thenReturn("Body"); when(notification.getSubject()).thenReturn("Subject"); - when(notification.getDeliveryStatus()).thenReturn(IamDeliveryStatus.PENDING); - // when(notification.getCreationTime()).thenReturn(currentTime); - // when(notification.getUuid()).thenReturn(randomUuid); + // when(notification.getDeliveryStatus()).thenReturn(IamDeliveryStatus.PENDING); when(notification.getReceivers()).thenReturn(asList(receiver)); @@ -139,17 +133,15 @@ public void testMessageIsDelivered() { @Test public void testDeliveryErrorIsPropagated() { - String randomUuid = UUID.randomUUID().toString(); - Date currentTime = new Date(); IamEmailNotification notification = Mockito.mock(IamEmailNotification.class); IamNotificationReceiver receiver = Mockito.mock(IamNotificationReceiver.class); - when(receiver.getIamEmailNotification()).thenReturn(notification); + // when(receiver.getIamEmailNotification()).thenReturn(notification); // when(receiver.getEmailAddress()).thenReturn(TEST_0_EMAIL); when(notification.getBody()).thenReturn("Body"); when(notification.getSubject()).thenReturn("Subject"); - when(notification.getDeliveryStatus()).thenReturn(IamDeliveryStatus.PENDING); + // when(notification.getDeliveryStatus()).thenReturn(IamDeliveryStatus.PENDING); // when(notification.getCreationTime()).thenReturn(currentTime); // when(notification.getUuid()).thenReturn(randomUuid);