diff --git a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIServiceGroupServiceIntegrationTest.java b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIServiceGroupServiceIntegrationTest.java index 4711274f4fe3a4feb37367f33fbb73597b5fddec..8cd0be9dd3cc91c303d077dbe171f4bd6133acd6 100644 --- a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIServiceGroupServiceIntegrationTest.java +++ b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIServiceGroupServiceIntegrationTest.java @@ -283,7 +283,7 @@ public class UIServiceGroupServiceIntegrationTest extends AbstractServiceIntegra @Test - public void validateExtensionVaild() throws IOException { + public void validateExtensionValid() throws IOException { // given ServiceGroupValidationRO sg = TestROUtils.getValidExtension(); @@ -296,7 +296,7 @@ public class UIServiceGroupServiceIntegrationTest extends AbstractServiceIntegra } @Test - public void validateExtensionMultipleVaild() throws IOException { + public void validateExtensionMultipleValid() throws IOException { // given ServiceGroupValidationRO sg = TestROUtils.getValidMultipleExtension(); @@ -309,7 +309,7 @@ public class UIServiceGroupServiceIntegrationTest extends AbstractServiceIntegra } @Test - public void validateExtensionCustomTextInvaldValid() throws IOException { + public void validateExtensionCustomTextInvalid() throws IOException { // given ServiceGroupValidationRO sg = TestROUtils.getValidCustomText(); @@ -331,7 +331,7 @@ public class UIServiceGroupServiceIntegrationTest extends AbstractServiceIntegra // then assertNotNull(sg.getErrorMessage()); - assertThat(sg.getErrorMessage(), containsString(" Invalid content was found starting with element 'ExtensionID'.")); + assertThat(sg.getErrorMessage(), containsString("cvc-complex-type.2.4.a: Invalid content was found starting with element '{\"http://docs.oasis-open.org/bdxr/ns/SMP/2016/05\":ExtensionID}'.")); assertNotNull(sg.getExtension()); } diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/URLCsrfMatcher.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/URLCsrfMatcher.java index 260294500cebd3ff69c97ee9889bb95a8ed5bbf5..3b68855f96780bd7e4be09d88c441ffc11570178 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/URLCsrfMatcher.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/URLCsrfMatcher.java @@ -2,44 +2,49 @@ package eu.europa.ec.edelivery.smp.auth; import eu.europa.ec.edelivery.smp.logging.SMPLoggerFactory; import org.slf4j.Logger; +import org.springframework.http.HttpMethod; import org.springframework.security.web.util.matcher.RegexRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; -import java.util.HashSet; - +import java.util.*; +import java.util.regex.Matcher; + +/** + * URLCsrfMatcher matches the request and validates if request can be ignored for CSRF. + * As example the non session requests (as SMP REST API) should now have the CSRF tokens. + * + * @author Joze Rihtarsic + * @since 4.2 + */ public class URLCsrfMatcher implements RequestMatcher { - private static final Logger LOGGER = SMPLoggerFactory.getLogger(URLCsrfMatcher.class); - - protected String ignoreUrl; + private static final Logger LOG = SMPLoggerFactory.getLogger(URLCsrfMatcher.class); + private List<RequestMatcher> unprotectedMatcherList = new ArrayList<>(); - private RegexRequestMatcher unprotectedMatcher = null; - private final HashSet<String> allowedMethods = new HashSet<String>( Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS")); - - @PostConstruct - public void init() { - LOGGER.debug("Initializing the matcher with [{}]", ignoreUrl); - unprotectedMatcher = new RegexRequestMatcher(ignoreUrl, null); - } @Override public boolean matches(HttpServletRequest request) { - if(this.allowedMethods.contains(request.getMethod())) { - LOGGER.trace("Matched method [{}]", request.getMethod()); - return false; - } - return !unprotectedMatcher.matches(request); + Optional<RequestMatcher> unprotectedMatcher = unprotectedMatcherList.stream().filter(requestMatcher -> requestMatcher.matches(request)).findFirst(); + return !unprotectedMatcher.isPresent(); } - public String getIgnoreUrl() { - return ignoreUrl; - } - public void setIgnoreUrl(String ignoreUrl) { - this.ignoreUrl = ignoreUrl; + /** + * Creates a case-sensitive {@code Pattern} instance to match against the request for http method(s). + * @param ignoreUrlPattern the regular expression to match ignore URLs. + * @param httpMethods the HTTP method(s) to match. May be null to match all methods. + */ + public void addIgnoreUrl(String ignoreUrlPattern, HttpMethod ... httpMethods) { + if (httpMethods==null || httpMethods.length ==0) { + unprotectedMatcherList.add(new RegexRequestMatcher(ignoreUrlPattern, null)); + } else { + Arrays.stream(httpMethods).forEach(httpMethod -> { + unprotectedMatcherList.add(new RegexRequestMatcher(ignoreUrlPattern, httpMethod.name())); + }); + } + } } \ No newline at end of file diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/config/SpringSecurityConfig.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/config/SpringSecurityConfig.java index 569bf7e2a1bd27a1372ebe93233cd441e0c89ddb..f8631e43badeb355b96be4b09888f7bd7c5a4a09 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/config/SpringSecurityConfig.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/config/SpringSecurityConfig.java @@ -17,6 +17,7 @@ import eu.europa.ec.edelivery.security.BlueCoatAuthenticationFilter; import eu.europa.ec.edelivery.security.EDeliveryX509AuthenticationFilter; import eu.europa.ec.edelivery.smp.auth.SMPAuthenticationProvider; import eu.europa.ec.edelivery.smp.auth.SMPAuthority; +import eu.europa.ec.edelivery.smp.auth.URLCsrfMatcher; import eu.europa.ec.edelivery.smp.error.SpringSecurityExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,8 +37,11 @@ import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; +import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.firewall.DefaultHttpFirewall; import org.springframework.security.web.firewall.HttpFirewall; +import org.springframework.security.web.util.matcher.RequestMatcher; /** * Created by gutowpa on 12/07/2017. @@ -82,7 +86,9 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { // prepare filters blueCoatAuthenticationFilter.setBlueCoatEnabled(clientCertEnabled); - httpSecurity.csrf().disable() + httpSecurity +// .csrf().disable() + .csrf().csrfTokenRepository(tokenRepository()).requireCsrfProtectionMatcher(csrfURLMatcher()).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and() .exceptionHandling().authenticationEntryPoint(new SpringSecurityExceptionHandler()).and() .headers().frameOptions().deny().contentTypeOptions().and().xssProtection().xssProtectionEnabled(true).and().and() @@ -153,4 +159,28 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { x509AuthenticationFilter.setAuthenticationManager(authenticationManager); return x509AuthenticationFilter; } + + @Bean + public CsrfTokenRepository tokenRepository(){ + CookieCsrfTokenRepository csrfTokenRepository = new CookieCsrfTokenRepository(); + csrfTokenRepository.setCookieHttpOnly(false); + return csrfTokenRepository; + } + + @Bean + public RequestMatcher csrfURLMatcher() { + URLCsrfMatcher requestMatcher = new URLCsrfMatcher(); + // Csrf ignore "SMP API 'stateless' calls! (each call is authenticated and session is not used!)" + requestMatcher.addIgnoreUrl("/.*::.*(/services/?.*)?", HttpMethod.GET, HttpMethod.DELETE, HttpMethod.POST, HttpMethod.PUT); + // ignore for login and logout + requestMatcher.addIgnoreUrl("/ui/rest/security/authentication", HttpMethod.DELETE, HttpMethod.POST); + // info + requestMatcher.addIgnoreUrl("/ui/rest/application/(info|rootContext|name)", HttpMethod.GET); + // monitor + requestMatcher.addIgnoreUrl("/monitor/is-alive", HttpMethod.GET); + // public search + + requestMatcher.addIgnoreUrl("/ui/rest/search", HttpMethod.GET); + return requestMatcher; + } } diff --git a/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationClientCertTest.java b/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationClientCertTest.java index ce84508031a572bdf6f46ff2542f3360ba1bf462..974548b0934baa5a5f59f0e845c772b5579bbcff 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationClientCertTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationClientCertTest.java @@ -38,6 +38,7 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -183,7 +184,7 @@ public class SecurityConfigurationClientCertTest { HttpHeaders headers = new HttpHeaders(); headers.add("Client-Cert", clientCert); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) - .headers(headers)) + .headers(headers).with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(expectedCertificateId)) .andReturn().getResponse().getContentAsString(); diff --git a/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationTest.java b/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationTest.java index 27877ddfde1c070f53e9249a78aabd1016c1a8d6..c334114c27fd5c2e52bc86aa2acbb696f6966533 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/cipa/smp/server/security/SecurityConfigurationTest.java @@ -31,6 +31,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -81,27 +82,31 @@ public class SecurityConfigurationTest { @Test public void getMethodAccessiblePubliclyTest() throws Exception { - mvc.perform(MockMvcRequestBuilders.get(RETURN_LOGGED_USER_PATH)) + mvc.perform(MockMvcRequestBuilders.get(RETURN_LOGGED_USER_PATH) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string("anonymousUser")); } @Test public void notAuthenticatedUserCannotCallPutTest() throws Exception { - mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH)) + mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) + .with(csrf())) .andExpect(status().isUnauthorized()); } @Test public void notAuthenticatedUserCannotCallDeleteTest() throws Exception { - mvc.perform(MockMvcRequestBuilders.delete(RETURN_LOGGED_USER_PATH)) + mvc.perform(MockMvcRequestBuilders.delete(RETURN_LOGGED_USER_PATH) + .with(csrf())) .andExpect(status().isUnauthorized()); } @Test public void userStoredWithHashedPassIsAuthorizedForPutTest() throws Exception { mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) - .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD))) + .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD)) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(TEST_USERNAME_DB_HASHED_PASS)); } @@ -113,7 +118,8 @@ public class SecurityConfigurationTest { Assert.assertNotEquals(upperCaseUsername, TEST_USERNAME_DB_HASHED_PASS); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) - .with(httpBasic(upperCaseUsername, PASSWORD))) + .with(httpBasic(upperCaseUsername, PASSWORD)) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(upperCaseUsername)); } @@ -124,7 +130,7 @@ public class SecurityConfigurationTest { @Test public void userStoredWithClearPassIsNotAuthorizedForPutTest() throws Exception { mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) - .with(httpBasic(TEST_USERNAME_DB_CLEAR_PASS, PASSWORD))) + .with(httpBasic(TEST_USERNAME_DB_CLEAR_PASS, PASSWORD)).with(csrf())) .andExpect(status().isUnauthorized()); } @@ -134,7 +140,7 @@ public class SecurityConfigurationTest { HttpHeaders headers = new HttpHeaders(); headers.add("Client-Cert", "malformed header value"); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) - .headers(headers)) + .headers(headers).with(csrf())) .andExpect(status().isUnauthorized()); } @@ -143,7 +149,8 @@ public class SecurityConfigurationTest { HttpHeaders headers = new HttpHeaders(); headers.add("Client-Cert", BLUE_COAT_VALID_HEADER); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) - .headers(headers)) + .headers(headers) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(TEST_USERNAME_BLUE_COAT)) .andReturn().getResponse().getContentAsString(); @@ -154,7 +161,7 @@ public class SecurityConfigurationTest { headers.add("Client-Cert", BLUE_COAT_NOT_AUTHORIZED_HEADER); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) - .headers(headers)) + .headers(headers).with(csrf())) .andExpect(status().isUnauthorized()); } @@ -164,7 +171,8 @@ public class SecurityConfigurationTest { headers.add("Client-Cert", BLUE_COAT_VALID_HEADER); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) .headers(headers) - .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD))) + .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD)) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(TEST_USERNAME_BLUE_COAT)); } @@ -175,7 +183,8 @@ public class SecurityConfigurationTest { headers.add("Client-Cert", BLUE_COAT_VALID_HEADER_UPPER_SN); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) .headers(headers) - .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD))) + .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD)) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(TEST_USERNAME_BLUE_COAT)); } @@ -187,7 +196,8 @@ public class SecurityConfigurationTest { headers.add("Client-Cert", BLUE_COAT_VALID_HEADER_DB_UPPER_SN); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) .headers(headers) - .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD))) + .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD)) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(TEST_USERNAME_BLUE_COAT__DB_UPPER_SN)); } @@ -198,7 +208,8 @@ public class SecurityConfigurationTest { headers.add("Client-Cert", BLUE_COAT_VALID_HEADER_DB_UPPER_SN); mvc.perform(MockMvcRequestBuilders.put(RETURN_LOGGED_USER_PATH) .headers(headers) - .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD))) + .with(httpBasic(TEST_USERNAME_DB_HASHED_PASS, PASSWORD)) + .with(csrf())) .andExpect(status().isOk()) .andExpect(content().string(TEST_USERNAME_BLUE_COAT__DB_UPPER_SN)); } diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ApplicationResourceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ApplicationResourceTest.java index 029b738fadfec67c747c6918baa00ac25695048c..3d4f71d27c6db37b01ba7facfb0e36a7d5df0a6a 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ApplicationResourceTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ApplicationResourceTest.java @@ -29,6 +29,7 @@ import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import static org.junit.Assert.*; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -110,7 +111,8 @@ public class ApplicationResourceTest { @Test public void testGetApplicationConfigNotAuthorized() throws Exception { // when - mvc.perform(get(PATH + "/config")) + mvc.perform(get(PATH + "/config") + .with(csrf())) .andExpect(status().isUnauthorized()) .andReturn() .getResponse(); @@ -118,21 +120,26 @@ public class ApplicationResourceTest { @Test public void testGetApplicationConfigAuthorized() throws Exception { // SMP admin - String val = mvc.perform(get(PATH + "/config").with(SMP_ADMIN_CREDENTIALS)) + String val = mvc.perform(get(PATH + "/config") + .with(SMP_ADMIN_CREDENTIALS) + .with(csrf())) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); assertNotNull(val); // service group - val = mvc.perform(get(PATH + "/config").with(SG_ADMIN_CREDENTIALS)) + val = mvc.perform(get(PATH + "/config").with(SG_ADMIN_CREDENTIALS) + .with(csrf())) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); assertNotNull(val); // system admin - val = mvc.perform(get(PATH + "/config").with(SYSTEM_CREDENTIALS)) + val = mvc.perform(get(PATH + "/config") + .with(SYSTEM_CREDENTIALS) + .with(csrf())) .andExpect(status().isOk()) .andReturn() .getResponse() @@ -143,8 +150,9 @@ public class ApplicationResourceTest { @Test public void testGetApplicationConfigSMPAdmin() throws Exception { // when - String value = mvc.perform(get(PATH + "/config").with(SMP_ADMIN_CREDENTIALS)) - + String value = mvc.perform(get(PATH + "/config") + .with(SMP_ADMIN_CREDENTIALS) + .with(csrf())) .andExpect(status().isOk()) .andReturn() .getResponse() diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/DomainResourceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/DomainResourceTest.java index 6011dc3778fc355454ee9496455ceb12671e771d..12b12d7c60f7bd6a9c95ec0a96b6e6493118e37e 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/DomainResourceTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/DomainResourceTest.java @@ -30,6 +30,7 @@ import javax.servlet.ServletContextListener; import static org.hamcrest.Matchers.stringContainsInOrder; import static org.junit.Assert.*; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -86,8 +87,10 @@ public class DomainResourceTest { public void geDomainList() throws Exception { // given when - MvcResult result = mvc.perform(get(PATH).with(SYSTEM_CREDENTIALS)). - andExpect(status().isOk()).andReturn(); + MvcResult result = mvc.perform(get(PATH) + .with(SYSTEM_CREDENTIALS) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); //them ObjectMapper mapper = new ObjectMapper(); @@ -111,6 +114,7 @@ public class DomainResourceTest { MvcResult result = mvc.perform(put(PATH ) .with(SYSTEM_CREDENTIALS) + .with(csrf()) .header("Content-Type", " application/json") .content("[{\"status\":3,\"index\":9,\"id\":2,\"domainCode\":\"domainTwo\",\"smlSubdomain\":\"newdomain\",\"smlSmpId\":\"CEF-SMP-010\",\"smlParticipantIdentifierRegExp\":null,\"smlClientCertHeader\":null,\"smlClientKeyAlias\":null,\"signatureKeyAlias\":\"sig-key\",\"smlBlueCoatAuth\":true,\"smlRegistered\":false,\"deleted\":true}]")) // delete domain with id 2 .andExpect(status().isOk()).andReturn(); @@ -125,6 +129,7 @@ public class DomainResourceTest { // given when MvcResult result = mvc.perform(put(PATH ) .with(SYSTEM_CREDENTIALS) + .with(csrf()) .header("Content-Type", " application/json") .content("[{\"status\":3,\"index\":9,\"id\":10,\"domainCode\":\"domainTwoNotExist\",\"smlSubdomain\":\"newdomain\",\"smlSmpId\":\"CEF-SMP-010\",\"smlParticipantIdentifierRegExp\":null,\"smlClientCertHeader\":null,\"smlClientKeyAlias\":null,\"signatureKeyAlias\":\"sig-key\",\"smlBlueCoatAuth\":true,\"smlRegistered\":false,\"deleted\":true}]")) // delete domain with id 2 .andExpect(status().isOk()).andReturn(); @@ -135,6 +140,7 @@ public class DomainResourceTest { // given when MvcResult result = mvc.perform(post(PATH + "/validateDelete") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .header("Content-Type", " application/json") .content("[2]")) // delete domain with id 2 .andExpect(status().isOk()).andReturn(); @@ -157,6 +163,7 @@ public class DomainResourceTest { MvcResult result = mvc.perform(put(PATH ) .with(SYSTEM_CREDENTIALS) + .with(csrf()) .header("Content-Type", " application/json") .content("[{\"status\":1,\"index\":9,\"id\":2,\"domainCode\":\"domainTwo\",\"smlSubdomain\":\"newdomain\",\"smlSmpId\":\"CEF-SMP-010\",\"smlParticipantIdentifierRegExp\":null,\"smlClientCertHeader\":null,\"smlClientKeyAlias\":null,\"signatureKeyAlias\":\"sig-key\",\"smlBlueCoatAuth\":true,\"smlRegistered\":false,\"deleted\":true}]")) // delete domain with id 2 .andExpect(status().isOk()).andReturn(); @@ -170,6 +177,7 @@ public class DomainResourceTest { // given when MvcResult result = mvc.perform(post(PATH + "/validateDelete") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .header("Content-Type", " application/json") .content("[1]")) // delete domain with id 2 .andExpect(status().isOk()).andReturn(); @@ -192,6 +200,7 @@ public class DomainResourceTest { // domainTwo - domain code mvc.perform(post(PATH + "/3/smlregister/domainTwo") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .header("Content-Type", " application/json")) .andExpect(status().isOk()) .andExpect(content().string(stringContainsInOrder("Configuration error: SML integration is not enabled!!"))); @@ -204,6 +213,7 @@ public class DomainResourceTest { // domainTwo - domain code mvc.perform(post(PATH + "/3/smlunregister/domainTwo") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .header("Content-Type", " application/json")) .andExpect(status().isOk()) .andExpect(content().string(stringContainsInOrder("Configuration error: SML integration is not enabled!!"))); diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/KeystoreResourceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/KeystoreResourceTest.java index 2aaa79520d54b61218106017eb076a683dcb2ec2..e157dd6bbdb5aeeab4b1f3e49676804157dd9654 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/KeystoreResourceTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/KeystoreResourceTest.java @@ -42,6 +42,7 @@ import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -98,8 +99,10 @@ public class KeystoreResourceTest { public void getKeyCertificateList() throws Exception { // given when int countStart = uiKeystoreService.getKeystoreEntriesList().size(); - MvcResult result = mvc.perform(get(PATH).with(SYSTEM_CREDENTIALS)). - andExpect(status().isOk()).andReturn(); + MvcResult result = mvc.perform(get(PATH) + .with(SYSTEM_CREDENTIALS) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); //them ObjectMapper mapper = new ObjectMapper(); @@ -122,6 +125,7 @@ public class KeystoreResourceTest { // given when MvcResult result = mvc.perform(post(PATH+"/3/upload/JKS/test123") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content("invalid keystore")). andExpect(status().isOk()).andReturn(); @@ -139,6 +143,7 @@ public class KeystoreResourceTest { // given when MvcResult result = mvc.perform(post(PATH+"/3/upload/JKS/NewPassword1234") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(Files.readAllBytes(keystore)) ) .andExpect(status().isOk()).andReturn(); @@ -157,6 +162,7 @@ public class KeystoreResourceTest { // given when MvcResult result = mvc.perform(post(PATH+"/3/upload/JKS/test123") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(Files.readAllBytes(keystore)) ) .andExpect(status().isOk()).andReturn(); @@ -176,6 +182,7 @@ public class KeystoreResourceTest { // given when MvcResult result = mvc.perform(delete(PATH+"/3/delete/second_domain_alias") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(Files.readAllBytes(keystore)) ) .andExpect(status().isOk()).andReturn(); diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ServiceGroupResourceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ServiceGroupResourceTest.java index 954657a403fb483eb6280fba55b72f6dda40d8fa..eb764c375a184f775831c25a915b78fb80954a1c 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ServiceGroupResourceTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/ServiceGroupResourceTest.java @@ -37,6 +37,7 @@ import javax.xml.ws.spi.WebServiceFeatureAnnotation; import java.io.IOException; import static org.junit.Assert.*; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -95,7 +96,7 @@ public class ServiceGroupResourceTest { public void getServiceGroupListForSMPAdmin() throws Exception { // given when MvcResult result = mvc.perform(get(PATH) - .with(SMP_ADMIN_CREDENTIALS) + .with(SMP_ADMIN_CREDENTIALS).with(csrf()) ).andExpect(status().isOk()).andReturn(); //them @@ -119,7 +120,7 @@ public class ServiceGroupResourceTest { public void getServiceGroupListForServiceGroupAdmin() throws Exception { // given when MvcResult result = mvc.perform(get(PATH) - .with(SG_ADMIN_CREDENTIALS) + .with(SG_ADMIN_CREDENTIALS).with(csrf()) ).andExpect(status().isOk()).andReturn(); //them @@ -143,7 +144,7 @@ public class ServiceGroupResourceTest { // given when MvcResult result = mvc.perform(get(PATH + "/100000") - .with(SMP_ADMIN_CREDENTIALS)). + .with(SMP_ADMIN_CREDENTIALS).with(csrf())). andExpect(status().isOk()).andReturn(); //them @@ -172,8 +173,8 @@ public class ServiceGroupResourceTest { // given when MvcResult result = mvc.perform(get(PATH + "/extension/100000") - .with(SMP_ADMIN_CREDENTIALS)). - andExpect(status().isOk()).andReturn(); + .with(SMP_ADMIN_CREDENTIALS).with(csrf())) + .andExpect(status().isOk()).andReturn(); //them ObjectMapper mapper = new ObjectMapper(); @@ -187,7 +188,7 @@ public class ServiceGroupResourceTest { } @Test - public void testValidateInvald() throws Exception { + public void testValidateInvalid() throws Exception { ObjectMapper mapper = new ObjectMapper(); ServiceGroupValidationRO validate = new ServiceGroupValidationRO(); validate.setExtension(validExtension + "<ADFA>sdfadsf"); @@ -196,7 +197,8 @@ public class ServiceGroupResourceTest { MvcResult result = mvc.perform(post(PATH + "/extension/validate") .with(SMP_ADMIN_CREDENTIALS) .header("Content-Type","application/json") - .content(mapper.writeValueAsString(validate))) + .content(mapper.writeValueAsString(validate)) + .with(csrf())) .andExpect(status().isOk()).andReturn(); //then diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/TruststoreResourceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/TruststoreResourceTest.java index 8b9ac9344fac36003bd42c2e30473b8cff981fcf..dd8f0c1c48156be4eacd1727f3cb034ccc6abc4a 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/TruststoreResourceTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/TruststoreResourceTest.java @@ -40,6 +40,7 @@ import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -94,8 +95,10 @@ public class TruststoreResourceTest { public void getCertificateList() throws Exception { // given when int countStart = uiTruststoreService.getCertificateROEntriesList().size(); - MvcResult result = mvc.perform(get(PATH).with(SYSTEM_CREDENTIALS)). - andExpect(status().isOk()).andReturn(); + MvcResult result = mvc.perform(get(PATH) + .with(SYSTEM_CREDENTIALS) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); //them ObjectMapper mapper = new ObjectMapper(); @@ -123,6 +126,7 @@ public class TruststoreResourceTest { // given when MvcResult result = mvc.perform(post(PATH+"/3/certdata") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(buff)) .andExpect(status().isOk()).andReturn(); @@ -145,6 +149,7 @@ public class TruststoreResourceTest { int countStart = uiTruststoreService.getNormalizedTrustedList().size(); MvcResult prepRes = mvc.perform(post(PATH+"/3/certdata") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(buff)) .andExpect(status().isOk()).andReturn(); @@ -158,6 +163,7 @@ public class TruststoreResourceTest { // then MvcResult result = mvc.perform(delete(PATH+"/3/delete/"+res.getAlias()) .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(buff)) .andExpect(status().isOk()).andReturn(); uiTruststoreService.refreshData(); diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/UserResourceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/UserResourceTest.java index eab1870de97d5192b3b990ef5984d1d0d52f314d..f739b076a76165a9b7405827704e9603f95e203f 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/UserResourceTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/UserResourceTest.java @@ -40,6 +40,7 @@ import java.util.Optional; import java.util.UUID; import static org.junit.Assert.*; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -88,8 +89,10 @@ public class UserResourceTest { @Test public void getUserList() throws Exception { // given when - MvcResult result = mvc.perform(get(PATH).with(ADMIN_CREDENTIALS)). - andExpect(status().isOk()).andReturn(); + MvcResult result = mvc.perform(get(PATH) + .with(ADMIN_CREDENTIALS) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); //them ObjectMapper mapper = new ObjectMapper(); @@ -127,7 +130,9 @@ public class UserResourceTest { } userRO.getCertificate().setCertificateId(UUID.randomUUID().toString()); - mvc.perform(put(PATH+"/"+userRO.getId()).with(ADMIN_CREDENTIALS) + mvc.perform(put(PATH+"/"+userRO.getId()) + .with(ADMIN_CREDENTIALS) + .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(userRO)) ).andExpect(status().isOk()).andReturn(); @@ -155,7 +160,9 @@ public class UserResourceTest { } userRO.getCertificate().setCertificateId(UUID.randomUUID().toString()); - mvc.perform(put(PATH+"/"+userRO.getId()).with(SYSTEM_CREDENTIALS) + mvc.perform(put(PATH+"/"+userRO.getId()) + .with(SYSTEM_CREDENTIALS) + .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(userRO)) ).andExpect(status().isUnauthorized()); @@ -164,8 +171,10 @@ public class UserResourceTest { @Test public void testUpdateUserList() throws Exception { // given when - MvcResult result = mvc.perform(get(PATH).with(SYSTEM_CREDENTIALS)). - andExpect(status().isOk()).andReturn(); + MvcResult result = mvc.perform(get(PATH) + .with(SYSTEM_CREDENTIALS) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); ObjectMapper mapper = new ObjectMapper(); ServiceResult res = mapper.readValue(result.getResponse().getContentAsString(), ServiceResult.class); assertNotNull(res); @@ -181,7 +190,9 @@ public class UserResourceTest { userRO.getCertificate().setCertificateId(UUID.randomUUID().toString()); mvc.perform(put(PATH) - .with(SYSTEM_CREDENTIALS).contentType(MediaType.APPLICATION_JSON) + .with(SYSTEM_CREDENTIALS) + .with(csrf()) + .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(Arrays.asList(userRO))) ).andExpect(status().isOk()); } @@ -189,8 +200,10 @@ public class UserResourceTest { @Test public void testUpdateUserListWrongAuthentication() throws Exception { // given when - MvcResult result = mvc.perform(get(PATH).with(SYSTEM_CREDENTIALS)). - andExpect(status().isOk()).andReturn(); + MvcResult result = mvc.perform(get(PATH) + .with(SYSTEM_CREDENTIALS) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); ObjectMapper mapper = new ObjectMapper(); ServiceResult res = mapper.readValue(result.getResponse().getContentAsString(), ServiceResult.class); assertNotNull(res); @@ -206,17 +219,22 @@ public class UserResourceTest { userRO.getCertificate().setCertificateId(UUID.randomUUID().toString()); // anonymous mvc.perform(put(PATH) + .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(Arrays.asList(userRO))) ).andExpect(status().isUnauthorized()); mvc.perform(put(PATH) - .with(ADMIN_CREDENTIALS).contentType(MediaType.APPLICATION_JSON) + .with(ADMIN_CREDENTIALS) + .with(csrf()) + .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(Arrays.asList(userRO))) ).andExpect(status().isUnauthorized()); mvc.perform(put(PATH) - .with(SG_ADMIN_CREDENTIALS).contentType(MediaType.APPLICATION_JSON) + .with(SG_ADMIN_CREDENTIALS) + .with(csrf()) + .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(Arrays.asList(userRO))) ).andExpect(status().isUnauthorized()); } @@ -228,6 +246,7 @@ public class UserResourceTest { // given when MvcResult result = mvc.perform(post(PATH+"/1098765430/certdata") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(buff)) .andExpect(status().isOk()).andReturn(); @@ -250,6 +269,7 @@ public class UserResourceTest { // given when mvc.perform(post(PATH+"/1098765430/certdata") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(buff)) .andExpect(status().is5xxServerError()) .andExpect(content().string(CoreMatchers.containsString(" The certificate is not valid"))); @@ -265,6 +285,7 @@ public class UserResourceTest { // given when MvcResult result = mvc.perform(post(PATH+"/1098765430/certdata") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .content(buff)) .andExpect(status().isOk()).andReturn(); @@ -283,6 +304,7 @@ public class UserResourceTest { // given when mvc.perform(post(PATH+"/34556655/certdata") .with(ADMIN_CREDENTIALS) + .with(csrf()) .content(buff)) .andExpect(status().isUnauthorized()).andReturn(); } @@ -292,6 +314,7 @@ public class UserResourceTest { // 1 is id for smp_admin MvcResult result = mvc.perform(post(PATH+"/1/samePreviousPasswordUsed") .with(ADMIN_CREDENTIALS) + .with(csrf()) .content("test123")) .andExpect(status().isOk()).andReturn(); @@ -304,6 +327,7 @@ public class UserResourceTest { // 1 is id for smp_admin MvcResult result = mvc.perform(post(PATH+"/1/samePreviousPasswordUsed") .with(ADMIN_CREDENTIALS) + .with(csrf()) .content("7777")) .andExpect(status().isOk()).andReturn(); @@ -316,16 +340,16 @@ public class UserResourceTest { // 1 is id for smp_admin so for 3 should be Unauthorized MvcResult result = mvc.perform(post(PATH+"/3/samePreviousPasswordUsed") .with(ADMIN_CREDENTIALS) + .with(csrf()) .content("test123")) .andExpect(status().isUnauthorized()).andReturn(); - - } @Test public void testValidateDeleteUserOK() throws Exception { MvcResult result = mvc.perform(post(PATH+"/validateDelete") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .contentType(org.springframework.http.MediaType.APPLICATION_JSON) .content("[5]")) .andExpect(status().isOk()).andReturn(); @@ -343,6 +367,7 @@ public class UserResourceTest { // note system credential has id 3! MvcResult result = mvc.perform(post(PATH+"/validateDelete") .with(SYSTEM_CREDENTIALS) + .with(csrf()) .contentType(org.springframework.http.MediaType.APPLICATION_JSON) .content("[3]")) .andExpect(status().isOk())