Revert unnecessary merges on 6.0.x

This commit removes unnecessary main-branch merges starting from
8750608b5b and adds the following
needed commit(s) that were made afterward:

- 5dce82c48b
This commit is contained in:
Steve Riesenberg
2023-10-31 15:11:45 -05:00
parent e9d4223402
commit 9db33f33c7
676 changed files with 6306 additions and 43249 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.security.web;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -27,7 +26,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
/**
* @author Luke Taylor
* @author Mark Chesney
* @since 3.0
*/
public class DefaultRedirectStrategyTests {
@@ -66,21 +64,4 @@ public class DefaultRedirectStrategyTests {
.isThrownBy(() -> rds.sendRedirect(request, response, "https://redirectme.somewhere.else"));
}
@Test
public void statusCodeIsHandledCorrectly() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
// when
redirectStrategy.sendRedirect(request, response, "/requested");
// then
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}
}

View File

@@ -97,24 +97,6 @@ public class ObservationFilterChainDecoratorTests {
assertThat(events.get(1).getName()).isEqualTo(filter.getClass().getSimpleName() + ".after");
}
@Test
void decorateFiltersWhenDefaultsThenUsesEventName() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = new BasicAuthenticationFilter();
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(handler, times(2)).onEvent(event.capture(), any());
List<Observation.Event> events = event.getAllValues();
assertThat(events.get(0).getName()).isEqualTo("authentication.basic.before");
assertThat(events.get(1).getName()).isEqualTo("authentication.basic.after");
}
// gh-12787
@Test
void decorateFiltersWhenErrorsThenClosesObservationOnlyOnce() throws Exception {
@@ -150,13 +132,6 @@ public class ObservationFilterChainDecoratorTests {
.isEqualTo(expectedFilterNameTag);
}
// gh-13660
@Test
void observationNamesDoNotContainDashes() {
ObservationFilterChainDecorator.ObservationFilter.OBSERVATION_NAMES.values()
.forEach((name) -> assertThat(name).doesNotContain("-"));
}
static Stream<Arguments> decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag() {
Filter filterWithName = new BasicAuthenticationFilter();

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.access;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.AccessDeniedException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class NoOpAccessDeniedHandlerTests {
private final NoOpAccessDeniedHandler handler = new NoOpAccessDeniedHandler();
@Test
void handleWhenInvokedThenDoesNothing() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
AccessDeniedException exception = mock(AccessDeniedException.class);
this.handler.handle(request, response, exception);
verifyNoInteractions(request, response, exception);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,20 +21,16 @@ import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.TestAuthentication;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link RequestMatcherDelegatingAuthorizationManager}.
@@ -128,280 +124,4 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
.withMessage("mappingsConsumer cannot be null");
}
@Test
public void mappingsWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.mappings((m) -> m.add(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE,
AuthenticatedAuthorizationManager.authenticated()))))
.withMessage("Can't configure mappings after anyRequest");
}
@Test
public void addWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.add(AnyRequestMatcher.INSTANCE, AuthenticatedAuthorizationManager.authenticated()))
.withMessage("Can't add mappings after anyRequest");
}
@Test
public void requestMatchersWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.requestMatchers(new AntPathRequestMatcher("/authenticated"))
.authenticated()
.build())
.withMessage("Can't configure requestMatchers after anyRequest");
}
@Test
public void anyRequestWhenConfiguredAfterAnyRequestThenException() {
assertThatIllegalStateException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.anyRequest()
.authenticated()
.build())
.withMessage("Can't configure anyRequest after itself");
}
@Test
public void anyRequestWhenPermitAllThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.permitAll()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void anyRequestWhenDenyAllThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.denyAll()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void authenticatedWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void authenticatedWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.authenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void fullyAuthenticatedWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.fullyAuthenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void fullyAuthenticatedWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.fullyAuthenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void fullyAuthenticatedWhenRememberMeUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.fullyAuthenticated()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::rememberMeUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void rememberMeWhenRememberMeUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.rememberMe()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::rememberMeUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void rememberMeWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.rememberMe()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void anonymousWhenAnonymousUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.anonymous()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void anonymousWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.anonymous()
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasRoleAdminWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasRole("ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasRoleAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasRole("ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyRoleUserOrAdminWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyRoleUserOrAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyRoleUserOrAdminWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasAuthorityRoleAdminWhenAuthenticatedUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAuthority("ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
@Test
public void hasAuthorityRoleAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAuthority("ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyAuthorityRoleUserOrAdminWhenAuthenticatedUserThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyAuthorityRoleUserOrAdminWhenAuthenticatedAdminThenGrantedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::authenticatedAdmin, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isTrue();
}
@Test
public void hasAnyAuthorityRoleUserOrAdminWhenAnonymousUserThenDeniedDecision() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.anyRequest()
.hasAnyRole("USER", "ADMIN")
.build();
AuthorizationDecision decision = manager.check(TestAuthentication::anonymousUser, null);
assertThat(decision).isNotNull();
assertThat(decision.isGranted()).isFalse();
}
}

View File

@@ -1,111 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dayan Kodippily
*/
public class AbstractAuthenticationTargetUrlRequestHandlerTests {
public static final String REQUEST_URI = "https://example.org";
public static final String DEFAULT_TARGET_URL = "/defaultTarget";
public static final String REFERER_URL = "https://www.springsource.com/";
public static final String TARGET_URL = "https://example.org/target";
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private AbstractAuthenticationTargetUrlRequestHandler handler;
@BeforeEach
void setUp() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.handler = new AbstractAuthenticationTargetUrlRequestHandler() {
@Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
return super.determineTargetUrl(request, response);
}
};
this.handler.setDefaultTargetUrl(DEFAULT_TARGET_URL);
this.request.setRequestURI(REQUEST_URI);
}
@Test
void returnDefaultTargetUrlIfUseDefaultTargetUrlTrue() {
this.handler.setAlwaysUseDefaultTargetUrl(true);
assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL);
}
@Test
void returnTargetUrlParamValueIfParamHasValue() {
this.handler.setTargetUrlParameter("param");
this.request.setParameter("param", TARGET_URL);
assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(TARGET_URL);
}
@Test
void targetUrlParamValueTakePrecedenceOverRefererIfParamHasValue() {
this.handler.setUseReferer(true);
this.handler.setTargetUrlParameter("param");
this.request.setParameter("param", TARGET_URL);
assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(TARGET_URL);
}
@Test
void returnDefaultTargetUrlIfTargetUrlParamHasNoValue() {
this.handler.setTargetUrlParameter("param");
this.request.setParameter("param", "");
assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL);
}
@Test
void returnDefaultTargetUrlIfTargetUrlParamHasNoValueContainsOnlyWhiteSpaces() {
this.handler.setTargetUrlParameter("param");
this.request.setParameter("param", " ");
assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL);
}
@Test
void returnRefererUrlIfUseRefererIsTrue() {
this.handler.setUseReferer(true);
this.request.addHeader("Referer", REFERER_URL);
assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(REFERER_URL);
}
@Test
void returnDefaultTargetUrlIfUseRefererIsFalse() {
this.handler.setUseReferer(false);
this.request.addHeader("Referer", REFERER_URL);
assertThat(this.handler.determineTargetUrl(this.request, this.response)).isEqualTo(DEFAULT_TARGET_URL);
}
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.AuthenticationException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class NoOpAuthenticationEntryPointTests {
private final NoOpAuthenticationEntryPoint authenticationEntryPoint = new NoOpAuthenticationEntryPoint();
@Test
void commenceWhenInvokedThenDoesNothing() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
AuthenticationException exception = mock(AuthenticationException.class);
this.authenticationEntryPoint.commence(request, response, exception);
verifyNoInteractions(request, response, exception);
}
}

View File

@@ -42,7 +42,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isEqualTo(details);
assertThat(token.getAuthorities()).isEmpty();
assertThat(token.getAuthorities().isEmpty()).isTrue();
}
@Test
@@ -53,7 +53,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isNull();
assertThat(token.getAuthorities()).isEmpty();
assertThat(token.getAuthorities().isEmpty()).isTrue();
}
@Test

View File

@@ -95,10 +95,10 @@ public class JdbcTokenRepositoryImplTests {
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate);
this.repo.createNewToken(token);
Map<String, Object> results = this.template.queryForMap("select * from persistent_logins");
assertThat(results).containsEntry("last_used", currentDate);
assertThat(results).containsEntry("username", "joeuser");
assertThat(results).containsEntry("series", "joesseries");
assertThat(results).containsEntry("token", "atoken");
assertThat(results.get("last_used")).isEqualTo(currentDate);
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
assertThat(results.get("token")).isEqualTo("atoken");
}
@Test
@@ -157,9 +157,9 @@ public class JdbcTokenRepositoryImplTests {
this.repo.updateToken("joesseries", "newtoken", new Date());
Map<String, Object> results = this.template
.queryForMap("select * from persistent_logins where series = 'joesseries'");
assertThat(results).containsEntry("username", "joeuser");
assertThat(results).containsEntry("series", "joesseries");
assertThat(results).containsEntry("token", "newtoken");
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
assertThat(results.get("token")).isEqualTo("newtoken");
Date lastUsed = (Date) results.get("last_used");
assertThat(lastUsed.getTime() > ts.getTime()).isTrue();
}

View File

@@ -93,7 +93,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
response);
assertThat(this.repo.getStoredToken().getSeries()).isEqualTo("series");
assertThat(this.repo.getStoredToken().getTokenValue()).hasSize(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo("series");
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());
@@ -108,8 +108,8 @@ public class PersistentTokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginSuccess(new MockHttpServletRequest(), response,
UsernamePasswordAuthenticationToken.unauthenticated("joe", "password"));
assertThat(this.repo.getStoredToken().getSeries()).hasSize(16);
assertThat(this.repo.getStoredToken().getTokenValue()).hasSize(16);
assertThat(this.repo.getStoredToken().getSeries().length()).isEqualTo(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo(this.repo.getStoredToken().getSeries());
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ public class DefaultLogoutPageGeneratingFilterTests {
+ " <meta name=\"description\" content=\"\">\n" + " <meta name=\"author\" content=\"\">\n"
+ " <title>Confirm Log Out?</title>\n"
+ " <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" integrity=\"sha384-oOE/3m0LUMPub4kaC09mrdEhIc+e3exm4xOGxAmuFXhBNF4hcg/6MiAXAf5p0P56\" crossorigin=\"anonymous\"/>\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"
+ " </head>\n" + " <body>\n" + " <div class=\"container\">\n"
+ " <form class=\"form-signin\" method=\"post\" action=\"/logout\">\n"
+ " <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n"

View File

@@ -21,7 +21,6 @@ import java.nio.charset.StandardCharsets;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -42,12 +41,9 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.test.web.CodecTestUtils;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.util.WebUtils;
import static org.assertj.core.api.Assertions.assertThat;
@@ -492,57 +488,4 @@ public class BasicAuthenticationFilterTests {
assertThat(authenticationRequest.getName()).isEqualTo("rod");
}
@Test
public void doFilterWhenCustomAuthenticationConverterThatIgnoresRequestThenIgnores() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ignored");
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
verify(this.manager, never()).authenticate(any(Authentication.class));
verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verifyNoMoreInteractions(this.manager, filterChain);
}
@Test
public void doFilterWhenCustomAuthenticationConverterRequestThenAuthenticate() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ok");
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
@Test
public void setAuthenticationConverterWhenNullThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthenticationConverter(null));
}
static class TestAuthenticationConverter implements AuthenticationConverter {
private final RequestMatcher matcher = AntPathRequestMatcher.antMatcher("/ignored");
private final BasicAuthenticationConverter delegate = new BasicAuthenticationConverter();
@Override
public Authentication convert(HttpServletRequest request) {
if (this.matcher.matches(request)) {
return null;
}
return this.delegate.convert(request);
}
}
}

View File

@@ -38,16 +38,16 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("username", "rod");
assertThat(headerMap).containsEntry("realm", "Contacts Realm");
assertThat(headerMap).containsEntry("nonce",
"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap).containsEntry("uri",
"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap).containsEntry("response", "38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap).containsEntry("nc", "00000004");
assertThat(headerMap).containsEntry("cnonce", "2b8d329a8571b99a");
assertThat(headerMap.get("username")).isEqualTo("rod");
assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm");
assertThat(headerMap.get("nonce"))
.isEqualTo("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap.get("uri"))
.isEqualTo("/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap.get("response")).isEqualTo("38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("2b8d329a8571b99a");
assertThat(headerMap).hasSize(8);
}
@@ -56,16 +56,16 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", null);
assertThat(headerMap).containsEntry("username", "\"rod\"");
assertThat(headerMap).containsEntry("realm", "\"Contacts Realm\"");
assertThat(headerMap).containsEntry("nonce",
"\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap).containsEntry("uri",
"\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap).containsEntry("response", "\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap).containsEntry("nc", "00000004");
assertThat(headerMap).containsEntry("cnonce", "\"2b8d329a8571b99a\"");
assertThat(headerMap.get("username")).isEqualTo("\"rod\"");
assertThat(headerMap.get("realm")).isEqualTo("\"Contacts Realm\"");
assertThat(headerMap.get("nonce"))
.isEqualTo("\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap.get("uri"))
.isEqualTo("\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap.get("response")).isEqualTo("\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("\"2b8d329a8571b99a\"");
assertThat(headerMap).hasSize(8);
}

View File

@@ -93,8 +93,8 @@ public class DigestAuthenticationEntryPointTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("realm", "hello");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("stale")).isNull();
checkNonceValid(headerMap.get("nonce"));
}
@@ -116,9 +116,9 @@ public class DigestAuthenticationEntryPointTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("realm", "hello");
assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap).containsEntry("stale", "true");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("stale")).isEqualTo("true");
checkNonceValid(headerMap.get("nonce"));
}

View File

@@ -149,7 +149,7 @@ public class DigestAuthenticationFilterTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap).containsEntry("stale", "true");
assertThat(headerMap.get("stale")).isEqualTo("true");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.security.web.context;
import java.util.Collections;
import java.util.EnumSet;
import java.util.EventListener;
import java.util.HashSet;
import java.util.Set;
import jakarta.servlet.DispatcherType;
@@ -318,15 +319,14 @@ public class AbstractSecurityWebApplicationInitializerTests {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class)))
.willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.COOKIE);
@@ -337,20 +337,18 @@ public class AbstractSecurityWebApplicationInitializerTests {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class)))
.willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
willDoNothing().given(context).setSessionTrackingModes(any());
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
@Override
public Set<SessionTrackingMode> getSessionTrackingModes() {
return Collections.singleton(SessionTrackingMode.SSL);
}
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.SSL);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,8 +20,6 @@ import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockCookie;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -31,10 +29,9 @@ import static org.springframework.security.web.csrf.CsrfTokenAssert.assertThatCs
/**
* @author Rob Winch
* @author Alex Montoya
* @since 4.1
*/
class CookieCsrfTokenRepositoryTests {
public class CookieCsrfTokenRepositoryTests {
CookieCsrfTokenRepository repository;
@@ -43,7 +40,7 @@ class CookieCsrfTokenRepositoryTests {
MockHttpServletRequest request;
@BeforeEach
void setup() {
public void setup() {
this.repository = new CookieCsrfTokenRepository();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
@@ -51,7 +48,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void generateToken() {
public void generateToken() {
CsrfToken generateToken = this.repository.generateToken(this.request);
assertThat(generateToken).isNotNull();
assertThat(generateToken.getHeaderName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_HEADER_NAME);
@@ -60,7 +57,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void generateTokenCustom() {
public void generateTokenCustom() {
String headerName = "headerName";
String parameterName = "paramName";
this.repository.setHeaderName(headerName);
@@ -73,7 +70,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveToken() {
public void saveToken() {
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
@@ -82,11 +79,11 @@ class CookieCsrfTokenRepositoryTests {
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure());
assertThat(tokenCookie.getValue()).isEqualTo(token.getToken());
assertThat(tokenCookie.isHttpOnly()).isTrue();
assertThat(tokenCookie.isHttpOnly()).isEqualTo(true);
}
@Test
void saveTokenSecure() {
public void saveTokenSecure() {
this.request.setSecure(true);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
@@ -95,7 +92,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenSecureFlagTrue() {
public void saveTokenSecureFlagTrue() {
this.request.setSecure(false);
this.repository.setSecure(Boolean.TRUE);
CsrfToken token = this.repository.generateToken(this.request);
@@ -105,17 +102,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenSecureFlagTrueUsingCustomizer() {
this.request.setSecure(false);
this.repository.setCookieCustomizer((customizer) -> customizer.secure(Boolean.TRUE));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isTrue();
}
@Test
void saveTokenSecureFlagFalse() {
public void saveTokenSecureFlagFalse() {
this.request.setSecure(true);
this.repository.setSecure(Boolean.FALSE);
CsrfToken token = this.repository.generateToken(this.request);
@@ -125,17 +112,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenSecureFlagFalseUsingCustomizer() {
this.request.setSecure(true);
this.repository.setCookieCustomizer((customizer) -> customizer.secure(Boolean.FALSE));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isFalse();
}
@Test
void saveTokenNull() {
public void saveTokenNull() {
this.request.setSecure(true);
this.repository.saveToken(null, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
@@ -147,7 +124,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenHttpOnlyTrue() {
public void saveTokenHttpOnlyTrue() {
this.repository.setCookieHttpOnly(true);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
@@ -156,16 +133,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenHttpOnlyTrueUsingCustomizer() {
this.repository.setCookieCustomizer((customizer) -> customizer.httpOnly(true));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isTrue();
}
@Test
void saveTokenHttpOnlyFalse() {
public void saveTokenHttpOnlyFalse() {
this.repository.setCookieHttpOnly(false);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
@@ -174,16 +142,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenHttpOnlyFalseUsingCustomizer() {
this.repository.setCookieCustomizer((customizer) -> customizer.httpOnly(false));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isFalse();
}
@Test
void saveTokenWithHttpOnlyFalse() {
public void saveTokenWithHttpOnlyFalse() {
this.repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
@@ -192,7 +151,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenCustomPath() {
public void saveTokenCustomPath() {
String customPath = "/custompath";
this.repository.setCookiePath(customPath);
CsrfToken token = this.repository.generateToken(this.request);
@@ -202,7 +161,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenEmptyCustomPath() {
public void saveTokenEmptyCustomPath() {
String customPath = "";
this.repository.setCookiePath(customPath);
CsrfToken token = this.repository.generateToken(this.request);
@@ -212,7 +171,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenNullCustomPath() {
public void saveTokenNullCustomPath() {
String customPath = null;
this.repository.setCookiePath(customPath);
CsrfToken token = this.repository.generateToken(this.request);
@@ -222,7 +181,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenWithCookieDomain() {
public void saveTokenWithCookieDomain() {
String domainName = "example.com";
this.repository.setCookieDomain(domainName);
CsrfToken token = this.repository.generateToken(this.request);
@@ -232,17 +191,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenWithCookieDomainUsingCustomizer() {
String domainName = "example.com";
this.repository.setCookieCustomizer((customizer) -> customizer.domain(domainName));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getDomain()).isEqualTo(domainName);
}
@Test
void saveTokenWithCookieMaxAge() {
public void saveTokenWithCookieMaxAge() {
int maxAge = 1200;
this.repository.setCookieMaxAge(maxAge);
CsrfToken token = this.repository.generateToken(this.request);
@@ -252,75 +201,24 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void saveTokenWithCookieMaxAgeUsingCustomizer() {
int maxAge = 1200;
this.repository.setCookieCustomizer((customizer) -> customizer.maxAge(maxAge));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getMaxAge()).isEqualTo(maxAge);
}
@Test
void saveTokenWithSameSiteNull() {
String sameSitePolicy = null;
this.repository.setCookieCustomizer((customizer) -> customizer.sameSite(sameSitePolicy));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(((MockCookie) tokenCookie).getSameSite()).isNull();
}
@Test
void saveTokenWithSameSiteStrict() {
String sameSitePolicy = "Strict";
this.repository.setCookieCustomizer((customizer) -> customizer.sameSite(sameSitePolicy));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(((MockCookie) tokenCookie).getSameSite()).isEqualTo(sameSitePolicy);
}
@Test
void saveTokenWithSameSiteLax() {
String sameSitePolicy = "Lax";
this.repository.setCookieCustomizer((customizer) -> customizer.sameSite(sameSitePolicy));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(((MockCookie) tokenCookie).getSameSite()).isEqualTo(sameSitePolicy);
}
// gh-13075
@Test
void saveTokenWithExistingSetCookieThenDoesNotOverwrite() {
this.response.setHeader(HttpHeaders.SET_COOKIE, "MyCookie=test");
this.repository = new CookieCsrfTokenRepository();
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
assertThat(this.response.getCookie("MyCookie")).isNotNull();
assertThat(this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME)).isNotNull();
}
@Test
void loadTokenNoCookiesNull() {
public void loadTokenNoCookiesNull() {
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
void loadTokenCookieIncorrectNameNull() {
public void loadTokenCookieIncorrectNameNull() {
this.request.setCookies(new Cookie("other", "name"));
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
void loadTokenCookieValueEmptyString() {
public void loadTokenCookieValueEmptyString() {
this.request.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, ""));
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
void loadToken() {
public void loadToken() {
CsrfToken generateToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generateToken.getToken()));
@@ -332,7 +230,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void loadTokenCustom() {
public void loadTokenCustom() {
String cookieName = "cookieName";
String value = "value";
String headerName = "headerName";
@@ -349,7 +247,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void loadDeferredTokenWhenDoesNotExistThenGeneratedAndSaved() {
public void loadDeferredTokenWhenDoesNotExistThenGeneratedAndSaved() {
DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response);
CsrfToken csrfToken = deferredCsrfToken.get();
assertThat(csrfToken).isNotNull();
@@ -365,7 +263,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void loadDeferredTokenWhenExistsAndNullSavedThenGeneratedAndSaved() {
public void loadDeferredTokenWhenExistsAndNullSavedThenGeneratedAndSaved() {
CsrfToken generatedToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
@@ -378,7 +276,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void loadDeferredTokenWhenExistsAndNullSavedAndNonNullSavedThenLoaded() {
public void loadDeferredTokenWhenExistsAndNullSavedAndNonNullSavedThenLoaded() {
CsrfToken generatedToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
@@ -391,7 +289,7 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void loadDeferredTokenWhenExistsThenLoaded() {
public void loadDeferredTokenWhenExistsThenLoaded() {
CsrfToken generatedToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
@@ -402,57 +300,22 @@ class CookieCsrfTokenRepositoryTests {
}
@Test
void cookieCustomizer() {
String domainName = "example.com";
String customPath = "/custompath";
String sameSitePolicy = "Strict";
this.repository.setCookieCustomizer((customizer) -> {
customizer.domain(domainName);
customizer.secure(false);
customizer.path(customPath);
customizer.sameSite(sameSitePolicy);
});
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie).isNotNull();
assertThat(tokenCookie.getMaxAge()).isEqualTo(-1);
assertThat(tokenCookie.getDomain()).isEqualTo(domainName);
assertThat(tokenCookie.getPath()).isEqualTo(customPath);
assertThat(tokenCookie.isHttpOnly()).isEqualTo(Boolean.TRUE);
assertThat(((MockCookie) tokenCookie).getSameSite()).isEqualTo(sameSitePolicy);
}
// gh-13659
@Test
void withHttpOnlyFalseWhenCookieCustomizerThenStillDefaultsToFalse() {
CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
repository.setCookieCustomizer((customizer) -> customizer.maxAge(1000));
CsrfToken token = repository.generateToken(this.request);
repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie).isNotNull();
assertThat(tokenCookie.getMaxAge()).isEqualTo(1000);
assertThat(tokenCookie.isHttpOnly()).isEqualTo(Boolean.FALSE);
}
@Test
void setCookieNameNullIllegalArgumentException() {
public void setCookieNameNullIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCookieName(null));
}
@Test
void setParameterNameNullIllegalArgumentException() {
public void setParameterNameNullIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setParameterName(null));
}
@Test
void setHeaderNameNullIllegalArgumentException() {
public void setHeaderNameNullIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setHeaderName(null));
}
@Test
void setCookieMaxAgeZeroIllegalArgumentException() {
public void setCookieMaxAgeZeroIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCookieMaxAge(0));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -208,14 +208,6 @@ public class XorCsrfTokenRequestAttributeHandlerTests {
assertThat(tokenValue).isEqualTo(this.token.getToken());
}
@Test
public void resolveCsrfTokenIsInvalidThenReturnsNull() {
this.request.setParameter(this.token.getParameterName(), XOR_CSRF_TOKEN_VALUE);
CsrfToken csrfToken = new DefaultCsrfToken("headerName", "paramName", "a");
String tokenValue = this.handler.resolveCsrfTokenValue(this.request, csrfToken);
assertThat(tokenValue).isNull();
}
private static Answer<Void> fillByteArray() {
return (invocation) -> {
byte[] bytes = invocation.getArgument(0);

View File

@@ -47,7 +47,7 @@ public class CacheControlHeadersWriterTests {
@Test
public void writeHeaders() {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(3);
assertThat(this.response.getHeaderNames().size()).isEqualTo(3);
assertThat(this.response.getHeaderValues("Cache-Control"))
.containsOnly("no-cache, no-store, max-age=0, must-revalidate");
assertThat(this.response.getHeaderValues("Pragma")).containsOnly("no-cache");

View File

@@ -112,7 +112,7 @@ public class HstsHeaderWriterTests {
public void writeHeadersInsecureRequestDoesNotWriteHeader() {
this.request.setSecure(false);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).isEmpty();
assertThat(this.response.getHeaderNames().isEmpty()).isTrue();
}
@Test

View File

@@ -72,7 +72,7 @@ public class FrameOptionsHeaderWriterTests {
public void writeHeadersAllowFromReturnsNull() {
this.writer = new XFrameOptionsHeaderWriter(this.strategy);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).isEmpty();
assertThat(this.response.getHeaderNames().isEmpty()).isTrue();
}
@Test

View File

@@ -40,7 +40,7 @@ import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
@@ -131,7 +131,7 @@ public final class ResolvableMethod {
private static final SpringObjenesis objenesis = new SpringObjenesis();
private static final ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
private static final ParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
private final Method method;

View File

@@ -45,7 +45,7 @@ public class DefaultSavedRequestTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("If-None-Match", "somehashvalue");
DefaultSavedRequest saved = new DefaultSavedRequest(request, new MockPortResolver(8080, 8443));
assertThat(saved.getHeaderValues("if-none-match")).isEmpty();
assertThat(saved.getHeaderValues("if-none-match").isEmpty()).isTrue();
}
// SEC-3082

View File

@@ -24,7 +24,6 @@ import java.util.Locale;
import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.PortResolverImpl;
@@ -43,21 +42,22 @@ public class SavedRequestAwareWrapperTests {
@Test
public void savedRequestCookiesAreIgnored() {
MockHttpServletRequest newRequest = new MockHttpServletRequest();
newRequest.setCookies(new Cookie("cookie", "fromnew"));
newRequest.setCookies(new Cookie[] { new Cookie("cookie", "fromnew") });
MockHttpServletRequest savedRequest = new MockHttpServletRequest();
savedRequest.setCookies(new Cookie("cookie", "fromsaved"));
savedRequest.setCookies(new Cookie[] { new Cookie("cookie", "fromsaved") });
SavedRequestAwareWrapper wrapper = createWrapper(savedRequest, newRequest);
assertThat(wrapper.getCookies()).hasSize(1);
assertThat(wrapper.getCookies()[0].getValue()).isEqualTo("fromnew");
}
@Test
@SuppressWarnings("unchecked")
public void savedRequesthHeaderIsReturnedIfSavedRequestIsSet() {
MockHttpServletRequest savedRequest = new MockHttpServletRequest();
savedRequest.addHeader("header", "savedheader");
SavedRequestAwareWrapper wrapper = createWrapper(savedRequest, new MockHttpServletRequest());
assertThat(wrapper.getHeader("nonexistent")).isNull();
Enumeration<String> headers = wrapper.getHeaders("nonexistent");
Enumeration headers = wrapper.getHeaders("nonexistent");
assertThat(headers.hasMoreElements()).isFalse();
assertThat(wrapper.getHeader("Header")).isEqualTo("savedheader");
headers = wrapper.getHeaders("heaDer");
@@ -97,7 +97,7 @@ public class SavedRequestAwareWrapperTests {
SavedRequestAwareWrapper wrapper = createWrapper(savedRequest, wrappedRequest);
assertThat(wrapper.getParameterValues("action")).hasSize(1);
assertThat(wrapper.getParameterMap()).hasSize(1);
assertThat(wrapper.getParameterMap().get("action")).hasSize(1);
assertThat(((String[]) wrapper.getParameterMap().get("action"))).hasSize(1);
}
@Test
@@ -127,7 +127,7 @@ public class SavedRequestAwareWrapperTests {
wrappedRequest.setParameter("action", "bar");
assertThat(wrapper.getParameterValues("action")).isEqualTo(new Object[] { "bar", "foo" });
// Check map is consistent
String[] valuesFromMap = wrapper.getParameterMap().get("action");
String[] valuesFromMap = (String[]) wrapper.getParameterMap().get("action");
assertThat(valuesFromMap).hasSize(2);
assertThat(valuesFromMap[0]).isEqualTo("bar");
}
@@ -169,13 +169,4 @@ public class SavedRequestAwareWrapperTests {
assertThat(wrapper.getIntHeader("nonexistent")).isEqualTo(-1);
}
@Test
public void correctContentTypeIsReturned() {
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/notused");
request.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
SavedRequestAwareWrapper wrapper = createWrapper(request, new MockHttpServletRequest("GET", "/notused"));
assertThat(wrapper.getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,23 +17,17 @@
package org.springframework.security.web.server.context;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
import reactor.util.context.Context;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.core.Authentication;
@@ -125,32 +119,4 @@ public class ReactorContextWebFilterTests {
StepVerifier.create(filter).expectAccessibleContext().hasKey(contextKey).then().verifyComplete();
}
@Test
public void filterWhenThreadFactoryIsPlatformThenSecurityContextLoaded() {
ThreadFactory threadFactory = Executors.defaultThreadFactory();
assertSecurityContextLoaded(threadFactory);
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void filterWhenThreadFactoryIsVirtualThenSecurityContextLoaded() {
ThreadFactory threadFactory = new VirtualThreadTaskExecutor().getVirtualThreadFactory();
assertSecurityContextLoaded(threadFactory);
}
private void assertSecurityContextLoaded(ThreadFactory threadFactory) {
SecurityContextImpl context = new SecurityContextImpl(this.principal);
given(this.repository.load(any())).willReturn(Mono.just(context));
// @formatter:off
WebFilter subscribeOnThreadFactory = (exchange, chain) -> chain.filter(exchange)
.subscribeOn(Schedulers.newSingle(threadFactory));
WebFilter assertSecurityContext = (exchange, chain) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.doOnSuccess((authentication) -> assertThat(authentication).isSameAs(this.principal))
.then(chain.filter(exchange));
// @formatter:on
this.handler = WebTestHandler.bindToWebFilters(subscribeOnThreadFactory, this.filter, assertSecurityContext);
this.handler.exchange(this.exchange);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,25 +17,17 @@
package org.springframework.security.web.server.context;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.test.web.reactive.server.WebTestHandler;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.handler.DefaultWebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
@@ -88,31 +80,4 @@ public class SecurityContextServerWebExchangeWebFilterTests {
StepVerifier.create(result).verifyComplete();
}
@Test
public void filterWhenThreadFactoryIsPlatformThenContextPopulated() {
ThreadFactory threadFactory = Executors.defaultThreadFactory();
assertPrincipalPopulated(threadFactory);
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void filterWhenThreadFactoryIsVirtualThenContextPopulated() {
ThreadFactory threadFactory = new VirtualThreadTaskExecutor().getVirtualThreadFactory();
assertPrincipalPopulated(threadFactory);
}
private void assertPrincipalPopulated(ThreadFactory threadFactory) {
// @formatter:off
WebFilter subscribeOnThreadFactory = (exchange, chain) -> chain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.principal))
.subscribeOn(Schedulers.newSingle(threadFactory));
WebFilter assertPrincipal = (exchange, chain) -> exchange.getPrincipal()
.doOnSuccess((principal) -> assertThat(principal).isSameAs(this.principal))
.then(chain.filter(exchange));
// @formatter:on
WebTestHandler handler = WebTestHandler.bindToWebFilters(subscribeOnThreadFactory, this.filter,
assertPrincipal);
handler.exchange(this.exchange);
}
}

View File

@@ -18,7 +18,6 @@ package org.springframework.security.web.server.csrf;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -36,10 +35,9 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Eric Deandrea
* @author Thomas Vitale
* @author Alonso Araya
* @author Alex Montoya
* @since 5.1
*/
class CookieServerCsrfTokenRepositoryTests {
public class CookieServerCsrfTokenRepositoryTests {
private CookieServerCsrfTokenRepository csrfTokenRepository;
@@ -63,122 +61,78 @@ class CookieServerCsrfTokenRepositoryTests {
private String expectedCookieValue = "csrfToken";
private String expectedSameSitePolicy = null;
@BeforeEach
void setUp() {
public void setUp() {
this.csrfTokenRepository = new CookieServerCsrfTokenRepository();
this.request = MockServerHttpRequest.get("/someUri");
}
@Test
void generateTokenWhenDefaultThenDefaults() {
public void generateTokenWhenDefaultThenDefaults() {
generateTokenAndAssertExpectedValues();
}
@Test
void generateTokenWhenCustomHeaderThenCustomHeader() {
public void generateTokenWhenCustomHeaderThenCustomHeader() {
setExpectedHeaderName("someHeader");
generateTokenAndAssertExpectedValues();
}
@Test
void generateTokenWhenCustomParameterThenCustomParameter() {
public void generateTokenWhenCustomParameterThenCustomParameter() {
setExpectedParameterName("someParam");
generateTokenAndAssertExpectedValues();
}
@Test
void generateTokenWhenCustomHeaderAndParameterThenCustomHeaderAndParameter() {
public void generateTokenWhenCustomHeaderAndParameterThenCustomHeaderAndParameter() {
setExpectedHeaderName("someHeader");
setExpectedParameterName("someParam");
generateTokenAndAssertExpectedValues();
}
@Test
void saveTokenWhenNoSubscriptionThenNotWritten() {
public void saveTokenWhenNoSubscriptionThenNotWritten() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.saveToken(exchange, createToken());
assertThat(exchange.getResponse().getCookies().getFirst(this.expectedCookieName)).isNull();
}
@Test
void saveTokenWhenDefaultThenDefaults() {
public void saveTokenWhenDefaultThenDefaults() {
saveAndAssertExpectedValues(createToken());
}
@Test
void saveTokenWhenNullThenDeletes() {
public void saveTokenWhenNullThenDeletes() {
saveAndAssertExpectedValues(null);
}
@Test
void saveTokenWhenHttpOnlyFalseThenHttpOnlyFalse() {
public void saveTokenWhenHttpOnlyFalseThenHttpOnlyFalse() {
setExpectedHttpOnly(false);
saveAndAssertExpectedValues(createToken());
}
@Test
void saveTokenWhenCookieMaxAgeThenCookieMaxAge() {
public void saveTokenWhenCookieMaxAgeThenCookieMaxAge() {
setExpectedCookieMaxAge(3600);
saveAndAssertExpectedValues(createToken());
}
@Test
void saveTokenWhenSameSiteThenCookieSameSite() {
setExpectedSameSitePolicy("Lax");
saveAndAssertExpectedValues(createToken());
}
@Test
void saveTokenWhenCustomPropertiesThenCustomProperties() {
public void saveTokenWhenCustomPropertiesThenCustomProperties() {
setExpectedDomain("spring.io");
setExpectedCookieName("csrfCookie");
setExpectedPath("/some/path");
setExpectedHeaderName("headerName");
setExpectedParameterName("paramName");
setExpectedSameSitePolicy("Strict");
setExpectedCookieMaxAge(3600);
saveAndAssertExpectedValues(createToken());
}
@Test
void saveTokenWhenCustomPropertiesThenCustomPropertiesUsingCustomizer() {
String expectedDomain = "spring.io";
int expectedMaxAge = 3600;
String expectedPath = "/some/path";
String expectedSameSite = "Strict";
setExpectedCookieName("csrfCookie");
setExpectedHeaderName("headerName");
setExpectedParameterName("paramName");
CsrfToken token = createToken();
this.csrfTokenRepository.setCookieCustomizer((customizer) -> {
customizer.domain(expectedDomain);
customizer.maxAge(expectedMaxAge);
customizer.path(expectedPath);
customizer.sameSite(expectedSameSite);
});
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.saveToken(exchange, token).block();
ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName);
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(Duration.of(expectedMaxAge, ChronoUnit.SECONDS));
assertThat(cookie.getDomain()).isEqualTo(expectedDomain);
assertThat(cookie.getPath()).isEqualTo(expectedPath);
assertThat(cookie.getSameSite()).isEqualTo(expectedSameSite);
assertThat(cookie.isSecure()).isEqualTo(this.expectedSecure);
assertThat(cookie.isHttpOnly()).isEqualTo(this.expectedHttpOnly);
assertThat(cookie.getName()).isEqualTo(this.expectedCookieName);
assertThat(cookie.getValue()).isEqualTo(this.expectedCookieValue);
}
@Test
void saveTokenWhenSslInfoPresentThenSecure() {
public void saveTokenWhenSslInfoPresentThenSecure() {
this.request.sslInfo(new MockSslInfo());
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.saveToken(exchange, createToken()).block();
@@ -188,7 +142,7 @@ class CookieServerCsrfTokenRepositoryTests {
}
@Test
void saveTokenWhenSslInfoNullThenNotSecure() {
public void saveTokenWhenSslInfoNullThenNotSecure() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.saveToken(exchange, createToken()).block();
ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName);
@@ -197,7 +151,7 @@ class CookieServerCsrfTokenRepositoryTests {
}
@Test
void saveTokenWhenSecureFlagTrueThenSecure() {
public void saveTokenWhenSecureFlagTrueThenSecure() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.setSecure(true);
this.csrfTokenRepository.saveToken(exchange, createToken()).block();
@@ -207,17 +161,7 @@ class CookieServerCsrfTokenRepositoryTests {
}
@Test
void saveTokenWhenSecureFlagTrueThenSecureUsingCustomizer() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.secure(true));
this.csrfTokenRepository.saveToken(exchange, createToken()).block();
ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName);
assertThat(cookie).isNotNull();
assertThat(cookie.isSecure()).isTrue();
}
@Test
void saveTokenWhenSecureFlagFalseThenNotSecure() {
public void saveTokenWhenSecureFlagFalseThenNotSecure() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.setSecure(false);
this.csrfTokenRepository.saveToken(exchange, createToken()).block();
@@ -227,17 +171,7 @@ class CookieServerCsrfTokenRepositoryTests {
}
@Test
void saveTokenWhenSecureFlagFalseThenNotSecureUsingCustomizer() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.secure(false));
this.csrfTokenRepository.saveToken(exchange, createToken()).block();
ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName);
assertThat(cookie).isNotNull();
assertThat(cookie.isSecure()).isFalse();
}
@Test
void saveTokenWhenSecureFlagFalseAndSslInfoThenNotSecure() {
public void saveTokenWhenSecureFlagFalseAndSslInfoThenNotSecure() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.request.sslInfo(new MockSslInfo());
this.csrfTokenRepository.setSecure(false);
@@ -248,23 +182,12 @@ class CookieServerCsrfTokenRepositoryTests {
}
@Test
void saveTokenWhenSecureFlagFalseAndSslInfoThenNotSecureUsingCustomizer() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
this.request.sslInfo(new MockSslInfo());
this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.secure(false));
this.csrfTokenRepository.saveToken(exchange, createToken()).block();
ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName);
assertThat(cookie).isNotNull();
assertThat(cookie.isSecure()).isFalse();
}
@Test
void loadTokenWhenCookieExistThenTokenFound() {
public void loadTokenWhenCookieExistThenTokenFound() {
loadAndAssertExpectedValues();
}
@Test
void loadTokenWhenCustomThenTokenFound() {
public void loadTokenWhenCustomThenTokenFound() {
setExpectedParameterName("paramName");
setExpectedHeaderName("headerName");
setExpectedCookieName("csrfCookie");
@@ -272,20 +195,20 @@ class CookieServerCsrfTokenRepositoryTests {
}
@Test
void loadTokenWhenNoCookiesThenNullToken() {
public void loadTokenWhenNoCookiesThenNullToken() {
MockServerWebExchange exchange = MockServerWebExchange.from(this.request);
CsrfToken csrfToken = this.csrfTokenRepository.loadToken(exchange).block();
assertThat(csrfToken).isNull();
}
@Test
void loadTokenWhenCookieExistsWithNoValue() {
public void loadTokenWhenCookieExistsWithNoValue() {
setExpectedCookieValue("");
loadAndAssertExpectedValues();
}
@Test
void loadTokenWhenCookieExistsWithNullValue() {
public void loadTokenWhenCookieExistsWithNullValue() {
setExpectedCookieValue(null);
loadAndAssertExpectedValues();
}
@@ -325,11 +248,6 @@ class CookieServerCsrfTokenRepositoryTests {
this.expectedMaxAge = Duration.ofSeconds(expectedCookieMaxAge);
}
private void setExpectedSameSitePolicy(String sameSitePolicy) {
this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.sameSite(sameSitePolicy));
this.expectedSameSitePolicy = sameSitePolicy;
}
private void setExpectedCookieValue(String expectedCookieValue) {
this.expectedCookieValue = expectedCookieValue;
}
@@ -366,7 +284,6 @@ class CookieServerCsrfTokenRepositoryTests {
assertThat(cookie.isHttpOnly()).isEqualTo(this.expectedHttpOnly);
assertThat(cookie.getName()).isEqualTo(this.expectedCookieName);
assertThat(cookie.getValue()).isEqualTo(this.expectedCookieValue);
assertThat(cookie.getSameSite()).isEqualTo(this.expectedSameSitePolicy);
}
private void generateTokenAndAssertExpectedValues() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -188,18 +188,6 @@ public class XorServerCsrfTokenRequestAttributeHandlerTests {
StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete();
}
@Test
public void resolveCsrfTokenIsInvalidThenReturnsNull() {
this.exchange = MockServerWebExchange
.builder(MockServerHttpRequest.post("/")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.body(this.token.getParameterName() + "=" + XOR_CSRF_TOKEN_VALUE))
.build();
CsrfToken token = new DefaultCsrfToken("headerName", "paramName", "a");
Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, token);
assertThat(csrfToken.block()).isNull();
}
private static Answer<Void> fillByteArray() {
return (invocation) -> {
byte[] bytes = invocation.getArgument(0);

View File

@@ -46,7 +46,7 @@ public class CookieServerRequestCacheTests {
.from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML));
this.cache.saveRequest(exchange).block();
MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
assertThat(cookies).hasSize(1);
assertThat(cookies.size()).isEqualTo(1);
ResponseCookie cookie = cookies.getFirst("REDIRECT_URI");
assertThat(cookie).isNotNull();
String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/".getBytes());
@@ -60,7 +60,7 @@ public class CookieServerRequestCacheTests {
.from(MockServerHttpRequest.get("/secured/").queryParam("key", "value").accept(MediaType.TEXT_HTML));
this.cache.saveRequest(exchange).block();
MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
assertThat(cookies).hasSize(1);
assertThat(cookies.size()).isEqualTo(1);
ResponseCookie cookie = cookies.getFirst("REDIRECT_URI");
assertThat(cookie).isNotNull();
String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/?key=value".getBytes());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,10 +20,8 @@ import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -31,7 +29,6 @@ import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@@ -49,11 +46,9 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* @author Luke Taylor
* @author Rob Winch
* @author Mark Chesney
*/
public class SessionManagementFilterTests {
@BeforeEach
@AfterEach
public void clearContext() {
SecurityContextHolder.clearContext();
@@ -179,69 +174,6 @@ public class SessionManagementFilterTests {
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
}
@Test
public void responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setContextRelative(true);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository,
sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/context/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
// when
filter.doFilter(request, response, chain);
// then
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
}
@Test
public void responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid() throws Exception {
// given
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository,
sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
// when
filter.doFilter(request, response, chain);
// then
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}
@Test
public void customAuthenticationTrustResolver() throws Exception {
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,7 +62,7 @@ public class TextEscapeUtilsTests {
@Test
public void undefinedSurrogatePairIsIgnored() {
assertThat(TextEscapeUtils.escapeEntities("abc\uDBFF\uDFFFa")).isEqualTo("abca");
assertThat(TextEscapeUtils.escapeEntities("abc\uD888\uDC00a")).isEqualTo("abca");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.springframework.security.web.util.matcher;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
@@ -27,8 +26,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.web.util.matcher.RequestMatcher.MatchResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
@@ -126,30 +123,4 @@ public class AndRequestMatcherTests {
assertThat(this.matcher.matches(this.request)).isFalse();
}
@Test
public void matcherWhenMatchersHavePlaceholdersThenPropagatesMatches() {
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "othervalue")));
MatchResult result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "othervalue"));
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.notMatch());
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).isEmpty();
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("otherparam", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables())
.containsExactlyInAnyOrderEntriesOf(Map.of("otherparam", "value", "param", "value"));
}
}

View File

@@ -88,7 +88,7 @@ public class MediaTypeRequestMatcherTests {
@Test
public void constructorWhenEmptyMediaTypeThenIAE() {
assertThatIllegalArgumentException().isThrownBy(MediaTypeRequestMatcher::new);
assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeRequestMatcher());
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.springframework.security.web.util.matcher;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
@@ -27,13 +26,10 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.web.util.matcher.RequestMatcher.MatchResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* @author Rob Winch
@@ -126,26 +122,4 @@ public class OrRequestMatcherTests {
assertThat(this.matcher.matches(this.request)).isTrue();
}
@Test
public void matcherWhenMatchersHavePlaceholdersThenPropagatesFirstMatch() {
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "othervalue")));
MatchResult result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
verifyNoInteractions(this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).isEmpty();
verifyNoInteractions(this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.notMatch());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
}
}

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.util.matcher;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link RequestMatchers}.
*
* @author Christian Schuster
*/
class RequestMatchersTests {
@Test
void checkAnyOfWhenOneMatchThenMatch() {
RequestMatcher composed = RequestMatchers.anyOf((r) -> false, (r) -> true);
boolean match = composed.matches(null);
assertThat(match).isTrue();
}
@Test
void checkAnyOfWhenNoneMatchThenNotMatch() {
RequestMatcher composed = RequestMatchers.anyOf((r) -> false, (r) -> false);
boolean match = composed.matches(null);
assertThat(match).isFalse();
}
@Test
void checkAnyOfWhenEmptyThenNotMatch() {
RequestMatcher composed = RequestMatchers.anyOf();
boolean match = composed.matches(null);
assertThat(match).isFalse();
}
@Test
void checkAllOfWhenOneNotMatchThenNotMatch() {
RequestMatcher composed = RequestMatchers.allOf((r) -> false, (r) -> true);
boolean match = composed.matches(null);
assertThat(match).isFalse();
}
@Test
void checkAllOfWhenAllMatchThenMatch() {
RequestMatcher composed = RequestMatchers.allOf((r) -> true, (r) -> true);
boolean match = composed.matches(null);
assertThat(match).isTrue();
}
@Test
void checkAllOfWhenEmptyThenMatch() {
RequestMatcher composed = RequestMatchers.allOf();
boolean match = composed.matches(null);
assertThat(match).isTrue();
}
@Test
void checkNotWhenMatchThenNotMatch() {
RequestMatcher composed = RequestMatchers.not((r) -> true);
boolean match = composed.matches(null);
assertThat(match).isFalse();
}
@Test
void checkNotWhenNotMatchThenMatch() {
RequestMatcher composed = RequestMatchers.not((r) -> false);
boolean match = composed.matches(null);
assertThat(match).isTrue();
}
}