From fa8cecd46a188dee8185ac1d0321a664de3629cf Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:43:43 +0000 Subject: [PATCH] bug: POST-only admin enable/disable + appointment confirm, enable CSRF (cookie token for AdminPortal), SameSite=Lax cookies (sfind-e783cad7) --- AdminPortal/src/app/appointment.service.ts | 2 +- .../app/appointment/appointment.component.ts | 6 +- AdminPortal/src/app/login.service.ts | 9 +- .../src/app/navbar/navbar.component.ts | 4 +- .../user-account/user-account.component.ts | 12 +- AdminPortal/src/app/user.service.ts | 4 +- UserFront/pom.xml | 6 + .../com/userFront/config/RequestFilter.java | 4 +- .../config/SameSiteCookieConfig.java | 20 +++ .../config/SameSiteCookieProcessor.java | 49 +++++ .../com/userFront/config/SecurityConfig.java | 10 +- .../controller/TransferController.java | 2 +- .../resource/AppointmentResource.java | 3 +- .../com/userFront/resource/CsrfResource.java | 18 ++ .../com/userFront/resource/UserResource.java | 4 +- .../main/resources/templates/appointment.html | 3 - .../resources/templates/betweenAccounts.html | 3 - .../resources/templates/common/header.html | 6 +- .../src/main/resources/templates/deposit.html | 3 - .../main/resources/templates/recipient.html | 10 +- .../resources/templates/toSomeoneElse.html | 3 - .../main/resources/templates/withdraw.html | 3 - .../userFront/config/CsrfProtectionTest.java | 167 ++++++++++++++++++ .../config/SameSiteCookieProcessorTest.java | 39 ++++ 24 files changed, 348 insertions(+), 42 deletions(-) create mode 100644 UserFront/src/main/java/com/userFront/config/SameSiteCookieConfig.java create mode 100644 UserFront/src/main/java/com/userFront/config/SameSiteCookieProcessor.java create mode 100644 UserFront/src/main/java/com/userFront/resource/CsrfResource.java create mode 100644 UserFront/src/test/java/com/userFront/config/CsrfProtectionTest.java create mode 100644 UserFront/src/test/java/com/userFront/config/SameSiteCookieProcessorTest.java diff --git a/AdminPortal/src/app/appointment.service.ts b/AdminPortal/src/app/appointment.service.ts index ad506808..2cfaeac8 100644 --- a/AdminPortal/src/app/appointment.service.ts +++ b/AdminPortal/src/app/appointment.service.ts @@ -14,7 +14,7 @@ export class AppointmentService { confirmAppointment(id: number) { let url = "http://localhost:8080/api/appointment/"+id+"/confirm"; - return this.http.get(url, { withCredentials: true }); + return this.http.post(url, null, { withCredentials: true }); } } diff --git a/AdminPortal/src/app/appointment/appointment.component.ts b/AdminPortal/src/app/appointment/appointment.component.ts index 5be37e91..cf6a8a3d 100644 --- a/AdminPortal/src/app/appointment/appointment.component.ts +++ b/AdminPortal/src/app/appointment/appointment.component.ts @@ -25,8 +25,10 @@ export class AppointmentComponent implements OnInit { } confirmAppointment(id: number) { - this.appointmentService.confirmAppointment(id).subscribe(); - location.reload(); + this.appointmentService.confirmAppointment(id).subscribe( + res => location.reload(), + error => console.log(error) + ); } ngOnInit() {} diff --git a/AdminPortal/src/app/login.service.ts b/AdminPortal/src/app/login.service.ts index a229f8f0..1095e6ab 100644 --- a/AdminPortal/src/app/login.service.ts +++ b/AdminPortal/src/app/login.service.ts @@ -1,6 +1,7 @@ import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/http'; import {Observable} from 'rxjs/Observable'; +import 'rxjs/add/operator/mergeMap'; @Injectable() export class LoginService { @@ -15,12 +16,16 @@ export class LoginService { 'Content-Type': 'application/x-www-form-urlencoded' // 'Access-Control-Allow-Credentials' : true }); - return this.http.post(url, params, {headers: headers, withCredentials : true}); + // Fetch the XSRF-TOKEN cookie first; Http sends it back as the X-XSRF-TOKEN header. + return this.http.get('http://localhost:8080/api/csrf', { withCredentials: true }) + .mergeMap(() => this.http.post(url, params, {headers: headers, withCredentials : true})); } logout() { let url = 'http://localhost:8080/logout'; - return this.http.get(url, { withCredentials: true }); + // Login rotates the CSRF token, so fetch the current XSRF-TOKEN cookie before posting. + return this.http.get('http://localhost:8080/api/csrf', { withCredentials: true }) + .mergeMap(() => this.http.post(url, null, { withCredentials: true })); } } diff --git a/AdminPortal/src/app/navbar/navbar.component.ts b/AdminPortal/src/app/navbar/navbar.component.ts index 019989bd..61e22956 100644 --- a/AdminPortal/src/app/navbar/navbar.component.ts +++ b/AdminPortal/src/app/navbar/navbar.component.ts @@ -23,11 +23,11 @@ export class NavbarComponent implements OnInit { this.loginService.logout().subscribe( res => { localStorage.setItem('PortalAdminHasLoggedIn', ''); + location.reload(); + this.router.navigate(['/login']); }, err => console.log(err) ); - location.reload(); - this.router.navigate(['/login']); } getDisplay() { diff --git a/AdminPortal/src/app/user-account/user-account.component.ts b/AdminPortal/src/app/user-account/user-account.component.ts index 872546c7..948a65a0 100644 --- a/AdminPortal/src/app/user-account/user-account.component.ts +++ b/AdminPortal/src/app/user-account/user-account.component.ts @@ -33,13 +33,17 @@ export class UserAccountComponent implements OnInit { } enableUser(username: string) { - this.userService.enableUser(username).subscribe(); - location.reload(); + this.userService.enableUser(username).subscribe( + res => location.reload(), + error => console.log(error) + ); } disableUser(username: string) { - this.userService.disableUser(username).subscribe(); - location.reload(); + this.userService.disableUser(username).subscribe( + res => location.reload(), + error => console.log(error) + ); } diff --git a/AdminPortal/src/app/user.service.ts b/AdminPortal/src/app/user.service.ts index bde10a38..424ec2a1 100644 --- a/AdminPortal/src/app/user.service.ts +++ b/AdminPortal/src/app/user.service.ts @@ -24,12 +24,12 @@ export class UserService { enableUser (username: string) { let url = "http://localhost:8080/api/user/"+username+"/enable"; - return this.http.get(url, { withCredentials: true }); + return this.http.post(url, null, { withCredentials: true }); } disableUser (username: string) { let url = "http://localhost:8080/api/user/"+username+"/disable"; - return this.http.get(url, { withCredentials: true }); + return this.http.post(url, null, { withCredentials: true }); } } diff --git a/UserFront/pom.xml b/UserFront/pom.xml index 902ec2b3..c491cd53 100644 --- a/UserFront/pom.xml +++ b/UserFront/pom.xml @@ -60,6 +60,12 @@ spring-boot-starter-test test + + + org.springframework.security + spring-security-test + test + diff --git a/UserFront/src/main/java/com/userFront/config/RequestFilter.java b/UserFront/src/main/java/com/userFront/config/RequestFilter.java index efff86c5..7a9c4fdc 100644 --- a/UserFront/src/main/java/com/userFront/config/RequestFilter.java +++ b/UserFront/src/main/java/com/userFront/config/RequestFilter.java @@ -22,7 +22,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200"); //8081 response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); - response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); + response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-xsrf-token"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); @@ -37,7 +37,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "authorization, content-type," + - "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with"); + "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,x-xsrf-token"); response.setStatus(HttpServletResponse.SC_OK); } diff --git a/UserFront/src/main/java/com/userFront/config/SameSiteCookieConfig.java b/UserFront/src/main/java/com/userFront/config/SameSiteCookieConfig.java new file mode 100644 index 00000000..9f925310 --- /dev/null +++ b/UserFront/src/main/java/com/userFront/config/SameSiteCookieConfig.java @@ -0,0 +1,20 @@ +package com.userFront.config; + +import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; +import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SameSiteCookieConfig { + + @Bean + public EmbeddedServletContainerCustomizer sameSiteCookieCustomizer() { + return container -> { + if (container instanceof TomcatEmbeddedServletContainerFactory) { + ((TomcatEmbeddedServletContainerFactory) container).addContextCustomizers( + context -> context.setCookieProcessor(new SameSiteCookieProcessor("Lax"))); + } + }; + } +} diff --git a/UserFront/src/main/java/com/userFront/config/SameSiteCookieProcessor.java b/UserFront/src/main/java/com/userFront/config/SameSiteCookieProcessor.java new file mode 100644 index 00000000..98910a57 --- /dev/null +++ b/UserFront/src/main/java/com/userFront/config/SameSiteCookieProcessor.java @@ -0,0 +1,49 @@ +package com.userFront.config; + +import java.nio.charset.Charset; +import java.util.Locale; + +import javax.servlet.http.Cookie; + +import org.apache.tomcat.util.http.CookieProcessor; +import org.apache.tomcat.util.http.MimeHeaders; +import org.apache.tomcat.util.http.Rfc6265CookieProcessor; +import org.apache.tomcat.util.http.ServerCookies; + +/** + * Adds a SameSite attribute to every cookie Tomcat writes (JSESSIONID, remember-me, XSRF-TOKEN). + * The bundled Tomcat predates Rfc6265CookieProcessor#setSameSiteCookies, so the header is appended here. + */ +public class SameSiteCookieProcessor implements CookieProcessor { + + private final CookieProcessor delegate; + private final String sameSite; + + public SameSiteCookieProcessor(String sameSite) { + this(new Rfc6265CookieProcessor(), sameSite); + } + + SameSiteCookieProcessor(CookieProcessor delegate, String sameSite) { + this.delegate = delegate; + this.sameSite = sameSite; + } + + @Override + public void parseCookieHeader(MimeHeaders headers, ServerCookies serverCookies) { + delegate.parseCookieHeader(headers, serverCookies); + } + + @Override + public String generateHeader(Cookie cookie) { + String header = delegate.generateHeader(cookie); + if (header.toLowerCase(Locale.ROOT).contains("; samesite=")) { + return header; + } + return header + "; SameSite=" + sameSite; + } + + @Override + public Charset getCharset() { + return delegate.getCharset(); + } +} diff --git a/UserFront/src/main/java/com/userFront/config/SecurityConfig.java b/UserFront/src/main/java/com/userFront/config/SecurityConfig.java index 40b10417..93141d85 100644 --- a/UserFront/src/main/java/com/userFront/config/SecurityConfig.java +++ b/UserFront/src/main/java/com/userFront/config/SecurityConfig.java @@ -13,6 +13,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.userFront.service.UserServiceImpl.UserSecurityService; @@ -45,7 +46,8 @@ public BCryptPasswordEncoder passwordEncoder() { "/contact/**", "/error/**/*", "/console/**", - "/signup" + "/signup", + "/api/csrf" }; @Override @@ -57,10 +59,12 @@ protected void configure(HttpSecurity http) throws Exception { permitAll().anyRequest().authenticated(); http - .csrf().disable().cors().disable() + .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) + .and() + .cors().disable() .formLogin().failureUrl("/index?error").defaultSuccessUrl("/userFront").loginPage("/index").permitAll() .and() - .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/index?logout").deleteCookies("remember-me").permitAll() + .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST")).logoutSuccessUrl("/index?logout").deleteCookies("remember-me").permitAll() .and() .rememberMe(); } diff --git a/UserFront/src/main/java/com/userFront/controller/TransferController.java b/UserFront/src/main/java/com/userFront/controller/TransferController.java index a6a8182c..3617cb68 100644 --- a/UserFront/src/main/java/com/userFront/controller/TransferController.java +++ b/UserFront/src/main/java/com/userFront/controller/TransferController.java @@ -85,7 +85,7 @@ public String recipientEdit(@RequestParam(value = "recipientName") String recipi return "recipient"; } - @RequestMapping(value = "/recipient/delete", method = RequestMethod.GET) + @RequestMapping(value = "/recipient/delete", method = RequestMethod.POST) @Transactional public String recipientDelete(@RequestParam(value = "recipientName") String recipientName, Model model, Principal principal) { diff --git a/UserFront/src/main/java/com/userFront/resource/AppointmentResource.java b/UserFront/src/main/java/com/userFront/resource/AppointmentResource.java index bcb37490..606ed3ce 100644 --- a/UserFront/src/main/java/com/userFront/resource/AppointmentResource.java +++ b/UserFront/src/main/java/com/userFront/resource/AppointmentResource.java @@ -6,6 +6,7 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.userFront.domain.Appointment; @@ -26,7 +27,7 @@ public List findAppointmentList() { return appointmentList; } - @RequestMapping("/{id}/confirm") + @RequestMapping(value = "/{id}/confirm", method = RequestMethod.POST) public void confirmAppointment(@PathVariable("id") Long id) { appointmentService.confirmAppointment(id); } diff --git a/UserFront/src/main/java/com/userFront/resource/CsrfResource.java b/UserFront/src/main/java/com/userFront/resource/CsrfResource.java new file mode 100644 index 00000000..63d151bb --- /dev/null +++ b/UserFront/src/main/java/com/userFront/resource/CsrfResource.java @@ -0,0 +1,18 @@ +package com.userFront.resource; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * Lets the AdminPortal SPA obtain the XSRF-TOKEN cookie (issued by the CSRF filter) before its first POST. + */ +@RestController +public class CsrfResource { + + @RequestMapping(value = "/api/csrf", method = RequestMethod.GET) + public ResponseEntity csrf() { + return ResponseEntity.noContent().build(); + } +} diff --git a/UserFront/src/main/java/com/userFront/resource/UserResource.java b/UserFront/src/main/java/com/userFront/resource/UserResource.java index d43c01b9..c0852167 100644 --- a/UserFront/src/main/java/com/userFront/resource/UserResource.java +++ b/UserFront/src/main/java/com/userFront/resource/UserResource.java @@ -42,12 +42,12 @@ public List getSavingsTransactionList(@RequestParam("usernam return transactionService.findSavingsTransactionList(username); } - @RequestMapping("/user/{username}/enable") + @RequestMapping(value = "/user/{username}/enable", method = RequestMethod.POST) public void enableUser(@PathVariable("username") String username) { userService.enableUser(username); } - @RequestMapping("/user/{username}/disable") + @RequestMapping(value = "/user/{username}/disable", method = RequestMethod.POST) public void diableUser(@PathVariable("username") String username) { userService.disableUser(username); } diff --git a/UserFront/src/main/resources/templates/appointment.html b/UserFront/src/main/resources/templates/appointment.html index 5c60611a..db604c94 100644 --- a/UserFront/src/main/resources/templates/appointment.html +++ b/UserFront/src/main/resources/templates/appointment.html @@ -39,9 +39,6 @@

Schedule An Appointment

- Submit Scheduling diff --git a/UserFront/src/main/resources/templates/betweenAccounts.html b/UserFront/src/main/resources/templates/betweenAccounts.html index 9caca1bb..9f481b69 100644 --- a/UserFront/src/main/resources/templates/betweenAccounts.html +++ b/UserFront/src/main/resources/templates/betweenAccounts.html @@ -33,9 +33,6 @@ - diff --git a/UserFront/src/main/resources/templates/common/header.html b/UserFront/src/main/resources/templates/common/header.html index 413f60bf..c7f13d12 100644 --- a/UserFront/src/main/resources/templates/common/header.html +++ b/UserFront/src/main/resources/templates/common/header.html @@ -90,7 +90,11 @@ diff --git a/UserFront/src/main/resources/templates/deposit.html b/UserFront/src/main/resources/templates/deposit.html index 5184ca09..9b1e460c 100644 --- a/UserFront/src/main/resources/templates/deposit.html +++ b/UserFront/src/main/resources/templates/deposit.html @@ -23,9 +23,6 @@ - diff --git a/UserFront/src/main/resources/templates/recipient.html b/UserFront/src/main/resources/templates/recipient.html index b35e73db..a8c5c011 100644 --- a/UserFront/src/main/resources/templates/recipient.html +++ b/UserFront/src/main/resources/templates/recipient.html @@ -36,9 +36,6 @@

Recipient Information

id="recipientDescription" placeholder="Description" th:text="${recipient.description}"> - @@ -69,7 +66,12 @@

List of Recipients

... ... ... - delete + +
+ + +
+ diff --git a/UserFront/src/main/resources/templates/toSomeoneElse.html b/UserFront/src/main/resources/templates/toSomeoneElse.html index 5e991d95..69cdc334 100644 --- a/UserFront/src/main/resources/templates/toSomeoneElse.html +++ b/UserFront/src/main/resources/templates/toSomeoneElse.html @@ -32,9 +32,6 @@ - diff --git a/UserFront/src/main/resources/templates/withdraw.html b/UserFront/src/main/resources/templates/withdraw.html index 1ecfdb5f..0d6d1358 100644 --- a/UserFront/src/main/resources/templates/withdraw.html +++ b/UserFront/src/main/resources/templates/withdraw.html @@ -23,9 +23,6 @@ - diff --git a/UserFront/src/test/java/com/userFront/config/CsrfProtectionTest.java b/UserFront/src/test/java/com/userFront/config/CsrfProtectionTest.java new file mode 100644 index 00000000..a7c360a4 --- /dev/null +++ b/UserFront/src/test/java/com/userFront/config/CsrfProtectionTest.java @@ -0,0 +1,167 @@ +package com.userFront.config; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import javax.servlet.http.Cookie; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.MethodMode; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.userFront.resource.AppointmentResource; +import com.userFront.resource.CsrfResource; +import com.userFront.resource.UserResource; +import com.userFront.service.AppointmentService; +import com.userFront.service.TransactionService; +import com.userFront.service.UserService; +import com.userFront.service.UserServiceImpl.UserSecurityService; + +@RunWith(SpringRunner.class) +@WebMvcTest(controllers = {UserResource.class, AppointmentResource.class, CsrfResource.class}) +@Import(SecurityConfig.class) +public class CsrfProtectionTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private UserService userService; + + @MockBean + private TransactionService transactionService; + + @MockBean + private AppointmentService appointmentService; + + @MockBean + private UserSecurityService userSecurityService; + + @Test + public void loginWithoutCsrfTokenIsForbidden() throws Exception { + mockMvc.perform(post("/index").param("username", "admin").param("password", "pw")) + .andExpect(status().isForbidden()); + } + + @Test + @WithMockUser(roles = "ADMIN") + public void enableUserWithoutCsrfTokenIsForbidden() throws Exception { + mockMvc.perform(post("/api/user/bob/enable")) + .andExpect(status().isForbidden()); + + verify(userService, never()).enableUser(anyString()); + } + + @Test + @WithMockUser(roles = "ADMIN") + public void enableUserWithCsrfTokenSucceeds() throws Exception { + mockMvc.perform(post("/api/user/bob/enable").with(csrf())) + .andExpect(status().isOk()); + + verify(userService).enableUser("bob"); + } + + @Test + @WithMockUser(roles = "ADMIN") + public void enableUserViaGetIsRejected() throws Exception { + mockMvc.perform(get("/api/user/bob/enable")) + .andExpect(status().isMethodNotAllowed()); + + verify(userService, never()).enableUser(anyString()); + } + + @Test + @WithMockUser(roles = "ADMIN") + public void disableUserWithoutCsrfTokenIsForbidden() throws Exception { + mockMvc.perform(post("/api/user/bob/disable")) + .andExpect(status().isForbidden()); + + verify(userService, never()).disableUser(anyString()); + } + + @Test + @WithMockUser(roles = "ADMIN") + public void confirmAppointmentRequiresPostWithCsrfToken() throws Exception { + mockMvc.perform(get("/api/appointment/1/confirm")) + .andExpect(status().isMethodNotAllowed()); + mockMvc.perform(post("/api/appointment/1/confirm")) + .andExpect(status().isForbidden()); + verify(appointmentService, never()).confirmAppointment(anyLong()); + + mockMvc.perform(post("/api/appointment/1/confirm").with(csrf())) + .andExpect(status().isOk()); + verify(appointmentService).confirmAppointment(1L); + } + + // csrf() swaps the CsrfFilter's token repository in the cached context; start from a clean one. + @Test + @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) + @WithMockUser(roles = "ADMIN") + public void xsrfCookieIssuedByCsrfEndpointIsAcceptedAsHeader() throws Exception { + Cookie xsrf = mockMvc.perform(get("/api/csrf")) + .andExpect(status().isNoContent()) + .andExpect(cookie().exists("XSRF-TOKEN")) + .andReturn().getResponse().getCookie("XSRF-TOKEN"); + assertNotNull(xsrf); + assertFalse(xsrf.isHttpOnly()); + + mockMvc.perform(post("/api/user/bob/enable").cookie(xsrf).header("X-XSRF-TOKEN", xsrf.getValue())) + .andExpect(status().isOk()); + + verify(userService).enableUser("bob"); + } + + // csrf() swaps the CsrfFilter's token repository in the cached context; start from a clean one. + @Test + @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) + @WithMockUser(roles = "ADMIN") + public void mismatchedXsrfHeaderIsForbidden() throws Exception { + Cookie xsrf = mockMvc.perform(get("/api/csrf")) + .andReturn().getResponse().getCookie("XSRF-TOKEN"); + + mockMvc.perform(post("/api/user/bob/enable").cookie(xsrf).header("X-XSRF-TOKEN", "forged")) + .andExpect(status().isForbidden()); + + verify(userService, never()).enableUser(anyString()); + } + + @Test + @WithMockUser + public void logoutRequiresPostWithCsrfToken() throws Exception { + mockMvc.perform(post("/logout")) + .andExpect(status().isForbidden()); + + mockMvc.perform(post("/logout").with(csrf())) + .andExpect(redirectedUrl("/index?logout")); + } + + @Test + public void preflightAllowsXsrfHeader() throws Exception { + mockMvc.perform(options("/api/user/bob/enable") + .header("Origin", "http://localhost:4200") + .header("Access-Control-Request-Method", "POST")) + .andExpect(status().isOk()) + .andExpect(header().string("Access-Control-Allow-Headers", containsString("x-xsrf-token"))); + } +} diff --git a/UserFront/src/test/java/com/userFront/config/SameSiteCookieProcessorTest.java b/UserFront/src/test/java/com/userFront/config/SameSiteCookieProcessorTest.java new file mode 100644 index 00000000..25607a61 --- /dev/null +++ b/UserFront/src/test/java/com/userFront/config/SameSiteCookieProcessorTest.java @@ -0,0 +1,39 @@ +package com.userFront.config; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.endsWith; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import javax.servlet.http.Cookie; + +import org.junit.Test; + +public class SameSiteCookieProcessorTest { + + private final SameSiteCookieProcessor processor = new SameSiteCookieProcessor("Lax"); + + @Test + public void sessionCookieGetsSameSiteLax() { + Cookie cookie = new Cookie("JSESSIONID", "abc123"); + cookie.setPath("/"); + cookie.setHttpOnly(true); + + String header = processor.generateHeader(cookie); + + assertThat(header, containsString("JSESSIONID=abc123")); + assertThat(header, containsString("HttpOnly")); + assertThat(header, endsWith("; SameSite=Lax")); + } + + @Test + public void existingSameSiteAttributeIsNotDuplicated() { + SameSiteCookieProcessor wrapped = new SameSiteCookieProcessor( + new SameSiteCookieProcessor("Strict"), "Lax"); + + String header = wrapped.generateHeader(new Cookie("XSRF-TOKEN", "t")); + + assertThat(header, endsWith("; SameSite=Strict")); + assertEquals(header.indexOf("SameSite"), header.lastIndexOf("SameSite")); + } +}