repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java
/* * Copyright 2002-2021 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.reactive.result.method.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.expression.BeanResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class AuthenticationPrincipalArgumentResolverTests { @Mock ServerWebExchange exchange; @Mock BindingContext bindingContext; @Mock Authentication authentication; @Mock BeanResolver beanResolver; ResolvableMethod authenticationPrincipal = ResolvableMethod.on(getClass()).named("authenticationPrincipal").build(); ResolvableMethod spel = ResolvableMethod.on(getClass()).named("spel").build(); ResolvableMethod spelPrimitive = ResolvableMethod.on(getClass()).named("spelPrimitive").build(); ResolvableMethod meta = ResolvableMethod.on(getClass()).named("meta").build(); ResolvableMethod bean = ResolvableMethod.on(getClass()).named("bean").build(); AuthenticationPrincipalArgumentResolver resolver; @BeforeEach public void setup() { this.resolver = new AuthenticationPrincipalArgumentResolver(new ReactiveAdapterRegistry()); this.resolver.setBeanResolver(this.beanResolver); } @Test public void supportsParameterAuthenticationPrincipal() { assertThat(this.resolver.supportsParameter(this.authenticationPrincipal.arg(String.class))).isTrue(); } @Test public void supportsParameterCurrentUser() { assertThat(this.resolver.supportsParameter(this.meta.arg(String.class))).isTrue(); } @Test public void resolveArgumentWhenIsAuthenticationThenObtainsPrincipal() { MethodParameter parameter = this.authenticationPrincipal.arg(String.class); given(this.authentication.getPrincipal()).willReturn("user"); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.block()).isEqualTo(this.authentication.getPrincipal()); } @Test public void resolveArgumentWhenIsEmptyThenMonoEmpty() { MethodParameter parameter = this.authenticationPrincipal.arg(String.class); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); assertThat(argument).isNotNull(); assertThat(argument.block()).isNull(); } @Test public void resolveArgumentWhenMonoIsAuthenticationThenObtainsPrincipal() { MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class); given(this.authentication.getPrincipal()).willReturn("user"); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.cast(Mono.class).block().block()).isEqualTo(this.authentication.getPrincipal()); } @Test public void resolveArgumentWhenMonoIsAuthenticationAndNoGenericThenObtainsPrincipal() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("authenticationPrincipalNoGeneric").build() .arg(Mono.class); given(this.authentication.getPrincipal()).willReturn("user"); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.cast(Mono.class).block().block()).isEqualTo(this.authentication.getPrincipal()); } @Test public void resolveArgumentWhenSpelThenObtainsPrincipal() { MyUser user = new MyUser(3L); MethodParameter parameter = this.spel.arg(Long.class); given(this.authentication.getPrincipal()).willReturn(user); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.block()).isEqualTo(user.getId()); } @Test public void resolveArgumentWhenSpelWithPrimitiveThenObtainsPrincipal() { MyUserPrimitive user = new MyUserPrimitive(3); MethodParameter parameter = this.spelPrimitive.arg(int.class); given(this.authentication.getPrincipal()).willReturn(user); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.block()).isEqualTo(user.getId()); } @Test public void resolveArgumentWhenBeanThenObtainsPrincipal() throws Exception { MyUser user = new MyUser(3L); MethodParameter parameter = this.bean.arg(Long.class); given(this.authentication.getPrincipal()).willReturn(user); given(this.beanResolver.resolve(any(), eq("beanName"))).willReturn(new Bean()); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.block()).isEqualTo(user.getId()); } @Test public void resolveArgumentWhenMetaThenObtainsPrincipal() { MethodParameter parameter = this.meta.arg(String.class); given(this.authentication.getPrincipal()).willReturn("user"); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.block()).isEqualTo("user"); } @Test public void resolveArgumentWhenErrorOnInvalidTypeImplicit() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenImplicit").build() .arg(Integer.class); given(this.authentication.getPrincipal()).willReturn("user"); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.block()).isNull(); } @Test public void resolveArgumentWhenErrorOnInvalidTypeExplicitFalse() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build() .arg(Integer.class); given(this.authentication.getPrincipal()).willReturn("user"); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThat(argument.block()).isNull(); } @Test public void resolveArgumentWhenErrorOnInvalidTypeExplicitTrue() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitTrue").build() .arg(Integer.class); given(this.authentication.getPrincipal()).willReturn("user"); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> argument.block()); } void authenticationPrincipal(@AuthenticationPrincipal String principal, @AuthenticationPrincipal Mono<String> monoPrincipal) { } void authenticationPrincipalNoGeneric(@AuthenticationPrincipal Mono monoPrincipal) { } void spel(@AuthenticationPrincipal(expression = "id") Long id) { } void spelPrimitive(@AuthenticationPrincipal(expression = "id") int id) { } void bean(@AuthenticationPrincipal(expression = "@beanName.methodName(#this)") Long id) { } void meta(@CurrentUser String principal) { } void errorOnInvalidTypeWhenImplicit(@AuthenticationPrincipal Integer implicit) { } void errorOnInvalidTypeWhenExplicitFalse(@AuthenticationPrincipal(errorOnInvalidType = false) Integer implicit) { } void errorOnInvalidTypeWhenExplicitTrue(@AuthenticationPrincipal(errorOnInvalidType = true) Integer implicit) { } static class Bean { public Long methodName(MyUser user) { return user.getId(); } } static class MyUser { private final Long id; MyUser(Long id) { this.id = id; } public Long getId() { return this.id; } } static class MyUserPrimitive { private final int id; MyUserPrimitive(int id) { this.id = id; } public int getId() { return this.id; } } @Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @AuthenticationPrincipal public @interface CurrentUser { } }
10,223
36.313869
117
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolverTests.java
/* * Copyright 2002-2019 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.reactive.result.method.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.util.context.Context; import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.expression.BeanResolver; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.CurrentSecurityContext; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Dan Zheng * @since 5.2 */ @ExtendWith(MockitoExtension.class) public class CurrentSecurityContextArgumentResolverTests { @Mock ServerWebExchange exchange; @Mock BindingContext bindingContext; @Mock Authentication authentication; @Mock BeanResolver beanResolver; @Mock SecurityContext securityContext; ResolvableMethod securityContextMethod = ResolvableMethod.on(getClass()).named("securityContext").build(); ResolvableMethod securityContextWithAuthentication = ResolvableMethod.on(getClass()) .named("securityContextWithAuthentication").build(); CurrentSecurityContextArgumentResolver resolver; @BeforeEach public void setup() { this.resolver = new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry()); this.resolver.setBeanResolver(this.beanResolver); } @Test public void supportsParameterCurrentSecurityContext() { assertThat(this.resolver.supportsParameter(this.securityContextMethod.arg(Mono.class, SecurityContext.class))) .isTrue(); } @Test public void supportsParameterWithAuthentication() { assertThat(this.resolver .supportsParameter(this.securityContextWithAuthentication.arg(Mono.class, Authentication.class))) .isTrue(); } @Test public void resolveArgumentWithNullSecurityContext() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContext").build().arg(Mono.class, SecurityContext.class); Context context = ReactiveSecurityContextHolder.withSecurityContext(Mono.empty()); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Object obj = argument.contextWrite(context).block(); assertThat(obj).isNull(); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithSecurityContext() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContext").build().arg(Mono.class, SecurityContext.class); Authentication auth = buildAuthenticationWithPrincipal("hello"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); SecurityContext securityContext = (SecurityContext) argument.contextWrite(context).cast(Mono.class).block() .block(); assertThat(securityContext.getAuthentication()).isSameAs(auth); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithCustomSecurityContext() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("customSecurityContext").build() .arg(Mono.class, SecurityContext.class); Authentication auth = buildAuthenticationWithPrincipal("hello"); Context context = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(new CustomSecurityContext(auth))); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); CustomSecurityContext securityContext = (CustomSecurityContext) argument.contextWrite(context).cast(Mono.class) .block().block(); assertThat(securityContext.getAuthentication()).isSameAs(auth); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithNullAuthentication1() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContext").build().arg(Mono.class, SecurityContext.class); Authentication auth = null; Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); SecurityContext securityContext = (SecurityContext) argument.contextWrite(context).cast(Mono.class).block() .block(); assertThat(securityContext.getAuthentication()).isNull(); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithNullAuthentication2() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContextWithAuthentication").build() .arg(Mono.class, Authentication.class); Authentication auth = null; Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Mono<Object> r = (Mono<Object>) argument.contextWrite(context).block(); assertThat(r.block()).isNull(); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithAuthentication1() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContextWithAuthentication").build() .arg(Mono.class, Authentication.class); Authentication auth = buildAuthenticationWithPrincipal("authentication1"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Mono<Authentication> auth1 = (Mono<Authentication>) argument.contextWrite(context).block(); assertThat(auth1.block()).isSameAs(auth); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithNullAuthenticationOptional1() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContextWithDepthPropOptional") .build().arg(Mono.class, Object.class); Authentication auth = null; Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Mono<Object> obj = (Mono<Object>) argument.contextWrite(context).block(); assertThat(obj.block()).isNull(); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithAuthenticationOptional1() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContextWithDepthPropOptional") .build().arg(Mono.class, Object.class); Authentication auth = buildAuthenticationWithPrincipal("auth_optional"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Mono<Object> obj = (Mono<Object>) argument.contextWrite(context).block(); assertThat(obj.block()).isEqualTo("auth_optional"); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithNullDepthProp1() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContextWithDepthProp").build() .arg(Mono.class, Object.class); Authentication auth = null; Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); assertThatExceptionOfType(SpelEvaluationException.class) .isThrownBy(() -> argument.contextWrite(context).block()); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWithStringDepthProp() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContextWithDepthStringProp").build() .arg(Mono.class, String.class); Authentication auth = buildAuthenticationWithPrincipal("auth_string"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Mono<String> obj = (Mono<String>) argument.contextWrite(context).block(); assertThat(obj.block()).isEqualTo("auth_string"); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentWhenErrorOnInvalidTypeImplicit() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenImplicit").build() .arg(Mono.class, String.class); Authentication auth = buildAuthenticationWithPrincipal("invalid_type_implicit"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Mono<String> obj = (Mono<String>) argument.contextWrite(context).block(); assertThat(obj.block()).isNull(); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentErrorOnInvalidTypeWhenExplicitFalse() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build() .arg(Mono.class, String.class); Authentication auth = buildAuthenticationWithPrincipal("error_on_invalid_type_explicit_false"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Mono<String> obj = (Mono<String>) argument.contextWrite(context).block(); assertThat(obj.block()).isNull(); ReactiveSecurityContextHolder.clearContext(); } @Test public void resolveArgumentErrorOnInvalidTypeWhenExplicitTrue() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitTrue").build() .arg(Mono.class, String.class); Authentication auth = buildAuthenticationWithPrincipal("error_on_invalid_type_explicit_true"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> argument.contextWrite(context).block()); ReactiveSecurityContextHolder.clearContext(); } @Test public void metaAnnotationWhenDefaultSecurityContextThenInjectSecurityContext() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("currentCustomSecurityContext").build() .arg(Mono.class, SecurityContext.class); Authentication auth = buildAuthenticationWithPrincipal("current_custom_security_context"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); SecurityContext securityContext = (SecurityContext) argument.contextWrite(context).cast(Mono.class).block() .block(); assertThat(securityContext.getAuthentication()).isSameAs(auth); ReactiveSecurityContextHolder.clearContext(); } @Test public void metaAnnotationWhenCurrentAuthenticationThenInjectAuthentication() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("currentAuthentication").build() .arg(Mono.class, Authentication.class); Authentication auth = buildAuthenticationWithPrincipal("current_authentication"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); Authentication authentication = (Authentication) argument.contextWrite(context).cast(Mono.class).block() .block(); assertThat(authentication).isSameAs(auth); ReactiveSecurityContextHolder.clearContext(); } @Test public void metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenInjectSecurityContext() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("currentSecurityWithErrorOnInvalidType") .build().arg(Mono.class, SecurityContext.class); Authentication auth = buildAuthenticationWithPrincipal("current_security_with_error_on_invalid_type"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); SecurityContext securityContext = (SecurityContext) argument.contextWrite(context).cast(Mono.class).block() .block(); assertThat(securityContext.getAuthentication()).isSameAs(auth); ReactiveSecurityContextHolder.clearContext(); } @Test public void metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenMisMatch() { MethodParameter parameter = ResolvableMethod.on(getClass()) .named("currentSecurityWithErrorOnInvalidTypeMisMatch").build().arg(Mono.class, String.class); Authentication auth = buildAuthenticationWithPrincipal("current_security_with_error_on_invalid_type_mismatch"); Context context = ReactiveSecurityContextHolder.withAuthentication(auth); Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange); assertThatExceptionOfType(ClassCastException.class) .isThrownBy(() -> argument.contextWrite(context).cast(Mono.class).block().block()); ReactiveSecurityContextHolder.clearContext(); } void securityContext(@CurrentSecurityContext Mono<SecurityContext> monoSecurityContext) { } void customSecurityContext(@CurrentSecurityContext Mono<SecurityContext> monoSecurityContext) { } void securityContextWithAuthentication( @CurrentSecurityContext(expression = "authentication") Mono<Authentication> authentication) { } void securityContextWithDepthPropOptional( @CurrentSecurityContext(expression = "authentication?.principal") Mono<Object> principal) { } void securityContextWithDepthProp( @CurrentSecurityContext(expression = "authentication.principal") Mono<Object> principal) { } void securityContextWithDepthStringProp( @CurrentSecurityContext(expression = "authentication.principal") Mono<String> principal) { } void errorOnInvalidTypeWhenImplicit(@CurrentSecurityContext Mono<String> implicit) { } void errorOnInvalidTypeWhenExplicitFalse( @CurrentSecurityContext(errorOnInvalidType = false) Mono<String> implicit) { } void errorOnInvalidTypeWhenExplicitTrue(@CurrentSecurityContext(errorOnInvalidType = true) Mono<String> implicit) { } void currentCustomSecurityContext(@CurrentCustomSecurityContext Mono<SecurityContext> monoSecurityContext) { } void currentAuthentication(@CurrentAuthentication Mono<Authentication> authentication) { } void currentSecurityWithErrorOnInvalidType( @CurrentSecurityWithErrorOnInvalidType Mono<SecurityContext> monoSecurityContext) { } void currentSecurityWithErrorOnInvalidTypeMisMatch( @CurrentSecurityWithErrorOnInvalidType Mono<String> typeMisMatch) { } private Authentication buildAuthenticationWithPrincipal(Object principal) { return new TestingAuthenticationToken(principal, "password", "ROLE_USER"); } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @CurrentSecurityContext @interface CurrentCustomSecurityContext { } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @CurrentSecurityContext(expression = "authentication") @interface CurrentAuthentication { } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @CurrentSecurityContext(errorOnInvalidType = true) @interface CurrentSecurityWithErrorOnInvalidType { } static class CustomSecurityContext implements SecurityContext { private Authentication authentication; CustomSecurityContext(Authentication authentication) { this.authentication = authentication; } @Override public Authentication getAuthentication() { return this.authentication; } @Override public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } }
17,247
42.555556
116
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessorTests.java
/* * 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. * 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.reactive.result.view; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.web.server.csrf.CsrfToken; import org.springframework.security.web.server.csrf.DefaultCsrfToken; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ public class CsrfRequestDataValueProcessorTests { private MockServerWebExchange exchange = exchange(HttpMethod.GET); private CsrfRequestDataValueProcessor processor = new CsrfRequestDataValueProcessor(); private CsrfToken token = new DefaultCsrfToken("1", "a", "b"); private Map<String, String> expected = new HashMap<>(); @BeforeEach public void setup() { this.expected.put(this.token.getParameterName(), this.token.getToken()); this.exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, this.token); } @Test public void assertAllMethodsDeclared() { Method[] expectedMethods = ReflectionUtils.getAllDeclaredMethods(CsrfRequestDataValueProcessor.class); for (Method expected : expectedMethods) { assertThat(ReflectionUtils.findMethod(CsrfRequestDataValueProcessor.class, expected.getName(), expected.getParameterTypes())) .as("Expected to find " + expected + " defined on " + CsrfRequestDataValueProcessor.class) .isNotNull(); } } @Test public void getExtraHiddenFieldsNoCsrfToken() { this.exchange.getAttributes().clear(); assertThat(this.processor.getExtraHiddenFields(this.exchange)).isEmpty(); } @Test public void getExtraHiddenFieldsHasCsrfTokenNoMethodSet() { assertThat(this.processor.getExtraHiddenFields(this.exchange)).isEqualTo(this.expected); } @Test public void getExtraHiddenFieldsHasCsrfToken_GET() { this.processor.processAction(this.exchange, "action", "GET"); assertThat(this.processor.getExtraHiddenFields(this.exchange)).isEmpty(); } @Test public void getExtraHiddenFieldsHasCsrfToken_get() { this.processor.processAction(this.exchange, "action", "get"); assertThat(this.processor.getExtraHiddenFields(this.exchange)).isEmpty(); } @Test public void getExtraHiddenFieldsHasCsrfToken_POST() { this.processor.processAction(this.exchange, "action", "POST"); assertThat(this.processor.getExtraHiddenFields(this.exchange)).isEqualTo(this.expected); } @Test public void getExtraHiddenFieldsHasCsrfToken_post() { this.processor.processAction(this.exchange, "action", "post"); assertThat(this.processor.getExtraHiddenFields(this.exchange)).isEqualTo(this.expected); } @Test public void processActionWithMethodArg() { String action = "action"; assertThat(this.processor.processAction(this.exchange, action, null)).isEqualTo(action); } @Test public void processFormFieldValue() { String value = "action"; assertThat(this.processor.processFormFieldValue(this.exchange, "name", value, "hidden")).isEqualTo(value); } @Test public void processUrl() { String url = "url"; assertThat(this.processor.processUrl(this.exchange, url)).isEqualTo(url); } @Test public void createGetExtraHiddenFieldsHasCsrfToken() { CsrfToken token = new DefaultCsrfToken("1", "a", "b"); this.exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token); Map<String, String> expected = new HashMap<>(); expected.put(token.getParameterName(), token.getToken()); CsrfRequestDataValueProcessor processor = new CsrfRequestDataValueProcessor(); assertThat(this.processor.getExtraHiddenFields(this.exchange)).isEqualTo(expected); } private MockServerWebExchange exchange(HttpMethod method) { return MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "/")); } }
4,671
33.865672
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java
/* * Copyright 2004, 2005, 2006, 2021 Acegi Technology Pty Limited * * 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.servletapi; import java.util.Arrays; import java.util.List; import jakarta.servlet.AsyncContext; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; 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.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.concurrent.DelegatingSecurityContextRunnable; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests {@link SecurityContextHolderAwareRequestFilter}. * * @author Ben Alex * @author Rob Winch * @author Eddú Meléndez */ @ExtendWith(MockitoExtension.class) public class SecurityContextHolderAwareRequestFilterTests { @Captor private ArgumentCaptor<HttpServletRequest> requestCaptor; @Mock private AuthenticationManager authenticationManager; @Mock private AuthenticationEntryPoint authenticationEntryPoint; @Mock private LogoutHandler logoutHandler; @Mock private FilterChain filterChain; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; private List<LogoutHandler> logoutHandlers; private SecurityContextHolderAwareRequestFilter filter; @BeforeEach public void setUp() throws Exception { this.logoutHandlers = Arrays.asList(this.logoutHandler); this.filter = new SecurityContextHolderAwareRequestFilter(); this.filter.setAuthenticationEntryPoint(this.authenticationEntryPoint); this.filter.setAuthenticationManager(this.authenticationManager); this.filter.setLogoutHandlers(this.logoutHandlers); this.filter.afterPropertiesSet(); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void expectedRequestWrapperClassIsUsed() throws Exception { this.filter.setRolePrefix("ROLE_"); this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), this.filterChain); // Now re-execute the filter, ensuring our replacement wrapper is still used this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), this.filterChain); verify(this.filterChain, times(2)).doFilter(any(SecurityContextHolderAwareRequestWrapper.class), any(HttpServletResponse.class)); this.filter.destroy(); } @Test public void authenticateFalse() throws Exception { assertThat(wrappedRequest().authenticate(this.response)).isFalse(); verify(this.authenticationEntryPoint).commence(eq(this.requestCaptor.getValue()), eq(this.response), any(AuthenticationException.class)); verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler); verify(this.request, times(0)).authenticate(any(HttpServletResponse.class)); } @Test public void authenticateTrue() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("test", "password", "ROLE_USER")); assertThat(wrappedRequest().authenticate(this.response)).isTrue(); verifyNoMoreInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); verify(this.request, times(0)).authenticate(any(HttpServletResponse.class)); } @Test public void authenticateNullEntryPointFalse() throws Exception { this.filter.setAuthenticationEntryPoint(null); this.filter.afterPropertiesSet(); assertThat(wrappedRequest().authenticate(this.response)).isFalse(); verify(this.request).authenticate(this.response); verifyNoMoreInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); } @Test public void authenticateNullEntryPointTrue() throws Exception { given(this.request.authenticate(this.response)).willReturn(true); this.filter.setAuthenticationEntryPoint(null); this.filter.afterPropertiesSet(); assertThat(wrappedRequest().authenticate(this.response)).isTrue(); verify(this.request).authenticate(this.response); verifyNoMoreInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); } @Test public void login() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) .willReturn(expectedAuth); wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth); verifyNoMoreInteractions(this.authenticationEntryPoint, this.logoutHandler); verify(this.request, times(0)).login(anyString(), anyString()); } // SEC-2296 @Test public void loginWithExistingUser() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); SecurityContextHolder.getContext().setAuthentication(expectedAuth); assertThatExceptionOfType(ServletException.class).isThrownBy( () -> wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials()))); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth); verifyNoMoreInteractions(this.authenticationEntryPoint, this.logoutHandler); verify(this.request, times(0)).login(anyString(), anyString()); } @Test public void loginFail() throws Exception { AuthenticationException authException = new BadCredentialsException("Invalid"); given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) .willThrow(authException); assertThatExceptionOfType(ServletException.class) .isThrownBy(() -> wrappedRequest().login("invalid", "credentials")).withCause(authException); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); verifyNoMoreInteractions(this.authenticationEntryPoint, this.logoutHandler); verify(this.request, times(0)).login(anyString(), anyString()); } @Test public void loginNullAuthenticationManager() throws Exception { this.filter.setAuthenticationManager(null); this.filter.afterPropertiesSet(); String username = "username"; String password = "password"; wrappedRequest().login(username, password); verify(this.request).login(username, password); verifyNoMoreInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); } @Test public void loginNullAuthenticationManagerFail() throws Exception { this.filter.setAuthenticationManager(null); this.filter.afterPropertiesSet(); String username = "username"; String password = "password"; ServletException authException = new ServletException("Failed Login"); willThrow(authException).given(this.request).login(username, password); assertThatExceptionOfType(ServletException.class).isThrownBy(() -> wrappedRequest().login(username, password)) .isEqualTo(authException); verifyNoMoreInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); } @Test public void loginWhenHttpServletRequestHasAuthenticationDetailsThenAuthenticationRequestHasDetails() throws Exception { String ipAddress = "10.0.0.100"; String sessionId = "session-id"; given(this.request.getRemoteAddr()).willReturn(ipAddress); given(this.request.getSession(anyBoolean())).willReturn(new MockHttpSession(null, sessionId)); wrappedRequest().login("username", "password"); ArgumentCaptor<UsernamePasswordAuthenticationToken> authenticationCaptor = ArgumentCaptor .forClass(UsernamePasswordAuthenticationToken.class); verify(this.authenticationManager).authenticate(authenticationCaptor.capture()); UsernamePasswordAuthenticationToken authenticationRequest = authenticationCaptor.getValue(); assertThat(authenticationRequest.getDetails()).isInstanceOf(WebAuthenticationDetails.class); WebAuthenticationDetails details = (WebAuthenticationDetails) authenticationRequest.getDetails(); assertThat(details.getRemoteAddress()).isEqualTo(ipAddress); assertThat(details.getSessionId()).isEqualTo(sessionId); } @Test public void logout() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); SecurityContextHolder.getContext().setAuthentication(expectedAuth); HttpServletRequest wrappedRequest = wrappedRequest(); wrappedRequest.logout(); verify(this.logoutHandler).logout(wrappedRequest, this.response, expectedAuth); verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler); verify(this.request, times(0)).logout(); } @Test public void logoutNullLogoutHandler() throws Exception { this.filter.setLogoutHandlers(null); this.filter.afterPropertiesSet(); wrappedRequest().logout(); verify(this.request).logout(); verifyNoMoreInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); } // gh-3780 @Test public void getAsyncContextNullFromSuper() throws Exception { assertThat(wrappedRequest().getAsyncContext()).isNull(); } @Test public void getAsyncContextStart() throws Exception { ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); SecurityContext context = SecurityContextHolder.createEmptyContext(); TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); context.setAuthentication(expectedAuth); SecurityContextHolder.setContext(context); AsyncContext asyncContext = mock(AsyncContext.class); given(this.request.getAsyncContext()).willReturn(asyncContext); Runnable runnable = () -> { }; wrappedRequest().getAsyncContext().start(runnable); verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler); verify(asyncContext).start(runnableCaptor.capture()); DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor .getValue(); assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context); assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate")); } @Test public void startAsyncStart() throws Exception { ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); SecurityContext context = SecurityContextHolder.createEmptyContext(); TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); context.setAuthentication(expectedAuth); SecurityContextHolder.setContext(context); AsyncContext asyncContext = mock(AsyncContext.class); given(this.request.startAsync()).willReturn(asyncContext); Runnable runnable = () -> { }; wrappedRequest().startAsync().start(runnable); verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler); verify(asyncContext).start(runnableCaptor.capture()); DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor .getValue(); assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context); assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate")); } @Test public void startAsyncWithRequestResponseStart() throws Exception { ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); SecurityContext context = SecurityContextHolder.createEmptyContext(); TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); context.setAuthentication(expectedAuth); SecurityContextHolder.setContext(context); AsyncContext asyncContext = mock(AsyncContext.class); given(this.request.startAsync(this.request, this.response)).willReturn(asyncContext); Runnable runnable = () -> { }; wrappedRequest().startAsync(this.request, this.response).start(runnable); verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler); verify(asyncContext).start(runnableCaptor.capture()); DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor .getValue(); assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context); assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate")); } // SEC-3047 @Test public void updateRequestFactory() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("user", "password", "PREFIX_USER")); this.filter.setRolePrefix("PREFIX_"); assertThat(wrappedRequest().isUserInRole("PREFIX_USER")).isTrue(); } private HttpServletRequest wrappedRequest() throws Exception { this.filter.doFilter(this.request, this.response, this.filterChain); verify(this.filterChain).doFilter(this.requestCaptor.capture(), any(HttpServletResponse.class)); return this.requestCaptor.getValue(); } }
15,268
43.257971
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapperTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.servletapi; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.AuthenticatedPrincipal; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests {@link SecurityContextHolderAwareRequestWrapper}. * * @author Ben Alex */ public class SecurityContextHolderAwareRequestWrapperTests { @BeforeEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void testCorrectOperationWithStringBasedPrincipal() { Authentication auth = new TestingAuthenticationToken("rod", "koala", "ROLE_FOO"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/"); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, ""); assertThat(wrapper.getRemoteUser()).isEqualTo("rod"); assertThat(wrapper.isUserInRole("ROLE_FOO")).isTrue(); assertThat(wrapper.isUserInRole("ROLE_NOT_GRANTED")).isFalse(); assertThat(wrapper.getUserPrincipal()).isEqualTo(auth); } @Test public void testUseOfRolePrefixMeansItIsntNeededWhenCallngIsUserInRole() { Authentication auth = new TestingAuthenticationToken("rod", "koala", "ROLE_FOO"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/"); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, "ROLE_"); assertThat(wrapper.isUserInRole("FOO")).isTrue(); } @Test public void testCorrectOperationWithUserDetailsBasedPrincipal() { Authentication auth = new TestingAuthenticationToken( new User("rodAsUserDetails", "koala", true, true, true, true, AuthorityUtils.NO_AUTHORITIES), "koala", "ROLE_HELLO", "ROLE_FOOBAR"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/"); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, ""); assertThat(wrapper.getRemoteUser()).isEqualTo("rodAsUserDetails"); assertThat(wrapper.isUserInRole("ROLE_FOO")).isFalse(); assertThat(wrapper.isUserInRole("ROLE_NOT_GRANTED")).isFalse(); assertThat(wrapper.isUserInRole("ROLE_FOOBAR")).isTrue(); assertThat(wrapper.isUserInRole("ROLE_HELLO")).isTrue(); assertThat(wrapper.getUserPrincipal()).isEqualTo(auth); } @Test public void testRoleIsntHeldIfAuthenticationIsNull() { SecurityContextHolder.getContext().setAuthentication(null); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/"); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, ""); assertThat(wrapper.getRemoteUser()).isNull(); assertThat(wrapper.isUserInRole("ROLE_ANY")).isFalse(); assertThat(wrapper.getUserPrincipal()).isNull(); } @Test public void testRolesArentHeldIfAuthenticationPrincipalIsNull() { Authentication auth = new TestingAuthenticationToken(null, "koala", "ROLE_HELLO", "ROLE_FOOBAR"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/"); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, ""); assertThat(wrapper.getRemoteUser()).isNull(); assertThat(wrapper.isUserInRole("ROLE_HELLO")).isFalse(); // principal is null, so // reject assertThat(wrapper.isUserInRole("ROLE_FOOBAR")).isFalse(); // principal is null, // so reject assertThat(wrapper.getUserPrincipal()).isNull(); } @Test public void testRolePrefix() { Authentication auth = new TestingAuthenticationToken("user", "koala", "ROLE_HELLO", "ROLE_FOOBAR"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, "ROLE_"); assertThat(wrapper.isUserInRole("HELLO")).isTrue(); assertThat(wrapper.isUserInRole("FOOBAR")).isTrue(); } // SEC-3020 @Test public void testRolePrefixNotAppliedIfRoleStartsWith() { Authentication auth = new TestingAuthenticationToken("user", "koala", "ROLE_HELLO", "ROLE_FOOBAR"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, "ROLE_"); assertThat(wrapper.isUserInRole("ROLE_HELLO")).isTrue(); assertThat(wrapper.isUserInRole("ROLE_FOOBAR")).isTrue(); } @Test public void testGetRemoteUserStringWithAuthenticatedPrincipal() { String username = "authPrincipalUsername"; AuthenticatedPrincipal principal = mock(AuthenticatedPrincipal.class); given(principal.getName()).willReturn(username); Authentication auth = new TestingAuthenticationToken(principal, "user"); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/"); SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, ""); assertThat(wrapper.getRemoteUser()).isEqualTo(username); verify(principal, times(1)).getName(); } }
6,767
43.235294
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java
/* * 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. * 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.firewall; import java.util.LinkedHashMap; import java.util.Map; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Luke Taylor */ public class RequestWrapperTests { private static Map<String, String> testPaths = new LinkedHashMap<>(); @BeforeAll // Some of these may be unrealistic values, but we can't be sure because of the // inconsistency in the spec. public static void createTestMap() { testPaths.put("/path1;x=y;z=w/path2;x=y/path3;x=y", "/path1/path2/path3"); testPaths.put("/path1;x=y/path2;x=y/", "/path1/path2/"); testPaths.put("/path1//path2/", "/path1/path2/"); testPaths.put("//path1/path2//", "/path1/path2/"); testPaths.put(";x=y;z=w", ""); } @Test public void pathParametersAreRemovedFromServletPath() { MockHttpServletRequest request = new MockHttpServletRequest(); for (Map.Entry<String, String> entry : testPaths.entrySet()) { String path = entry.getKey(); String expectedResult = entry.getValue(); request.setServletPath(path); RequestWrapper wrapper = new RequestWrapper(request); assertThat(wrapper.getServletPath()).isEqualTo(expectedResult); wrapper.reset(); assertThat(wrapper.getServletPath()).isEqualTo(path); } } @Test public void pathParametersAreRemovedFromPathInfo() { MockHttpServletRequest request = new MockHttpServletRequest(); for (Map.Entry<String, String> entry : testPaths.entrySet()) { String path = entry.getKey(); String expectedResult = entry.getValue(); // Should be null when stripped value is empty if (expectedResult.length() == 0) { expectedResult = null; } request.setPathInfo(path); RequestWrapper wrapper = new RequestWrapper(request); assertThat(wrapper.getPathInfo()).isEqualTo(expectedResult); wrapper.reset(); assertThat(wrapper.getPathInfo()).isEqualTo(path); } } @Test public void resetWhenForward() throws Exception { String denormalizedPath = testPaths.keySet().iterator().next(); String forwardPath = "/forward/path"; HttpServletRequest mockRequest = mock(HttpServletRequest.class); HttpServletResponse mockResponse = mock(HttpServletResponse.class); RequestDispatcher mockDispatcher = mock(RequestDispatcher.class); given(mockRequest.getServletPath()).willReturn(""); given(mockRequest.getPathInfo()).willReturn(denormalizedPath); given(mockRequest.getRequestDispatcher(forwardPath)).willReturn(mockDispatcher); RequestWrapper wrapper = new RequestWrapper(mockRequest); RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath); dispatcher.forward(mockRequest, mockResponse); verify(mockRequest).getRequestDispatcher(forwardPath); verify(mockDispatcher).forward(mockRequest, mockResponse); assertThat(wrapper.getPathInfo()).isEqualTo(denormalizedPath); verify(mockRequest, times(2)).getPathInfo(); // validate wrapper.getServletPath() delegates to the mock wrapper.getServletPath(); verify(mockRequest, times(2)).getServletPath(); verifyNoMoreInteractions(mockRequest, mockResponse, mockDispatcher); } @Test public void requestDispatcherNotWrappedAfterReset() { String path = "/forward/path"; HttpServletRequest request = mock(HttpServletRequest.class); RequestDispatcher dispatcher = mock(RequestDispatcher.class); given(request.getRequestDispatcher(path)).willReturn(dispatcher); RequestWrapper wrapper = new RequestWrapper(request); wrapper.reset(); assertThat(wrapper.getRequestDispatcher(path)).isSameAs(dispatcher); } }
4,650
37.122951
82
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/firewall/DefaultHttpFirewallTests.java
/* * 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. * 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.firewall; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor */ public class DefaultHttpFirewallTests { public String[] unnormalizedPaths = { "/..", "/./path/", "/path/path/.", "/path/path//.", "./path/../path//.", "./path", ".//path", "." }; @Test public void unnormalizedPathsAreRejected() { DefaultHttpFirewall fw = new DefaultHttpFirewall(); for (String path : this.unnormalizedPaths) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath(path); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> fw.getFirewalledRequest(request)); request.setPathInfo(path); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> fw.getFirewalledRequest(request)); } } /** * On WebSphere 8.5 a URL like /context-root/a/b;%2f1/c can bypass a rule on /a/b/c * because the pathInfo is /a/b;/1/c which ends up being /a/b/1/c while Spring MVC * will strip the ; content from requestURI before the path is URL decoded. */ @Test public void getFirewalledRequestWhenLowercaseEncodedPathThenException() { DefaultHttpFirewall fw = new DefaultHttpFirewall(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/context-root/a/b;%2f1/c"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> fw.getFirewalledRequest(request)); } @Test public void getFirewalledRequestWhenUppercaseEncodedPathThenException() { DefaultHttpFirewall fw = new DefaultHttpFirewall(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/context-root/a/b;%2F1/c"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> fw.getFirewalledRequest(request)); } @Test public void getFirewalledRequestWhenAllowUrlEncodedSlashAndLowercaseEncodedPathThenNoException() { DefaultHttpFirewall fw = new DefaultHttpFirewall(); fw.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/context-root/a/b;%2f1/c"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI fw.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenAllowUrlEncodedSlashAndUppercaseEncodedPathThenNoException() { DefaultHttpFirewall fw = new DefaultHttpFirewall(); fw.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/context-root/a/b;%2F1/c"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI fw.getFirewalledRequest(request); } }
3,839
37.787879
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/firewall/CompositeRequestRejectedHandlerTests.java
/* * 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. * 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.firewall; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; public class CompositeRequestRejectedHandlerTests { @Test void compositeRequestRejectedHandlerRethrowsTheException() { RequestRejectedException requestRejectedException = new RequestRejectedException("rejected"); CompositeRequestRejectedHandler handler = new CompositeRequestRejectedHandler( new DefaultRequestRejectedHandler()); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> handler .handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException)) .withMessage("rejected"); } @Test void compositeRequestRejectedHandlerForbidsEmptyHandlers() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(CompositeRequestRejectedHandler::new); } }
1,671
37
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandlerTests.java
/* * Copyright 2002-2020 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.firewall; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class HttpStatusRequestRejectedHandlerTests { @Test public void httpStatusRequestRejectedHandlerUsesStatus400byDefault() throws Exception { HttpStatusRequestRejectedHandler sut = new HttpStatusRequestRejectedHandler(); HttpServletResponse response = mock(HttpServletResponse.class); sut.handle(mock(HttpServletRequest.class), response, mock(RequestRejectedException.class)); verify(response).sendError(400); } @Test public void httpStatusRequestRejectedHandlerCanBeConfiguredToUseStatus() throws Exception { httpStatusRequestRejectedHandlerCanBeConfiguredToUseStatusHelper(400); httpStatusRequestRejectedHandlerCanBeConfiguredToUseStatusHelper(403); httpStatusRequestRejectedHandlerCanBeConfiguredToUseStatusHelper(500); } private void httpStatusRequestRejectedHandlerCanBeConfiguredToUseStatusHelper(int status) throws Exception { HttpStatusRequestRejectedHandler sut = new HttpStatusRequestRejectedHandler(status); HttpServletResponse response = mock(HttpServletResponse.class); sut.handle(mock(HttpServletRequest.class), response, mock(RequestRejectedException.class)); verify(response).sendError(status); } }
2,045
39.117647
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java
/* * 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. * 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.firewall; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Luke Taylor * @author Eddú Meléndez * @author Gabriel Lavoie */ public class FirewalledResponseTests { private static final String CRLF_MESSAGE = "Invalid characters (CR/LF)"; private HttpServletResponse response; private FirewalledResponse fwResponse; @BeforeEach public void setup() { this.response = mock(HttpServletResponse.class); this.fwResponse = new FirewalledResponse(this.response); } @Test public void sendRedirectWhenValidThenNoException() throws Exception { this.fwResponse.sendRedirect("/theURL"); verify(this.response).sendRedirect("/theURL"); } @Test public void sendRedirectWhenNullThenDelegateInvoked() throws Exception { this.fwResponse.sendRedirect(null); verify(this.response).sendRedirect(null); } @Test public void sendRedirectWhenHasCrlfThenThrowsException() throws Exception { assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.sendRedirect("/theURL\r\nsomething")) .withMessageContaining(CRLF_MESSAGE); } @Test public void addHeaderWhenValidThenDelegateInvoked() { this.fwResponse.addHeader("foo", "bar"); verify(this.response).addHeader("foo", "bar"); } @Test public void addHeaderWhenNullValueThenDelegateInvoked() { this.fwResponse.addHeader("foo", null); verify(this.response).addHeader("foo", null); } @Test public void addHeaderWhenHeaderValueHasCrlfThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.fwResponse.addHeader("foo", "abc\r\nContent-Length:100")) .withMessageContaining(CRLF_MESSAGE); } @Test public void addHeaderWhenHeaderNameHasCrlfThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.fwResponse.addHeader("abc\r\nContent-Length:100", "bar")) .withMessageContaining(CRLF_MESSAGE); } @Test public void addCookieWhenValidThenDelegateInvoked() { Cookie cookie = new Cookie("foo", "bar"); cookie.setPath("/foobar"); cookie.setDomain("foobar"); cookie.setComment("foobar"); this.fwResponse.addCookie(cookie); verify(this.response).addCookie(cookie); } @Test public void addCookieWhenNullThenDelegateInvoked() { this.fwResponse.addCookie(null); verify(this.response).addCookie(null); } @Test public void addCookieWhenCookieNameContainsCrlfThenException() { // Constructor validates the name Cookie cookie = new Cookie("valid-since-constructor-validates", "bar") { @Override public String getName() { return "foo\r\nbar"; } }; assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie)) .withMessageContaining(CRLF_MESSAGE); } @Test public void addCookieWhenCookieValueContainsCrlfThenException() { Cookie cookie = new Cookie("foo", "foo\r\nbar"); assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie)) .withMessageContaining(CRLF_MESSAGE); } @Test public void addCookieWhenCookiePathContainsCrlfThenException() { Cookie cookie = new Cookie("foo", "bar"); cookie.setPath("/foo\r\nbar"); assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie)) .withMessageContaining(CRLF_MESSAGE); } @Test public void addCookieWhenCookieDomainContainsCrlfThenException() { Cookie cookie = new Cookie("foo", "bar"); cookie.setDomain("foo\r\nbar"); assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie)) .withMessageContaining(CRLF_MESSAGE); } @Test public void rejectAnyLineEndingInNameAndValue() { validateLineEnding("foo", "foo\rbar"); validateLineEnding("foo", "foo\r\nbar"); validateLineEnding("foo", "foo\nbar"); validateLineEnding("foo\rbar", "bar"); validateLineEnding("foo\r\nbar", "bar"); validateLineEnding("foo\nbar", "bar"); } private void validateLineEnding(String name, String value) { assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.validateCrlf(name, value)); } }
4,944
30.297468
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java
/* * Copyright 2002-2020 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.firewall; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; public class DefaultRequestRejectedHandlerTests { @Test public void defaultRequestRejectedHandlerRethrowsTheException() throws Exception { RequestRejectedException requestRejectedException = new RequestRejectedException("rejected"); DefaultRequestRejectedHandler sut = new DefaultRequestRejectedHandler(); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> sut .handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException)) .withMessage("rejected"); } }
1,456
37.342105
103
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java
/* * Copyright 2012-2021 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.firewall; import java.util.Arrays; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch * @author Eddú Meléndez */ public class StrictHttpFirewallTests { public String[] unnormalizedPaths = { "/..", "/./path/", "/path/path/.", "/path/path//.", "./path/../path//.", "./path", ".//path", ".", "//path", "//path/path", "//path//path", "/path//path" }; private StrictHttpFirewall firewall = new StrictHttpFirewall(); private MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); @Test public void getFirewalledRequestWhenInvalidMethodThenThrowsRequestRejectedException() { this.request.setMethod("INVALID"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } // blocks XST attacks @Test public void getFirewalledRequestWhenTraceMethodThenThrowsRequestRejectedException() { this.request.setMethod(HttpMethod.TRACE.name()); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test // blocks XST attack if request is forwarded to a Microsoft IIS web server public void getFirewalledRequestWhenTrackMethodThenThrowsRequestRejectedException() { this.request.setMethod("TRACK"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test // HTTP methods are case sensitive public void getFirewalledRequestWhenLowercaseGetThenThrowsRequestRejectedException() { this.request.setMethod("get"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenAllowedThenNoException() { List<String> allowedMethods = Arrays.asList("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"); for (String allowedMethod : allowedMethods) { this.request = new MockHttpServletRequest(allowedMethod, ""); this.firewall.getFirewalledRequest(this.request); } } @Test public void getFirewalledRequestWhenInvalidMethodAndAnyMethodThenNoException() { this.firewall.setUnsafeAllowAnyHttpMethod(true); this.request.setMethod("INVALID"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenRequestURINotNormalizedThenThrowsRequestRejectedException() { for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setRequestURI(path); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } @Test public void getFirewalledRequestWhenContextPathNotNormalizedThenThrowsRequestRejectedException() { for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setContextPath(path); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } @Test public void getFirewalledRequestWhenServletPathNotNormalizedThenThrowsRequestRejectedException() { for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setServletPath(path); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } @Test public void getFirewalledRequestWhenPathInfoNotNormalizedThenThrowsRequestRejectedException() { for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setPathInfo(path); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } @Test public void getFirewalledRequestWhenSemicolonInContextPathThenThrowsRequestRejectedException() { this.request.setContextPath(";/context"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenSemicolonInServletPathThenThrowsRequestRejectedException() { this.request.setServletPath("/spring;/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenSemicolonInPathInfoThenThrowsRequestRejectedException() { this.request.setPathInfo("/path;/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenSemicolonInRequestUriThenThrowsRequestRejectedException() { this.request.setRequestURI("/path;/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenEncodedSemicolonInContextPathThenThrowsRequestRejectedException() { this.request.setContextPath("%3B/context"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenEncodedSemicolonInServletPathThenThrowsRequestRejectedException() { this.request.setServletPath("/spring%3B/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenEncodedSemicolonInPathInfoThenThrowsRequestRejectedException() { this.request.setPathInfo("/path%3B/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenEncodedSemicolonInRequestUriThenThrowsRequestRejectedException() { this.request.setRequestURI("/path%3B/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInContextPathThenThrowsRequestRejectedException() { this.request.setContextPath("%3b/context"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInServletPathThenThrowsRequestRejectedException() { this.request.setServletPath("/spring%3b/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInPathInfoThenThrowsRequestRejectedException() { this.request.setPathInfo("/path%3b/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInRequestUriThenThrowsRequestRejectedException() { this.request.setRequestURI("/path%3b/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenSemicolonInContextPathAndAllowSemicolonThenNoException() { this.firewall.setAllowSemicolon(true); this.request.setContextPath(";/context"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenSemicolonInServletPathAndAllowSemicolonThenNoException() { this.firewall.setAllowSemicolon(true); this.request.setServletPath("/spring;/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenSemicolonInPathInfoAndAllowSemicolonThenNoException() { this.firewall.setAllowSemicolon(true); this.request.setPathInfo("/path;/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenSemicolonInRequestUriAndAllowSemicolonThenNoException() { this.firewall.setAllowSemicolon(true); this.request.setRequestURI("/path;/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenEncodedSemicolonInContextPathAndAllowSemicolonThenNoException() { this.firewall.setAllowUrlEncodedPercent(true); this.firewall.setAllowSemicolon(true); this.request.setContextPath("%3B/context"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenEncodedSemicolonInServletPathAndAllowSemicolonThenNoException() { this.firewall.setAllowUrlEncodedPercent(true); this.firewall.setAllowSemicolon(true); this.request.setServletPath("/spring%3B/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenEncodedSemicolonInPathInfoAndAllowSemicolonThenNoException() { this.firewall.setAllowUrlEncodedPercent(true); this.firewall.setAllowSemicolon(true); this.request.setPathInfo("/path%3B/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenEncodedSemicolonInRequestUriAndAllowSemicolonThenNoException() { this.firewall.setAllowSemicolon(true); this.request.setRequestURI("/path%3B/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInContextPathAndAllowSemicolonThenNoException() { this.firewall.setAllowUrlEncodedPercent(true); this.firewall.setAllowSemicolon(true); this.request.setContextPath("%3b/context"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInServletPathAndAllowSemicolonThenNoException() { this.firewall.setAllowUrlEncodedPercent(true); this.firewall.setAllowSemicolon(true); this.request.setServletPath("/spring%3b/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInPathInfoAndAllowSemicolonThenNoException() { this.firewall.setAllowUrlEncodedPercent(true); this.firewall.setAllowSemicolon(true); this.request.setPathInfo("/path%3b/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenLowercaseEncodedSemicolonInRequestUriAndAllowSemicolonThenNoException() { this.firewall.setAllowSemicolon(true); this.request.setRequestURI("/path%3b/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenEncodedPeriodInThenThrowsRequestRejectedException() { this.request.setRequestURI("/%2E/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenLowercaseEncodedPeriodInThenThrowsRequestRejectedException() { this.request.setRequestURI("/%2e/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenAllowEncodedPeriodAndEncodedPeriodInThenNoException() { this.firewall.setAllowUrlEncodedPeriod(true); this.request.setRequestURI("/%2E/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenExceedsLowerboundAsciiThenException() { this.request.setRequestURI("/\u0019"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsLowerboundAsciiThenNoException() { this.request.setRequestURI("/ "); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenContainsUpperboundAsciiThenNoException() { this.request.setRequestURI("/~"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenJapaneseCharacterThenNoException() { this.request.setServletPath("/\u3042"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenExceedsUpperboundAsciiThenException() { this.request.setRequestURI("/\u007f"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsNullThenException() { this.request.setRequestURI("/\0"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsEncodedNullThenException() { this.request.setRequestURI("/something%00/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsLowercaseEncodedLineFeedThenException() { this.request.setRequestURI("/something%0a/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsUppercaseEncodedLineFeedThenException() { this.request.setRequestURI("/something%0A/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsLineFeedThenException() { this.request.setRequestURI("/something\n/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenServletPathContainsLineFeedThenException() { this.request.setServletPath("/something\n/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsLowercaseEncodedCarriageReturnThenException() { this.request.setRequestURI("/something%0d/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsUppercaseEncodedCarriageReturnThenException() { this.request.setRequestURI("/something%0D/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsCarriageReturnThenException() { this.request.setRequestURI("/something\r/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenServletPathContainsCarriageReturnThenException() { this.request.setServletPath("/something\r/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenServletPathContainsLineSeparatorThenException() { this.request.setServletPath("/something\u2028/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenServletPathContainsParagraphSeparatorThenException() { this.request.setServletPath("/something\u2029/"); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenContainsLowercaseEncodedLineFeedAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedLineFeed(true); this.request.setRequestURI("/something%0a/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenContainsUppercaseEncodedLineFeedAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedLineFeed(true); this.request.setRequestURI("/something%0A/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenContainsLineFeedAndAllowedThenException() { this.firewall.setAllowUrlEncodedLineFeed(true); this.request.setRequestURI("/something\n/"); // Expected an error because the line feed is decoded in an encoded part of the // URL assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenServletPathContainsLineFeedAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedLineFeed(true); this.request.setServletPath("/something\n/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenContainsLowercaseEncodedCarriageReturnAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedCarriageReturn(true); this.request.setRequestURI("/something%0d/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenContainsUppercaseEncodedCarriageReturnAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedCarriageReturn(true); this.request.setRequestURI("/something%0D/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenContainsCarriageReturnAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedCarriageReturn(true); this.request.setRequestURI("/something\r/"); // Expected an error because the carriage return is decoded in an encoded part of // the URL assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenServletPathContainsCarriageReturnAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedCarriageReturn(true); this.request.setServletPath("/something\r/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenServletPathContainsLineSeparatorAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedLineSeparator(true); this.request.setServletPath("/something\u2028/"); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenServletPathContainsParagraphSeparatorAndAllowedThenNoException() { this.firewall.setAllowUrlEncodedParagraphSeparator(true); this.request.setServletPath("/something\u2029/"); this.firewall.getFirewalledRequest(this.request); } /** * On WebSphere 8.5 a URL like /context-root/a/b;%2f1/c can bypass a rule on /a/b/c * because the pathInfo is /a/b;/1/c which ends up being /a/b/1/c while Spring MVC * will strip the ; content from requestURI before the path is URL decoded. */ @Test public void getFirewalledRequestWhenLowercaseEncodedPathThenException() { this.request.setRequestURI("/context-root/a/b;%2f1/c"); this.request.setContextPath("/context-root"); this.request.setServletPath(""); this.request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenUppercaseEncodedPathThenException() { this.request.setRequestURI("/context-root/a/b;%2F1/c"); this.request.setContextPath("/context-root"); this.request.setServletPath(""); this.request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestWhenAllowUrlEncodedSlashAndLowercaseEncodedPathThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); this.firewall.setAllowSemicolon(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b;%2f1/c"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenAllowUrlEncodedSlashAndUppercaseEncodedPathThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); this.firewall.setAllowSemicolon(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b;%2F1/c"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenAllowUrlLowerCaseEncodedDoubleSlashThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); this.firewall.setAllowUrlEncodedDoubleSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2fc"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenAllowUrlUpperCaseEncodedDoubleSlashThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); this.firewall.setAllowUrlEncodedDoubleSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2Fc"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenAllowUrlLowerCaseAndUpperCaseEncodedDoubleSlashThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); this.firewall.setAllowUrlEncodedDoubleSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2Fc"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenAllowUrlUpperCaseAndLowerCaseEncodedDoubleSlashThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); this.firewall.setAllowUrlEncodedDoubleSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2fc"); request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromUpperCaseEncodedUrlBlacklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2Fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2F%2F")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromLowerCaseEncodedUrlBlacklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2f%2f")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromLowerCaseAndUpperCaseEncodedUrlBlacklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2Fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2f%2F")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromUpperCaseAndLowerCaseEncodedUrlBlacklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2F%2f")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromDecodedUrlBlacklistThenNoException() { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setPathInfo("/a/b//c"); this.firewall.getDecodedUrlBlacklist().removeAll(Arrays.asList("//")); this.firewall.getFirewalledRequest(request); } // blocklist @Test public void getFirewalledRequestWhenRemoveFromUpperCaseEncodedUrlBlocklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2Fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2F%2F")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromLowerCaseEncodedUrlBlocklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2f%2f")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromLowerCaseAndUpperCaseEncodedUrlBlocklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2Fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2f%2F")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromUpperCaseAndLowerCaseEncodedUrlBlocklistThenNoException() { this.firewall.setAllowUrlEncodedSlash(true); MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2F%2f")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenRemoveFromDecodedUrlBlocklistThenNoException() { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setPathInfo("/a/b//c"); this.firewall.getDecodedUrlBlocklist().removeAll(Arrays.asList("//")); this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenTrustedDomainThenNoException() { this.request.addHeader("Host", "example.org"); this.firewall.setAllowedHostnames((hostname) -> hostname.equals("example.org")); this.firewall.getFirewalledRequest(this.request); } @Test public void getFirewalledRequestWhenUntrustedDomainThenException() { this.request.addHeader("Host", "example.org"); this.firewall.setAllowedHostnames((hostname) -> hostname.equals("myexample.org")); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test public void getFirewalledRequestGetHeaderWhenNotAllowedHeaderNameThenException() { this.firewall.setAllowedHeaderNames((name) -> !name.equals("bad name")); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getHeader("bad name")); } @Test public void getFirewalledRequestGetHeaderWhenNotAllowedHeaderValueThenException() { this.request.addHeader("good name", "bad value"); this.firewall.setAllowedHeaderValues((value) -> !value.equals("bad value")); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getHeader("good name")); } @Test public void getFirewalledRequestGetDateHeaderWhenControlCharacterInHeaderNameThenException() { this.request.addHeader("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getDateHeader("Bad\0Name")); } @Test public void getFirewalledRequestGetIntHeaderWhenControlCharacterInHeaderNameThenException() { this.request.addHeader("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getIntHeader("Bad\0Name")); } @Test public void getFirewalledRequestGetHeaderWhenControlCharacterInHeaderNameThenException() { this.request.addHeader("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getHeader("Bad\0Name")); } @Test public void getFirewalledRequestGetHeaderWhenUndefinedCharacterInHeaderNameThenException() { this.request.addHeader("Bad\uFFFEName", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getHeader("Bad\uFFFEName")); } @Test public void getFirewalledRequestGetHeadersWhenControlCharacterInHeaderNameThenException() { this.request.addHeader("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getHeaders("Bad\0Name")); } @Test public void getFirewalledRequestGetHeaderNamesWhenControlCharacterInHeaderNameThenException() { this.request.addHeader("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> request.getHeaderNames().nextElement()); } @Test public void getFirewalledRequestGetHeaderWhenControlCharacterInHeaderValueThenException() { this.request.addHeader("Something", "bad\0value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getHeader("Something")); } @Test public void getFirewalledRequestGetHeaderWhenUndefinedCharacterInHeaderValueThenException() { this.request.addHeader("Something", "bad\uFFFEvalue"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getHeader("Something")); } @Test public void getFirewalledRequestGetHeadersWhenControlCharacterInHeaderValueThenException() { this.request.addHeader("Something", "bad\0value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> request.getHeaders("Something").nextElement()); } @Test public void getFirewalledRequestGetParameterWhenControlCharacterInParameterNameThenException() { this.request.addParameter("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> request.getParameter("Bad\0Name")); } @Test public void getFirewalledRequestGetParameterMapWhenControlCharacterInParameterNameThenException() { this.request.addParameter("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(request::getParameterMap); } @Test public void getFirewalledRequestGetParameterNamesWhenControlCharacterInParameterNameThenException() { this.request.addParameter("Bad\0Name", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(request.getParameterNames()::nextElement); } @Test public void getFirewalledRequestGetParameterNamesWhenUndefinedCharacterInParameterNameThenException() { this.request.addParameter("Bad\uFFFEName", "some value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(request.getParameterNames()::nextElement); } @Test public void getFirewalledRequestGetParameterValuesWhenNotAllowedInParameterValueThenException() { this.firewall.setAllowedParameterValues((value) -> !value.equals("bad value")); this.request.addParameter("Something", "bad value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> request.getParameterValues("Something")); } @Test public void getFirewalledRequestGetParameterValuesWhenNotAllowedInParameterNameThenException() { this.firewall.setAllowedParameterNames((value) -> !value.equals("bad name")); this.request.addParameter("bad name", "good value"); HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(RequestRejectedException.class) .isThrownBy(() -> request.getParameterValues("bad name")); } // gh-9598 @Test public void getFirewalledRequestGetParameterWhenNameIsNullThenIllegalArgumentException() { HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> request.getParameter(null)); } // gh-9598 @Test public void getFirewalledRequestGetParameterValuesWhenNameIsNullThenIllegalArgumentException() { HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> request.getParameterValues(null)); } // gh-9598 @Test public void getFirewalledRequestGetHeaderWhenNameIsNullThenNull() { HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThat(request.getHeader(null)).isNull(); } // gh-9598 @Test public void getFirewalledRequestGetHeadersWhenNameIsNullThenEmptyEnumeration() { HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThat(request.getHeaders(null).hasMoreElements()).isFalse(); } // gh-9598 @Test public void getFirewalledRequestGetIntHeaderWhenNameIsNullThenNegativeOne() { HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThat(request.getIntHeader(null)).isEqualTo(-1); } @Test public void getFirewalledRequestGetDateHeaderWhenNameIsNullThenNegativeOne() { HttpServletRequest request = this.firewall.getFirewalledRequest(this.request); assertThat(request.getDateHeader(null)).isEqualTo(-1); } }
36,307
39.933484
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/UrlUtilsTests.java
/* * 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. * 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; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author Luke Taylor */ public class UrlUtilsTests { @Test public void absoluteUrlsAreMatchedAsAbsolute() { assertThat(UrlUtils.isAbsoluteUrl("https://something/")).isTrue(); assertThat(UrlUtils.isAbsoluteUrl("http1://something/")).isTrue(); assertThat(UrlUtils.isAbsoluteUrl("HTTP://something/")).isTrue(); assertThat(UrlUtils.isAbsoluteUrl("https://something/")).isTrue(); assertThat(UrlUtils.isAbsoluteUrl("a://something/")).isTrue(); assertThat(UrlUtils.isAbsoluteUrl("zz+zz.zz-zz://something/")).isTrue(); } @Test public void isAbsoluteUrlWhenNullThenFalse() { assertThat(UrlUtils.isAbsoluteUrl(null)).isFalse(); } @Test public void isAbsoluteUrlWhenEmptyThenFalse() { assertThat(UrlUtils.isAbsoluteUrl("")).isFalse(); } @Test public void isValidRedirectUrlWhenNullThenFalse() { assertThat(UrlUtils.isValidRedirectUrl(null)).isFalse(); } @Test public void isValidRedirectUrlWhenEmptyThenFalse() { assertThat(UrlUtils.isValidRedirectUrl("")).isFalse(); } }
1,775
29.101695
75
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/TextEscapeUtilsTests.java
/* * 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. * 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; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; public class TextEscapeUtilsTests { /** * &amp;, &lt;, &gt;, &#34;, &#39 and&#32;(space) escaping */ @Test public void charactersAreEscapedCorrectly() { assertThat(TextEscapeUtils.escapeEntities("& a<script>\"'")).isEqualTo("&amp;&#32;a&lt;script&gt;&#34;&#39;"); } @Test public void nullOrEmptyStringIsHandled() { assertThat(TextEscapeUtils.escapeEntities("")).isEqualTo(""); assertThat(TextEscapeUtils.escapeEntities(null)).isNull(); } @Test public void invalidLowSurrogateIsDetected() { assertThatIllegalArgumentException().isThrownBy(() -> TextEscapeUtils.escapeEntities("abc\uDCCCdef")); } @Test public void missingLowSurrogateIsDetected() { assertThatIllegalArgumentException().isThrownBy(() -> TextEscapeUtils.escapeEntities("abc\uD888a")); } @Test public void highSurrogateAtEndOfStringIsRejected() { assertThatIllegalArgumentException().isThrownBy(() -> TextEscapeUtils.escapeEntities("abc\uD888")); } /** * Delta char: &#66560; */ @Test public void validSurrogatePairIsAccepted() { assertThat(TextEscapeUtils.escapeEntities("abc\uD801\uDC00a")).isEqualTo("abc&#66560;a"); } @Test public void undefinedSurrogatePairIsIgnored() { assertThat(TextEscapeUtils.escapeEntities("abc\uD888\uDC00a")).isEqualTo("abca"); } }
2,127
29.84058
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java
/* * Copyright 2002-2015 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; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class OnCommittedResponseWrapperTests { private static final String NL = "\r\n"; @Mock HttpServletResponse delegate; @Mock PrintWriter writer; @Mock ServletOutputStream out; OnCommittedResponseWrapper response; boolean committed; @BeforeEach public void setup() throws Exception { this.response = new OnCommittedResponseWrapper(this.delegate) { @Override protected void onResponseCommitted() { OnCommittedResponseWrapperTests.this.committed = true; } }; } private void givenGetWriterThenReturn() throws IOException { given(this.delegate.getWriter()).willReturn(this.writer); } private void givenGetOutputStreamThenReturn() throws IOException { given(this.delegate.getOutputStream()).willReturn(this.out); } @Test public void printWriterHashCode() throws Exception { givenGetWriterThenReturn(); int expected = this.writer.hashCode(); assertThat(this.response.getWriter().hashCode()).isEqualTo(expected); } @Test public void printWriterCheckError() throws Exception { givenGetWriterThenReturn(); boolean expected = true; given(this.writer.checkError()).willReturn(expected); assertThat(this.response.getWriter().checkError()).isEqualTo(expected); } @Test public void printWriterWriteInt() throws Exception { givenGetWriterThenReturn(); int expected = 1; this.response.getWriter().write(expected); verify(this.writer).write(expected); } @Test public void printWriterWriteCharIntInt() throws Exception { givenGetWriterThenReturn(); char[] buff = new char[0]; int off = 2; int len = 3; this.response.getWriter().write(buff, off, len); verify(this.writer).write(buff, off, len); } @Test public void printWriterWriteChar() throws Exception { givenGetWriterThenReturn(); char[] buff = new char[0]; this.response.getWriter().write(buff); verify(this.writer).write(buff); } @Test public void printWriterWriteStringIntInt() throws Exception { givenGetWriterThenReturn(); String s = ""; int off = 2; int len = 3; this.response.getWriter().write(s, off, len); verify(this.writer).write(s, off, len); } @Test public void printWriterWriteString() throws Exception { givenGetWriterThenReturn(); String s = ""; this.response.getWriter().write(s); verify(this.writer).write(s); } @Test public void printWriterPrintBoolean() throws Exception { givenGetWriterThenReturn(); boolean b = true; this.response.getWriter().print(b); verify(this.writer).print(b); } @Test public void printWriterPrintChar() throws Exception { givenGetWriterThenReturn(); char c = 1; this.response.getWriter().print(c); verify(this.writer).print(c); } @Test public void printWriterPrintInt() throws Exception { givenGetWriterThenReturn(); int i = 1; this.response.getWriter().print(i); verify(this.writer).print(i); } @Test public void printWriterPrintLong() throws Exception { givenGetWriterThenReturn(); long l = 1; this.response.getWriter().print(l); verify(this.writer).print(l); } @Test public void printWriterPrintFloat() throws Exception { givenGetWriterThenReturn(); float f = 1; this.response.getWriter().print(f); verify(this.writer).print(f); } @Test public void printWriterPrintDouble() throws Exception { givenGetWriterThenReturn(); double x = 1; this.response.getWriter().print(x); verify(this.writer).print(x); } @Test public void printWriterPrintCharArray() throws Exception { givenGetWriterThenReturn(); char[] x = new char[0]; this.response.getWriter().print(x); verify(this.writer).print(x); } @Test public void printWriterPrintString() throws Exception { givenGetWriterThenReturn(); String x = "1"; this.response.getWriter().print(x); verify(this.writer).print(x); } @Test public void printWriterPrintObject() throws Exception { givenGetWriterThenReturn(); Object x = "1"; this.response.getWriter().print(x); verify(this.writer).print(x); } @Test public void printWriterPrintln() throws Exception { givenGetWriterThenReturn(); this.response.getWriter().println(); verify(this.writer).println(); } @Test public void printWriterPrintlnBoolean() throws Exception { givenGetWriterThenReturn(); boolean b = true; this.response.getWriter().println(b); verify(this.writer).println(b); } @Test public void printWriterPrintlnChar() throws Exception { givenGetWriterThenReturn(); char c = 1; this.response.getWriter().println(c); verify(this.writer).println(c); } @Test public void printWriterPrintlnInt() throws Exception { givenGetWriterThenReturn(); int i = 1; this.response.getWriter().println(i); verify(this.writer).println(i); } @Test public void printWriterPrintlnLong() throws Exception { givenGetWriterThenReturn(); long l = 1; this.response.getWriter().println(l); verify(this.writer).println(l); } @Test public void printWriterPrintlnFloat() throws Exception { givenGetWriterThenReturn(); float f = 1; this.response.getWriter().println(f); verify(this.writer).println(f); } @Test public void printWriterPrintlnDouble() throws Exception { givenGetWriterThenReturn(); double x = 1; this.response.getWriter().println(x); verify(this.writer).println(x); } @Test public void printWriterPrintlnCharArray() throws Exception { givenGetWriterThenReturn(); char[] x = new char[0]; this.response.getWriter().println(x); verify(this.writer).println(x); } @Test public void printWriterPrintlnString() throws Exception { givenGetWriterThenReturn(); String x = "1"; this.response.getWriter().println(x); verify(this.writer).println(x); } @Test public void printWriterPrintlnObject() throws Exception { givenGetWriterThenReturn(); Object x = "1"; this.response.getWriter().println(x); verify(this.writer).println(x); } @Test public void printWriterPrintfStringObjectVargs() throws Exception { givenGetWriterThenReturn(); String format = "format"; Object[] args = new Object[] { "1" }; this.response.getWriter().printf(format, args); verify(this.writer).printf(format, args); } @Test public void printWriterPrintfLocaleStringObjectVargs() throws Exception { givenGetWriterThenReturn(); Locale l = Locale.US; String format = "format"; Object[] args = new Object[] { "1" }; this.response.getWriter().printf(l, format, args); verify(this.writer).printf(l, format, args); } @Test public void printWriterFormatStringObjectVargs() throws Exception { givenGetWriterThenReturn(); String format = "format"; Object[] args = new Object[] { "1" }; this.response.getWriter().format(format, args); verify(this.writer).format(format, args); } @Test public void printWriterFormatLocaleStringObjectVargs() throws Exception { givenGetWriterThenReturn(); Locale l = Locale.US; String format = "format"; Object[] args = new Object[] { "1" }; this.response.getWriter().format(l, format, args); verify(this.writer).format(l, format, args); } @Test public void printWriterAppendCharSequence() throws Exception { givenGetWriterThenReturn(); String x = "a"; this.response.getWriter().append(x); verify(this.writer).append(x); } @Test public void printWriterAppendCharSequenceIntInt() throws Exception { givenGetWriterThenReturn(); String x = "abcdef"; int start = 1; int end = 3; this.response.getWriter().append(x, start, end); verify(this.writer).append(x, start, end); } @Test public void printWriterAppendChar() throws Exception { givenGetWriterThenReturn(); char x = 1; this.response.getWriter().append(x); verify(this.writer).append(x); } // servletoutputstream @Test public void outputStreamHashCode() throws Exception { givenGetOutputStreamThenReturn(); int expected = this.out.hashCode(); assertThat(this.response.getOutputStream().hashCode()).isEqualTo(expected); } @Test public void outputStreamWriteInt() throws Exception { givenGetOutputStreamThenReturn(); int expected = 1; this.response.getOutputStream().write(expected); verify(this.out).write(expected); } @Test public void outputStreamWriteByte() throws Exception { givenGetOutputStreamThenReturn(); byte[] expected = new byte[0]; this.response.getOutputStream().write(expected); verify(this.out).write(expected); } @Test public void outputStreamWriteByteIntInt() throws Exception { givenGetOutputStreamThenReturn(); int start = 1; int end = 2; byte[] expected = new byte[0]; this.response.getOutputStream().write(expected, start, end); verify(this.out).write(expected, start, end); } @Test public void outputStreamPrintBoolean() throws Exception { givenGetOutputStreamThenReturn(); boolean b = true; this.response.getOutputStream().print(b); verify(this.out).print(b); } @Test public void outputStreamPrintChar() throws Exception { givenGetOutputStreamThenReturn(); char c = 1; this.response.getOutputStream().print(c); verify(this.out).print(c); } @Test public void outputStreamPrintInt() throws Exception { givenGetOutputStreamThenReturn(); int i = 1; this.response.getOutputStream().print(i); verify(this.out).print(i); } @Test public void outputStreamPrintLong() throws Exception { givenGetOutputStreamThenReturn(); long l = 1; this.response.getOutputStream().print(l); verify(this.out).print(l); } @Test public void outputStreamPrintFloat() throws Exception { givenGetOutputStreamThenReturn(); float f = 1; this.response.getOutputStream().print(f); verify(this.out).print(f); } @Test public void outputStreamPrintDouble() throws Exception { givenGetOutputStreamThenReturn(); double x = 1; this.response.getOutputStream().print(x); verify(this.out).print(x); } @Test public void outputStreamPrintString() throws Exception { givenGetOutputStreamThenReturn(); String x = "1"; this.response.getOutputStream().print(x); verify(this.out).print(x); } @Test public void outputStreamPrintln() throws Exception { givenGetOutputStreamThenReturn(); this.response.getOutputStream().println(); verify(this.out).println(); } @Test public void outputStreamPrintlnBoolean() throws Exception { givenGetOutputStreamThenReturn(); boolean b = true; this.response.getOutputStream().println(b); verify(this.out).println(b); } @Test public void outputStreamPrintlnChar() throws Exception { givenGetOutputStreamThenReturn(); char c = 1; this.response.getOutputStream().println(c); verify(this.out).println(c); } @Test public void outputStreamPrintlnInt() throws Exception { givenGetOutputStreamThenReturn(); int i = 1; this.response.getOutputStream().println(i); verify(this.out).println(i); } @Test public void outputStreamPrintlnLong() throws Exception { givenGetOutputStreamThenReturn(); long l = 1; this.response.getOutputStream().println(l); verify(this.out).println(l); } @Test public void outputStreamPrintlnFloat() throws Exception { givenGetOutputStreamThenReturn(); float f = 1; this.response.getOutputStream().println(f); verify(this.out).println(f); } @Test public void outputStreamPrintlnDouble() throws Exception { givenGetOutputStreamThenReturn(); double x = 1; this.response.getOutputStream().println(x); verify(this.out).println(x); } @Test public void outputStreamPrintlnString() throws Exception { givenGetOutputStreamThenReturn(); String x = "1"; this.response.getOutputStream().println(x); verify(this.out).println(x); } // The amount of content specified in the setContentLength method of the response // has been greater than zero and has been written to the response. // gh-3823 @Test public void contentLengthPrintWriterWriteNullCommits() throws Exception { givenGetWriterThenReturn(); String expected = null; this.response.setContentLength(String.valueOf(expected).length() + 1); this.response.getWriter().write(expected); assertThat(this.committed).isFalse(); this.response.getWriter().write("a"); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteIntCommits() throws Exception { givenGetWriterThenReturn(); int expected = 1; this.response.setContentLength(String.valueOf(expected).length()); this.response.getWriter().write(expected); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteIntMultiDigitCommits() throws Exception { givenGetWriterThenReturn(); int expected = 10000; this.response.setContentLength(String.valueOf(expected).length()); this.response.getWriter().write(expected); assertThat(this.committed).isTrue(); } @Test public void contentLengthPlus1PrintWriterWriteIntMultiDigitCommits() throws Exception { givenGetWriterThenReturn(); int expected = 10000; this.response.setContentLength(String.valueOf(expected).length() + 1); this.response.getWriter().write(expected); assertThat(this.committed).isFalse(); this.response.getWriter().write(1); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteCharIntIntCommits() throws Exception { givenGetWriterThenReturn(); char[] buff = new char[0]; int off = 2; int len = 3; this.response.setContentLength(3); this.response.getWriter().write(buff, off, len); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteCharCommits() throws Exception { givenGetWriterThenReturn(); char[] buff = new char[4]; this.response.setContentLength(buff.length); this.response.getWriter().write(buff); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteStringIntIntCommits() throws Exception { givenGetWriterThenReturn(); String s = ""; int off = 2; int len = 3; this.response.setContentLength(3); this.response.getWriter().write(s, off, len); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterWriteStringCommits() throws IOException { givenGetWriterThenReturn(); String body = "something"; this.response.setContentLength(body.length()); this.response.getWriter().write(body); assertThat(this.committed).isTrue(); } @Test public void printWriterWriteStringContentLengthCommits() throws IOException { givenGetWriterThenReturn(); String body = "something"; this.response.getWriter().write(body); this.response.setContentLength(body.length()); assertThat(this.committed).isTrue(); } @Test public void printWriterWriteStringDoesNotCommit() throws IOException { givenGetWriterThenReturn(); String body = "something"; this.response.getWriter().write(body); assertThat(this.committed).isFalse(); } @Test public void contentLengthPrintWriterPrintBooleanCommits() throws Exception { givenGetWriterThenReturn(); boolean b = true; this.response.setContentLength(1); this.response.getWriter().print(b); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintCharCommits() throws Exception { givenGetWriterThenReturn(); char c = 1; this.response.setContentLength(1); this.response.getWriter().print(c); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintIntCommits() throws Exception { givenGetWriterThenReturn(); int i = 1234; this.response.setContentLength(String.valueOf(i).length()); this.response.getWriter().print(i); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintLongCommits() throws Exception { givenGetWriterThenReturn(); long l = 12345; this.response.setContentLength(String.valueOf(l).length()); this.response.getWriter().print(l); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintFloatCommits() throws Exception { givenGetWriterThenReturn(); float f = 12345; this.response.setContentLength(String.valueOf(f).length()); this.response.getWriter().print(f); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintDoubleCommits() throws Exception { givenGetWriterThenReturn(); double x = 1.2345; this.response.setContentLength(String.valueOf(x).length()); this.response.getWriter().print(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintCharArrayCommits() throws Exception { givenGetWriterThenReturn(); char[] x = new char[10]; this.response.setContentLength(x.length); this.response.getWriter().print(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintStringCommits() throws Exception { givenGetWriterThenReturn(); String x = "12345"; this.response.setContentLength(x.length()); this.response.getWriter().print(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintObjectCommits() throws Exception { givenGetWriterThenReturn(); Object x = "12345"; this.response.setContentLength(String.valueOf(x).length()); this.response.getWriter().print(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnCommits() throws Exception { givenGetWriterThenReturn(); this.response.setContentLength(NL.length()); this.response.getWriter().println(); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnBooleanCommits() throws Exception { givenGetWriterThenReturn(); boolean b = true; this.response.setContentLength(1); this.response.getWriter().println(b); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnCharCommits() throws Exception { givenGetWriterThenReturn(); char c = 1; this.response.setContentLength(1); this.response.getWriter().println(c); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnIntCommits() throws Exception { givenGetWriterThenReturn(); int i = 12345; this.response.setContentLength(String.valueOf(i).length()); this.response.getWriter().println(i); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnLongCommits() throws Exception { givenGetWriterThenReturn(); long l = 12345678; this.response.setContentLength(String.valueOf(l).length()); this.response.getWriter().println(l); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnFloatCommits() throws Exception { givenGetWriterThenReturn(); float f = 1234; this.response.setContentLength(String.valueOf(f).length()); this.response.getWriter().println(f); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnDoubleCommits() throws Exception { givenGetWriterThenReturn(); double x = 1; this.response.setContentLength(String.valueOf(x).length()); this.response.getWriter().println(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnCharArrayCommits() throws Exception { givenGetWriterThenReturn(); char[] x = new char[20]; this.response.setContentLength(x.length); this.response.getWriter().println(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnStringCommits() throws Exception { givenGetWriterThenReturn(); String x = "1"; this.response.setContentLength(String.valueOf(x).length()); this.response.getWriter().println(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterPrintlnObjectCommits() throws Exception { givenGetWriterThenReturn(); Object x = "1"; this.response.setContentLength(String.valueOf(x).length()); this.response.getWriter().println(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterAppendCharSequenceCommits() throws Exception { givenGetWriterThenReturn(); String x = "a"; this.response.setContentLength(String.valueOf(x).length()); this.response.getWriter().append(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterAppendCharSequenceIntIntCommits() throws Exception { givenGetWriterThenReturn(); String x = "abcdef"; int start = 1; int end = 3; this.response.setContentLength(end - start); this.response.getWriter().append(x, start, end); assertThat(this.committed).isTrue(); } @Test public void contentLengthPrintWriterAppendCharCommits() throws Exception { givenGetWriterThenReturn(); char x = 1; this.response.setContentLength(1); this.response.getWriter().append(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamWriteIntCommits() throws Exception { givenGetOutputStreamThenReturn(); int expected = 1; this.response.setContentLength(String.valueOf(expected).length()); this.response.getOutputStream().write(expected); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamWriteIntMultiDigitCommits() throws Exception { givenGetOutputStreamThenReturn(); int expected = 10000; this.response.setContentLength(String.valueOf(expected).length()); this.response.getOutputStream().write(expected); assertThat(this.committed).isTrue(); } @Test public void contentLengthPlus1OutputStreamWriteIntMultiDigitCommits() throws Exception { givenGetOutputStreamThenReturn(); int expected = 10000; this.response.setContentLength(String.valueOf(expected).length() + 1); this.response.getOutputStream().write(expected); assertThat(this.committed).isFalse(); this.response.getOutputStream().write(1); assertThat(this.committed).isTrue(); } // gh-171 @Test public void contentLengthPlus1OutputStreamWriteByteArrayMultiDigitCommits() throws Exception { givenGetOutputStreamThenReturn(); String expected = "{\n" + " \"parameterName\" : \"_csrf\",\n" + " \"token\" : \"06300b65-c4aa-4c8f-8cda-39ee17f545a0\",\n" + " \"headerName\" : \"X-CSRF-TOKEN\"\n" + "}"; this.response.setContentLength(expected.length() + 1); this.response.getOutputStream().write(expected.getBytes()); assertThat(this.committed).isFalse(); this.response.getOutputStream().write("1".getBytes("UTF-8")); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintBooleanCommits() throws Exception { givenGetOutputStreamThenReturn(); boolean b = true; this.response.setContentLength(1); this.response.getOutputStream().print(b); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintCharCommits() throws Exception { givenGetOutputStreamThenReturn(); char c = 1; this.response.setContentLength(1); this.response.getOutputStream().print(c); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintIntCommits() throws Exception { givenGetOutputStreamThenReturn(); int i = 1234; this.response.setContentLength(String.valueOf(i).length()); this.response.getOutputStream().print(i); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintLongCommits() throws Exception { givenGetOutputStreamThenReturn(); long l = 12345; this.response.setContentLength(String.valueOf(l).length()); this.response.getOutputStream().print(l); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintFloatCommits() throws Exception { givenGetOutputStreamThenReturn(); float f = 12345; this.response.setContentLength(String.valueOf(f).length()); this.response.getOutputStream().print(f); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintDoubleCommits() throws Exception { givenGetOutputStreamThenReturn(); double x = 1.2345; this.response.setContentLength(String.valueOf(x).length()); this.response.getOutputStream().print(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintStringCommits() throws Exception { givenGetOutputStreamThenReturn(); String x = "12345"; this.response.setContentLength(x.length()); this.response.getOutputStream().print(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnCommits() throws Exception { givenGetOutputStreamThenReturn(); this.response.setContentLength(NL.length()); this.response.getOutputStream().println(); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnBooleanCommits() throws Exception { givenGetOutputStreamThenReturn(); boolean b = true; this.response.setContentLength(1); this.response.getOutputStream().println(b); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnCharCommits() throws Exception { givenGetOutputStreamThenReturn(); char c = 1; this.response.setContentLength(1); this.response.getOutputStream().println(c); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnIntCommits() throws Exception { givenGetOutputStreamThenReturn(); int i = 12345; this.response.setContentLength(String.valueOf(i).length()); this.response.getOutputStream().println(i); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnLongCommits() throws Exception { givenGetOutputStreamThenReturn(); long l = 12345678; this.response.setContentLength(String.valueOf(l).length()); this.response.getOutputStream().println(l); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnFloatCommits() throws Exception { givenGetOutputStreamThenReturn(); float f = 1234; this.response.setContentLength(String.valueOf(f).length()); this.response.getOutputStream().println(f); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnDoubleCommits() throws Exception { givenGetOutputStreamThenReturn(); double x = 1; this.response.setContentLength(String.valueOf(x).length()); this.response.getOutputStream().println(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthOutputStreamPrintlnStringCommits() throws Exception { givenGetOutputStreamThenReturn(); String x = "1"; this.response.setContentLength(String.valueOf(x).length()); this.response.getOutputStream().println(x); assertThat(this.committed).isTrue(); } @Test public void contentLengthDoesNotCommit() { String body = "something"; this.response.setContentLength(body.length()); assertThat(this.committed).isFalse(); } @Test public void contentLengthOutputStreamWriteStringCommits() throws IOException { givenGetOutputStreamThenReturn(); String body = "something"; this.response.setContentLength(body.length()); this.response.getOutputStream().print(body); assertThat(this.committed).isTrue(); } // gh-7261 @Test public void contentLengthLongOutputStreamWriteStringCommits() throws IOException { givenGetOutputStreamThenReturn(); String body = "something"; this.response.setContentLengthLong(body.length()); this.response.getOutputStream().print(body); assertThat(this.committed).isTrue(); } @Test public void addHeaderContentLengthPrintWriterWriteStringCommits() throws Exception { givenGetWriterThenReturn(); int expected = 1234; this.response.addHeader("Content-Length", String.valueOf(String.valueOf(expected).length())); this.response.getWriter().write(expected); assertThat(this.committed).isTrue(); } @Test public void bufferSizePrintWriterWriteCommits() throws Exception { givenGetWriterThenReturn(); String expected = "1234567890"; given(this.response.getBufferSize()).willReturn(expected.length()); this.response.getWriter().write(expected); assertThat(this.committed).isTrue(); } @Test public void bufferSizeCommitsOnce() throws Exception { givenGetWriterThenReturn(); String expected = "1234567890"; given(this.response.getBufferSize()).willReturn(expected.length()); this.response.getWriter().write(expected); assertThat(this.committed).isTrue(); this.committed = false; this.response.getWriter().write(expected); assertThat(this.committed).isFalse(); } }
29,481
27.595538
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/ThrowableAnalyzerTests.java
/* * 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. * 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; import java.lang.reflect.InvocationTargetException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Test cases for {@link ThrowableAnalyzer}. * * @author Andreas Senft */ @SuppressWarnings("unchecked") public class ThrowableAnalyzerTests { /** * An array of nested throwables for testing. The cause of element 0 is element 1, the * cause of element 1 is element 2 and so on. */ private Throwable[] testTrace; /** * Plain <code>ThrowableAnalyzer</code>. */ private ThrowableAnalyzer standardAnalyzer; /** * Enhanced <code>ThrowableAnalyzer</code> capable to process * <code>NonStandardException</code>s. */ private ThrowableAnalyzer nonstandardAnalyzer; @BeforeEach public void setUp() { // Set up test trace this.testTrace = new Throwable[7]; this.testTrace[6] = new IllegalArgumentException("Test_6"); this.testTrace[5] = new Throwable("Test_5", this.testTrace[6]); this.testTrace[4] = new InvocationTargetException(this.testTrace[5], "Test_4"); this.testTrace[3] = new Exception("Test_3", this.testTrace[4]); this.testTrace[2] = new NonStandardException("Test_2", this.testTrace[3]); this.testTrace[1] = new RuntimeException("Test_1", this.testTrace[2]); this.testTrace[0] = new Exception("Test_0", this.testTrace[1]); // Set up standard analyzer this.standardAnalyzer = new ThrowableAnalyzer(); // Set up nonstandard analyzer this.nonstandardAnalyzer = new ThrowableAnalyzer() { /** * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap() */ @Override protected void initExtractorMap() { super.initExtractorMap(); // register extractor for NonStandardException registerExtractor(NonStandardException.class, new NonStandardExceptionCauseExtractor()); } }; } @Test public void testRegisterExtractorWithInvalidExtractor() { assertThatIllegalArgumentException().isThrownBy(() -> new ThrowableAnalyzer() { @Override protected void initExtractorMap() { // null is no valid extractor super.registerExtractor(Exception.class, null); } }); } @Test public void testGetRegisteredTypes() { Class[] registeredTypes = this.nonstandardAnalyzer.getRegisteredTypes(); for (int i = 0; i < registeredTypes.length; ++i) { Class clazz = registeredTypes[i]; // The most specific types have to occur first. for (int j = 0; j < i; ++j) { Class prevClazz = registeredTypes[j]; assertThat(prevClazz.isAssignableFrom(clazz)) .withFailMessage( "Unexpected order of registered classes: " + prevClazz + " is assignable from " + clazz) .isFalse(); } } } @Test public void testDetermineCauseChainWithNoExtractors() { ThrowableAnalyzer analyzer = new ThrowableAnalyzer() { /** * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap() */ @Override protected void initExtractorMap() { // skip default initialization } }; assertThat(analyzer.getRegisteredTypes().length).withFailMessage("Unexpected number of registered types") .isZero(); Throwable t = this.testTrace[0]; Throwable[] chain = analyzer.determineCauseChain(t); // Without extractors only the root throwable is available assertThat(chain.length).as("Unexpected chain size").isEqualTo(1); assertThat(chain[0]).as("Unexpected chain entry").isEqualTo(t); } @Test public void testDetermineCauseChainWithDefaultExtractors() { ThrowableAnalyzer analyzer = this.standardAnalyzer; assertThat(analyzer.getRegisteredTypes().length).withFailMessage("Unexpected number of registered types") .isEqualTo(2); Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); // Element at index 2 is a NonStandardException which cannot be analyzed further // by default assertThat(chain.length).as("Unexpected chain size").isEqualTo(3); for (int i = 0; i < 3; ++i) { assertThat(chain[i]).withFailMessage("Unexpected chain entry: " + i).isEqualTo(this.testTrace[i]); } } @Test public void testDetermineCauseChainWithCustomExtractors() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); assertThat(chain.length).as("Unexpected chain size").isEqualTo(this.testTrace.length); for (int i = 0; i < chain.length; ++i) { assertThat(chain[i]).withFailMessage("Unexpected chain entry: " + i).isEqualTo(this.testTrace[i]); } } @Test public void testGetFirstThrowableOfTypeWithSuccess1() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); Throwable result = analyzer.getFirstThrowableOfType(Exception.class, chain); assertThat(result).as("null not expected").isNotNull(); assertThat(result).as("Unexpected throwable found").isEqualTo(this.testTrace[0]); } @Test public void testGetFirstThrowableOfTypeWithSuccess2() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); Throwable result = analyzer.getFirstThrowableOfType(NonStandardException.class, chain); assertThat(result).as("null not expected").isNotNull(); assertThat(result).as("Unexpected throwable found").isEqualTo(this.testTrace[2]); } @Test public void testGetFirstThrowableOfTypeWithFailure() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); // IllegalStateException not in trace Throwable result = analyzer.getFirstThrowableOfType(IllegalStateException.class, chain); assertThat(result).as("null expected").isNull(); } @Test public void testVerifyThrowableHierarchyWithExactType() { Throwable throwable = new IllegalStateException("Test"); ThrowableAnalyzer.verifyThrowableHierarchy(throwable, IllegalStateException.class); // No exception expected } @Test public void testVerifyThrowableHierarchyWithCompatibleType() { Throwable throwable = new IllegalStateException("Test"); ThrowableAnalyzer.verifyThrowableHierarchy(throwable, Exception.class); // No exception expected } @Test public void testVerifyThrowableHierarchyWithNull() { assertThatIllegalArgumentException() .isThrownBy(() -> ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class)); } @Test public void testVerifyThrowableHierarchyWithNonmatchingType() { Throwable throwable = new IllegalStateException("Test"); assertThatIllegalArgumentException().isThrownBy( () -> ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class)); } /** * Exception for testing purposes. The cause is not retrievable by * {@link #getCause()}. */ public static final class NonStandardException extends Exception { private final Throwable cause; public NonStandardException(String message, Throwable cause) { super(message); this.cause = cause; } public Throwable resolveCause() { return this.cause; } } /** * <code>ThrowableCauseExtractor</code> for handling <code>NonStandardException</code> * instances. */ public static final class NonStandardExceptionCauseExtractor implements ThrowableCauseExtractor { @Override public Throwable extractCause(Throwable throwable) { ThrowableAnalyzer.verifyThrowableHierarchy(throwable, NonStandardException.class); return ((NonStandardException) throwable).resolveCause(); } } }
8,272
33.470833
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java
/* * 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 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; 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 * */ @ExtendWith(MockitoExtension.class) public class OrRequestMatcherTests { @Mock private RequestMatcher delegate; @Mock private RequestMatcher delegate2; @Mock private HttpServletRequest request; private RequestMatcher matcher; @Test public void constructorNullArray() { assertThatNullPointerException().isThrownBy(() -> new OrRequestMatcher((RequestMatcher[]) null)); } @Test public void constructorListOfDoesNotThrowNullPointer() { new OrRequestMatcher(List.of(new AntPathRequestMatcher("/test"))); } @Test public void constructorArrayContainsNull() { assertThatIllegalArgumentException().isThrownBy(() -> new OrRequestMatcher((RequestMatcher) null)); } @Test public void constructorEmptyArray() { assertThatIllegalArgumentException().isThrownBy(() -> new OrRequestMatcher(new RequestMatcher[0])); } @Test public void constructorNullList() { assertThatIllegalArgumentException().isThrownBy(() -> new OrRequestMatcher((List<RequestMatcher>) null)); } @Test public void constructorListContainsNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new OrRequestMatcher(Arrays.asList((RequestMatcher) null))); } @Test public void constructorEmptyList() { assertThatIllegalArgumentException() .isThrownBy(() -> new OrRequestMatcher(Collections.<RequestMatcher>emptyList())); } @Test public void matchesSingleTrue() { given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new OrRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchesMultiTrue() { given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new OrRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchesSingleFalse() { given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new OrRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesMultiBothFalse() { given(this.delegate.matches(this.request)).willReturn(false); given(this.delegate2.matches(this.request)).willReturn(false); this.matcher = new OrRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesMultiSingleFalse() { given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new OrRequestMatcher(this.delegate, this.delegate2); 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")); } }
5,199
33.210526
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java
/* * 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. * 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 jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.util.UrlPathHelper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; /** * @author Luke Taylor * @author Rob Winch * @author Evgeniy Cheban */ @ExtendWith(MockitoExtension.class) public class AntPathRequestMatcherTests { @Mock private HttpServletRequest request; @Test public void matchesWhenUrlPathHelperThenMatchesOnRequestUri() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/foo/bar", null, true, new UrlPathHelper()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/bar"); assertThat(matcher.matches(request)).isTrue(); } @Test public void singleWildcardMatchesAnyPath() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**"); assertThat(matcher.getPattern()).isEqualTo("/**"); assertThat(matcher.matches(createRequest("/blah"))).isTrue(); matcher = new AntPathRequestMatcher("**"); assertThat(matcher.matches(createRequest("/blah"))).isTrue(); assertThat(matcher.matches(createRequest(""))).isTrue(); } @Test public void trailingWildcardMatchesCorrectly() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/blah/blAh/**", null, false); assertThat(matcher.matches(createRequest("/BLAH/blah"))).isTrue(); assertThat(matcher.matches(createRequest("/blah/bleh"))).isFalse(); assertThat(matcher.matches(createRequest("/blah/blah/"))).isTrue(); assertThat(matcher.matches(createRequest("/blah/blah/xxx"))).isTrue(); assertThat(matcher.matches(createRequest("/blah/blaha"))).isFalse(); assertThat(matcher.matches(createRequest("/blah/bleh/"))).isFalse(); MockHttpServletRequest request = createRequest("/blah/"); request.setPathInfo("blah/bleh"); assertThat(matcher.matches(request)).isTrue(); matcher = new AntPathRequestMatcher("/bl?h/blAh/**", null, false); assertThat(matcher.matches(createRequest("/BLAH/Blah/aaa/"))).isTrue(); assertThat(matcher.matches(createRequest("/bleh/Blah"))).isTrue(); matcher = new AntPathRequestMatcher("/blAh/**/blah/**", null, false); assertThat(matcher.matches(createRequest("/blah/blah"))).isTrue(); assertThat(matcher.matches(createRequest("/blah/bleh"))).isFalse(); assertThat(matcher.matches(createRequest("/blah/aaa/blah/bbb"))).isTrue(); } @Test public void trailingWildcardWithVariableMatchesCorrectly() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/{id}/blAh/**", null, false); assertThat(matcher.matches(createRequest("/1234/blah"))).isTrue(); assertThat(matcher.matches(createRequest("/4567/bleh"))).isFalse(); assertThat(matcher.matches(createRequest("/paskos/blah/"))).isTrue(); assertThat(matcher.matches(createRequest("/12345/blah/xxx"))).isTrue(); assertThat(matcher.matches(createRequest("/12345/blaha"))).isFalse(); assertThat(matcher.matches(createRequest("/paskos/bleh/"))).isFalse(); } @Test public void nontrailingWildcardWithVariableMatchesCorrectly() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**/{id}"); assertThat(matcher.matches(createRequest("/blah/1234"))).isTrue(); assertThat(matcher.matches(createRequest("/bleh/4567"))).isTrue(); assertThat(matcher.matches(createRequest("/paskos/blah/"))).isFalse(); assertThat(matcher.matches(createRequest("/12345/blah/xxx"))).isTrue(); assertThat(matcher.matches(createRequest("/12345/blaha"))).isTrue(); assertThat(matcher.matches(createRequest("/paskos/bleh/"))).isFalse(); } @Test public void requestHasNullMethodMatches() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*", "GET"); HttpServletRequest request = createRequestWithNullMethod("/something/here"); assertThat(matcher.matches(request)).isTrue(); } // SEC-2084 @Test public void requestHasNullMethodNoMatch() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*", "GET"); HttpServletRequest request = createRequestWithNullMethod("/nomatch"); assertThat(matcher.matches(request)).isFalse(); } @Test public void requestHasNullMethodAndNullMatcherMatches() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*"); MockHttpServletRequest request = createRequest("/something/here"); request.setMethod(null); assertThat(matcher.matches(request)).isTrue(); } @Test public void requestHasNullMethodAndNullMatcherNoMatch() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/something/*"); MockHttpServletRequest request = createRequest("/nomatch"); request.setMethod(null); assertThat(matcher.matches(request)).isFalse(); } @Test public void exactMatchOnlyMatchesIdenticalPath() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/login.html"); assertThat(matcher.matches(createRequest("/login.html"))).isTrue(); assertThat(matcher.matches(createRequest("/login.html/"))).isFalse(); assertThat(matcher.matches(createRequest("/login.html/blah"))).isFalse(); } @Test public void httpMethodSpecificMatchOnlyMatchesRequestsWithCorrectMethod() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/blah", "GET"); MockHttpServletRequest request = createRequest("/blah"); request.setMethod("GET"); assertThat(matcher.matches(request)).isTrue(); request.setMethod("POST"); assertThat(matcher.matches(request)).isFalse(); } @Test public void caseSensitive() { MockHttpServletRequest request = createRequest("/UPPER"); assertThat(new AntPathRequestMatcher("/upper", null, true).matches(request)).isFalse(); assertThat(new AntPathRequestMatcher("/upper", "POST", true).matches(request)).isFalse(); assertThat(new AntPathRequestMatcher("/upper", "GET", true).matches(request)).isFalse(); assertThat(new AntPathRequestMatcher("/upper", null, false).matches(request)).isTrue(); assertThat(new AntPathRequestMatcher("/upper", "POST", false).matches(request)).isTrue(); } @Test public void spacesInPathSegmentsAreNotIgnored() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/path/*/bar"); MockHttpServletRequest request = createRequest("/path /foo/bar"); assertThat(matcher.matches(request)).isFalse(); matcher = new AntPathRequestMatcher("/path/foo"); request = createRequest("/path /foo"); assertThat(matcher.matches(request)).isFalse(); } @Test public void equalsBehavesCorrectly() { // Both universal wildcard options should be equal assertThat(new AntPathRequestMatcher("**")).isEqualTo(new AntPathRequestMatcher("/**")); assertThat(new AntPathRequestMatcher("/xyz")).isEqualTo(new AntPathRequestMatcher("/xyz")); assertThat(new AntPathRequestMatcher("/xyz", "POST")).isEqualTo(new AntPathRequestMatcher("/xyz", "POST")); assertThat(new AntPathRequestMatcher("/xyz", "POST")).isNotEqualTo(new AntPathRequestMatcher("/xyz", "GET")); assertThat(new AntPathRequestMatcher("/xyz")).isNotEqualTo(new AntPathRequestMatcher("/xxx")); assertThat(new AntPathRequestMatcher("/xyz").equals(AnyRequestMatcher.INSTANCE)).isFalse(); assertThat(new AntPathRequestMatcher("/xyz", "GET", false)) .isNotEqualTo(new AntPathRequestMatcher("/xyz", "GET", true)); } @Test public void toStringIsOk() { new AntPathRequestMatcher("/blah").toString(); new AntPathRequestMatcher("/blah", "GET").toString(); } // SEC-2831 @Test public void matchesWithInvalidMethod() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/blah", "GET"); MockHttpServletRequest request = createRequest("/blah"); request.setMethod("INVALID"); assertThat(matcher.matches(request)).isFalse(); } // gh-9285 @Test public void matcherWhenMatchAllPatternThenMatchResult() { AntPathRequestMatcher matcher = new AntPathRequestMatcher("/**"); MockHttpServletRequest request = createRequest("/blah"); assertThat(matcher.matcher(request).isMatch()).isTrue(); } @Test public void staticAntMatcherWhenPatternProvidedThenPattern() { AntPathRequestMatcher matcher = antMatcher("/path"); assertThat(matcher.getPattern()).isEqualTo("/path"); } @Test public void staticAntMatcherWhenMethodProvidedThenMatchAll() { AntPathRequestMatcher matcher = antMatcher(HttpMethod.GET); assertThat(ReflectionTestUtils.getField(matcher, "httpMethod")).isEqualTo(HttpMethod.GET); } @Test public void staticAntMatcherWhenMethodAndPatternProvidedThenMatchAll() { AntPathRequestMatcher matcher = antMatcher(HttpMethod.POST, "/path"); assertThat(matcher.getPattern()).isEqualTo("/path"); assertThat(ReflectionTestUtils.getField(matcher, "httpMethod")).isEqualTo(HttpMethod.POST); } @Test public void staticAntMatcherWhenMethodNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> antMatcher((HttpMethod) null)) .withMessage("method cannot be null"); } @Test public void staticAntMatcherWhenPatternNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> antMatcher((String) null)) .withMessage("pattern cannot be empty"); } @Test public void forMethodWhenMethodThenMatches() { AntPathRequestMatcher matcher = antMatcher(HttpMethod.POST); MockHttpServletRequest request = createRequest("/path"); assertThat(matcher.matches(request)).isTrue(); request.setServletPath("/another-path/second"); assertThat(matcher.matches(request)).isTrue(); request.setMethod("GET"); assertThat(matcher.matches(request)).isFalse(); } private HttpServletRequest createRequestWithNullMethod(String path) { given(this.request.getServletPath()).willReturn(path); return this.request; } private MockHttpServletRequest createRequest(String path) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("doesntMatter"); request.setServletPath(path); request.setMethod("POST"); return request; } }
10,983
40.138577
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/RequestMatchersTests.java
/* * 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(); } }
2,435
27
78
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java
/* * Copyright 2002-2019 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.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Luke Taylor */ public class IpAddressMatcherTests { final IpAddressMatcher v6matcher = new IpAddressMatcher("fe80::21f:5bff:fe33:bd68"); final IpAddressMatcher v4matcher = new IpAddressMatcher("192.168.1.104"); MockHttpServletRequest ipv4Request = new MockHttpServletRequest(); MockHttpServletRequest ipv6Request = new MockHttpServletRequest(); @BeforeEach public void setup() { this.ipv6Request.setRemoteAddr("fe80::21f:5bff:fe33:bd68"); this.ipv4Request.setRemoteAddr("192.168.1.104"); } @Test public void ipv6MatcherMatchesIpv6Address() { assertThat(this.v6matcher.matches(this.ipv6Request)).isTrue(); } @Test public void ipv6MatcherDoesntMatchIpv4Address() { assertThat(this.v6matcher.matches(this.ipv4Request)).isFalse(); } @Test public void ipv4MatcherMatchesIpv4Address() { assertThat(this.v4matcher.matches(this.ipv4Request)).isTrue(); } @Test public void ipv4SubnetMatchesCorrectly() { IpAddressMatcher matcher = new IpAddressMatcher("192.168.1.0/24"); assertThat(matcher.matches(this.ipv4Request)).isTrue(); matcher = new IpAddressMatcher("192.168.1.128/25"); assertThat(matcher.matches(this.ipv4Request)).isFalse(); this.ipv4Request.setRemoteAddr("192.168.1.159"); // 159 = 0x9f assertThat(matcher.matches(this.ipv4Request)).isTrue(); } @Test public void ipv6RangeMatches() { IpAddressMatcher matcher = new IpAddressMatcher("2001:DB8::/48"); assertThat(matcher.matches("2001:DB8:0:0:0:0:0:0")).isTrue(); assertThat(matcher.matches("2001:DB8:0:0:0:0:0:1")).isTrue(); assertThat(matcher.matches("2001:DB8:0:FFFF:FFFF:FFFF:FFFF:FFFF")).isTrue(); assertThat(matcher.matches("2001:DB8:1:0:0:0:0:0")).isFalse(); } // SEC-1733 @Test public void zeroMaskMatchesAnything() { IpAddressMatcher matcher = new IpAddressMatcher("0.0.0.0/0"); assertThat(matcher.matches("123.4.5.6")).isTrue(); assertThat(matcher.matches("192.168.0.159")).isTrue(); matcher = new IpAddressMatcher("192.168.0.159/0"); assertThat(matcher.matches("123.4.5.6")).isTrue(); assertThat(matcher.matches("192.168.0.159")).isTrue(); } // SEC-2576 @Test public void ipv4RequiredAddressMaskTooLongThenIllegalArgumentException() { String ipv4AddressWithTooLongMask = "192.168.1.104/33"; assertThatIllegalArgumentException().isThrownBy(() -> new IpAddressMatcher(ipv4AddressWithTooLongMask)) .withMessage(String.format("IP address %s is too short for bitmask of length %d", "192.168.1.104", 33)); } // SEC-2576 @Test public void ipv6RequiredAddressMaskTooLongThenIllegalArgumentException() { String ipv6AddressWithTooLongMask = "fe80::21f:5bff:fe33:bd68/129"; assertThatIllegalArgumentException().isThrownBy(() -> new IpAddressMatcher(ipv6AddressWithTooLongMask)) .withMessage(String.format("IP address %s is too short for bitmask of length %d", "fe80::21f:5bff:fe33:bd68", 129)); } }
3,838
34.220183
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/RequestMatcherEntryTests.java
/* * Copyright 2002-2021 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; import static org.mockito.Mockito.mock; class RequestMatcherEntryTests { @Test void constructWhenGetRequestMatcherAndEntryThenSameRequestMatcherAndEntry() { RequestMatcher requestMatcher = mock(RequestMatcher.class); RequestMatcherEntry<String> entry = new RequestMatcherEntry<>(requestMatcher, "entry"); assertThat(entry.getRequestMatcher()).isSameAs(requestMatcher); assertThat(entry.getEntry()).isEqualTo("entry"); } @Test void constructWhenNullValuesThenNullValues() { RequestMatcherEntry<String> entry = new RequestMatcherEntry<>(null, null); assertThat(entry.getRequestMatcher()).isNull(); assertThat(entry.getEntry()).isNull(); } }
1,436
33.214286
89
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java
/* * 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 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; 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; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class AndRequestMatcherTests { @Mock private RequestMatcher delegate; @Mock private RequestMatcher delegate2; @Mock private HttpServletRequest request; private RequestMatcher matcher; @Test public void constructorNullArray() { assertThatNullPointerException().isThrownBy(() -> new AndRequestMatcher((RequestMatcher[]) null)); } @Test public void constructorListOfDoesNotThrowNullPointer() { new AndRequestMatcher(List.of(new AntPathRequestMatcher("/test"))); } @Test public void constructorArrayContainsNull() { assertThatIllegalArgumentException().isThrownBy(() -> new AndRequestMatcher((RequestMatcher) null)); } @Test public void constructorEmptyArray() { assertThatIllegalArgumentException().isThrownBy(() -> new AndRequestMatcher(new RequestMatcher[0])); } @Test public void constructorNullList() { assertThatIllegalArgumentException().isThrownBy(() -> new AndRequestMatcher((List<RequestMatcher>) null)); } @Test public void constructorListContainsNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new AndRequestMatcher(Arrays.asList((RequestMatcher) null))); } @Test public void constructorEmptyList() { assertThatIllegalArgumentException() .isThrownBy(() -> new AndRequestMatcher(Collections.<RequestMatcher>emptyList())); } @Test public void matchesSingleTrue() { given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new AndRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchesMultiTrue() { given(this.delegate.matches(this.request)).willReturn(true); given(this.delegate2.matches(this.request)).willReturn(true); this.matcher = new AndRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchesSingleFalse() { given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new AndRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesMultiBothFalse() { given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new AndRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesMultiSingleFalse() { given(this.delegate.matches(this.request)).willReturn(true); given(this.delegate2.matches(this.request)).willReturn(false); this.matcher = new AndRequestMatcher(this.delegate, this.delegate2); 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")); } }
5,528
34.442308
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java
/* * 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. * 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 jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher; /** * @author Luke Taylor * @author Rob Winch */ @ExtendWith(MockitoExtension.class) public class RegexRequestMatcherTests { @Mock private HttpServletRequest request; @Test public void doesntMatchIfHttpMethodIsDifferent() { RegexRequestMatcher matcher = new RegexRequestMatcher(".*", "GET"); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/anything"); assertThat(matcher.matches(request)).isFalse(); } @Test public void matchesIfHttpMethodAndPathMatch() { RegexRequestMatcher matcher = new RegexRequestMatcher(".*", "GET"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/anything"); request.setServletPath("/anything"); assertThat(matcher.matches(request)).isTrue(); } @Test public void queryStringIsMatcherCorrectly() { RegexRequestMatcher matcher = new RegexRequestMatcher(".*\\?x=y", "GET"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/any/path?x=y"); request.setServletPath("/any"); request.setPathInfo("/path"); request.setQueryString("x=y"); assertThat(matcher.matches(request)).isTrue(); } @Test public void requestHasNullMethodMatches() { RegexRequestMatcher matcher = new RegexRequestMatcher("/something/.*", "GET"); HttpServletRequest request = createRequestWithNullMethod("/something/here"); assertThat(matcher.matches(request)).isTrue(); } // SEC-2084 @Test public void requestHasNullMethodNoMatch() { RegexRequestMatcher matcher = new RegexRequestMatcher("/something/.*", "GET"); HttpServletRequest request = createRequestWithNullMethod("/nomatch"); assertThat(matcher.matches(request)).isFalse(); } @Test public void requestHasNullMethodAndNullMatcherMatches() { RegexRequestMatcher matcher = new RegexRequestMatcher("/something/.*", null); HttpServletRequest request = createRequestWithNullMethod("/something/here"); assertThat(matcher.matches(request)).isTrue(); } @Test public void requestHasNullMethodAndNullMatcherNoMatch() { RegexRequestMatcher matcher = new RegexRequestMatcher("/something/.*", null); HttpServletRequest request = createRequestWithNullMethod("/nomatch"); assertThat(matcher.matches(request)).isFalse(); } // SEC-2831 @Test public void matchesWithInvalidMethod() { RegexRequestMatcher matcher = new RegexRequestMatcher("/blah", "GET"); MockHttpServletRequest request = new MockHttpServletRequest("INVALID", "/blah"); request.setMethod("INVALID"); assertThat(matcher.matches(request)).isFalse(); } @Test public void matchesWithCarriageReturn() { RegexRequestMatcher matcher = new RegexRequestMatcher(".*", null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/blah%0a"); request.setServletPath("/blah\n"); assertThat(matcher.matches(request)).isTrue(); } @Test public void matchesWithLineFeed() { RegexRequestMatcher matcher = new RegexRequestMatcher(".*", null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/blah%0d"); request.setServletPath("/blah\r"); assertThat(matcher.matches(request)).isTrue(); } @Test public void toStringThenFormatted() { RegexRequestMatcher matcher = new RegexRequestMatcher("/blah", "GET"); assertThat(matcher.toString()).isEqualTo("Regex [pattern='/blah', GET]"); } @Test public void matchesWhenRequestUriMatchesThenMatchesTrue() { RegexRequestMatcher matcher = regexMatcher(".*"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something/anything"); assertThat(matcher.matches(request)).isTrue(); } @Test public void matchesWhenRequestUriDontMatchThenMatchesFalse() { RegexRequestMatcher matcher = regexMatcher(".*\\?param=value"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something/anything"); assertThat(matcher.matches(request)).isFalse(); } @Test public void matchesWhenRequestMethodMatchesThenMatchesTrue() { RegexRequestMatcher matcher = regexMatcher(HttpMethod.GET); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something/anything"); assertThat(matcher.matches(request)).isTrue(); } @Test public void matchesWhenRequestMethodDontMatchThenMatchesFalse() { RegexRequestMatcher matcher = regexMatcher(HttpMethod.POST); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something/anything"); assertThat(matcher.matches(request)).isFalse(); } @Test public void staticRegexMatcherWhenNoPatternThenException() { assertThatIllegalArgumentException().isThrownBy(() -> regexMatcher((String) null)) .withMessage("pattern cannot be empty"); } @Test public void staticRegexMatcherNoMethodThenException() { assertThatIllegalArgumentException().isThrownBy(() -> regexMatcher((HttpMethod) null)) .withMessage("method cannot be null"); } private HttpServletRequest createRequestWithNullMethod(String path) { given(this.request.getQueryString()).willReturn("doesntMatter"); given(this.request.getServletPath()).willReturn(path); return this.request; } }
6,291
34.954286
93
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/RequestHeaderRequestMatcherTests.java
/* * Copyright 2002-2013 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.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * */ public class RequestHeaderRequestMatcherTests { private final String headerName = "headerName"; private final String headerValue = "headerValue"; private MockHttpServletRequest request; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); } @Test public void constructorNullHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new RequestHeaderRequestMatcher(null)); } @Test public void constructorNullHeaderNameNonNullHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new RequestHeaderRequestMatcher(null, "v")); } @Test public void matchesHeaderNameMatches() { this.request.addHeader(this.headerName, this.headerValue); assertThat(new RequestHeaderRequestMatcher(this.headerName).matches(this.request)).isTrue(); } @Test public void matchesHeaderNameDoesNotMatch() { this.request.addHeader(this.headerName + "notMatch", this.headerValue); assertThat(new RequestHeaderRequestMatcher(this.headerName).matches(this.request)).isFalse(); } @Test public void matchesHeaderNameValueMatches() { this.request.addHeader(this.headerName, this.headerValue); assertThat(new RequestHeaderRequestMatcher(this.headerName, this.headerValue).matches(this.request)).isTrue(); } @Test public void matchesHeaderNameValueHeaderNameNotMatch() { this.request.addHeader(this.headerName + "notMatch", this.headerValue); assertThat(new RequestHeaderRequestMatcher(this.headerName, this.headerValue).matches(this.request)).isFalse(); } @Test public void matchesHeaderNameValueHeaderValueNotMatch() { this.request.addHeader(this.headerName, this.headerValue + "notMatch"); assertThat(new RequestHeaderRequestMatcher(this.headerName, this.headerValue).matches(this.request)).isFalse(); } @Test public void matchesHeaderNameValueHeaderValueMultiNotMatch() { this.request.addHeader(this.headerName, this.headerValue + "notMatch"); this.request.addHeader(this.headerName, this.headerValue); assertThat(new RequestHeaderRequestMatcher(this.headerName, this.headerValue).matches(this.request)).isFalse(); } }
3,103
32.73913
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcherTests.java
/* * Copyright 2002-2021 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 java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.accept.ContentNegotiationStrategy; import org.springframework.web.context.request.NativeWebRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @author Dan Zheng */ @ExtendWith(MockitoExtension.class) public class MediaTypeRequestMatcherTests { private MediaTypeRequestMatcher matcher; private MockHttpServletRequest request; @Mock private ContentNegotiationStrategy negotiationStrategy; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); } @Test public void constructorWhenNullCNSThenIAE() { ContentNegotiationStrategy c = null; assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeRequestMatcher(c, MediaType.ALL)); } @Test public void constructorNullCNSSet() { assertThatIllegalArgumentException() .isThrownBy(() -> new MediaTypeRequestMatcher(null, Collections.singleton(MediaType.ALL))); } @Test public void constructorNoVarargs() { assertThatIllegalArgumentException().isThrownBy(() -> new MediaTypeRequestMatcher(this.negotiationStrategy)); } @Test public void constructorNullMediaTypes() { Collection<MediaType> mediaTypes = null; assertThatIllegalArgumentException() .isThrownBy(() -> new MediaTypeRequestMatcher(this.negotiationStrategy, mediaTypes)); } @Test public void constructorEmptyMediaTypes() { assertThatIllegalArgumentException().isThrownBy( () -> new MediaTypeRequestMatcher(this.negotiationStrategy, Collections.<MediaType>emptyList())); } @Test public void constructorWhenEmptyMediaTypeThenIAE() { assertThatIllegalArgumentException().isThrownBy(MediaTypeRequestMatcher::new); } @Test public void constructorWhenEmptyMediaTypeCollectionThenIAE() { assertThatIllegalArgumentException() .isThrownBy(() -> new MediaTypeRequestMatcher(Collections.<MediaType>emptyList())); } @Test public void negotiationStrategyThrowsHMTNAE() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willThrow(new HttpMediaTypeNotAcceptableException("oops")); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.ALL); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void mediaAllMatches() throws Exception { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.ALL)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); assertThat(this.matcher.matches(this.request)).isTrue(); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_XHTML_XML); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenAcceptHeaderAsteriskThenAll() { this.request.addHeader("Accept", "*/*"); this.matcher = new MediaTypeRequestMatcher(MediaType.ALL); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenAcceptHeaderAsteriskThenAnyone() { this.request.addHeader("Accept", "*/*"); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenAcceptHeaderAsteriskThenAllInCollection() { this.request.addHeader("Accept", "*/*"); this.matcher = new MediaTypeRequestMatcher(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenAcceptHeaderAsteriskThenAnyoneInCollection() { this.request.addHeader("Accept", "*/*"); this.matcher = new MediaTypeRequestMatcher(Collections.singleton(MediaType.TEXT_HTML)); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenNoAcceptHeaderThenAll() { this.request.removeHeader("Accept"); // if not set Accept, it is match all this.matcher = new MediaTypeRequestMatcher(MediaType.ALL); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenNoAcceptHeaderThenAnyone() { this.request.removeHeader("Accept"); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenSingleAcceptHeaderThenOne() { this.request.addHeader("Accept", "text/html"); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenSingleAcceptHeaderThenOneWithCollection() { this.request.addHeader("Accept", "text/html"); this.matcher = new MediaTypeRequestMatcher(Collections.singleton(MediaType.TEXT_HTML)); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenMultipleAcceptHeaderThenMatchMultiple() { this.request.addHeader("Accept", "text/html, application/xhtml+xml, application/xml;q=0.9"); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenMultipleAcceptHeaderThenAnyoneInCollection() { this.request.addHeader("Accept", "text/html, application/xhtml+xml, application/xml;q=0.9"); this.matcher = new MediaTypeRequestMatcher(Arrays.asList(MediaType.APPLICATION_XHTML_XML)); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void multipleMediaType() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_XHTML_XML, MediaType.TEXT_HTML)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_ATOM_XML, MediaType.TEXT_HTML); assertThat(this.matcher.matches(this.request)).isTrue(); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_JSON); assertThat(this.matcher.matches(this.request)).isTrue(); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void resolveTextPlainMatchesTextAll() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "*")); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenAcceptHeaderIsTextThenMediaTypeAllIsMatched() { this.request.addHeader("Accept", MediaType.TEXT_PLAIN_VALUE); this.matcher = new MediaTypeRequestMatcher(new MediaType("text", "*")); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void resolveTextAllMatchesTextPlain() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(new MediaType("text", "*"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchWhenAcceptHeaderIsTextWildcardThenMediaTypeTextIsMatched() { this.request.addHeader("Accept", "text/*"); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_PLAIN); assertThat(this.matcher.matches(this.request)).isTrue(); } // useEquals @Test public void useEqualsResolveTextAllMatchesTextPlain() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(new MediaType("text", "*"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void useEqualsWhenTrueThenMediaTypeTextIsNotMatched() { this.request.addHeader("Accept", "text/*"); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_PLAIN); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void useEqualsResolveTextPlainMatchesTextAll() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "*")); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void useEqualsWhenTrueThenMediaTypeTextAllIsNotMatched() { this.request.addHeader("Accept", MediaType.TEXT_PLAIN_VALUE); this.matcher = new MediaTypeRequestMatcher(new MediaType("text", "*")); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void useEqualsSame() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void useEqualsWhenTrueThenMediaTypeIsMatchedWithEqualString() { this.request.addHeader("Accept", MediaType.TEXT_PLAIN_VALUE); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_PLAIN); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void useEqualsWithCustomMediaType() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(new MediaType("text", "unique"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "unique")); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void useEqualsWhenTrueThenCustomMediaTypeIsMatched() { this.request.addHeader("Accept", "text/unique"); this.matcher = new MediaTypeRequestMatcher(new MediaType("text", "unique")); this.matcher.setUseEquals(true); assertThat(this.matcher.matches(this.request)).isTrue(); } // ignoreMediaTypeAll @Test public void mediaAllIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.ALL)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void ignoredMediaTypesWhenAllThenAnyoneIsNotMatched() { this.request.addHeader("Accept", MediaType.ALL_VALUE); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void mediaAllAndTextHtmlIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.ALL, MediaType.TEXT_HTML)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void ignoredMediaTypesWhenAllAndTextThenTextCanBeMatched() { this.request.addHeader("Accept", MediaType.ALL_VALUE + ", " + MediaType.TEXT_HTML_VALUE); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void mediaAllQ08AndTextPlainIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException { given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) .willReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.parseMediaType("*/*;q=0.8"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void ignoredMediaTypesWhenAllThenQ08WithTextIsNotMatched() { this.request.addHeader("Accept", MediaType.TEXT_PLAIN + ", */*;q=0.8"); this.matcher = new MediaTypeRequestMatcher(MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isFalse(); } }
14,479
39.560224
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java
/* * 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. * 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 jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class NegatedRequestMatcherTests { @Mock private RequestMatcher delegate; @Mock private HttpServletRequest request; private RequestMatcher matcher; @Test public void constructorNull() { assertThatIllegalArgumentException().isThrownBy(() -> new NegatedRequestMatcher(null)); } @Test public void matchesDelegateFalse() { given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new NegatedRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isTrue(); } @Test public void matchesDelegateTrue() { given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new NegatedRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isFalse(); } }
1,904
28.765625
89
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/DispatcherTypeRequestMatcherTests.java
/* * Copyright 2002-2020 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 jakarta.servlet.DispatcherType; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; /** * @author Nick McKinney */ public class DispatcherTypeRequestMatcherTests { @Test public void matches_dispatcher_type() { HttpServletRequest request = mockHttpServletRequest(DispatcherType.ERROR, HttpMethod.GET); DispatcherTypeRequestMatcher matcher = new DispatcherTypeRequestMatcher(DispatcherType.ERROR); assertThat(matcher.matches(request)).isTrue(); } @Test public void matches_dispatcher_type_and_http_method() { HttpServletRequest request = mockHttpServletRequest(DispatcherType.ERROR, HttpMethod.GET); DispatcherTypeRequestMatcher matcher = new DispatcherTypeRequestMatcher(DispatcherType.ERROR, HttpMethod.GET); assertThat(matcher.matches(request)).isTrue(); } @Test public void does_not_match_wrong_type() { HttpServletRequest request = mockHttpServletRequest(DispatcherType.FORWARD, HttpMethod.GET); DispatcherTypeRequestMatcher matcher = new DispatcherTypeRequestMatcher(DispatcherType.ERROR); assertThat(matcher.matches(request)).isFalse(); } @Test public void does_not_match_with_wrong_http_method() { HttpServletRequest request = mockHttpServletRequest(DispatcherType.ERROR, HttpMethod.GET); DispatcherTypeRequestMatcher matcher = new DispatcherTypeRequestMatcher(DispatcherType.ERROR, HttpMethod.POST); assertThat(matcher.matches(request)).isFalse(); } @Test public void null_http_method_matches_any_http_method() { HttpServletRequest request = mockHttpServletRequest(DispatcherType.ERROR, HttpMethod.POST); DispatcherTypeRequestMatcher matcher = new DispatcherTypeRequestMatcher(DispatcherType.ERROR, null); assertThat(matcher.matches(request)).isTrue(); } private HttpServletRequest mockHttpServletRequest(DispatcherType dispatcherType, HttpMethod httpMethod) { MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); mockHttpServletRequest.setDispatcherType(dispatcherType); mockHttpServletRequest.setMethod(httpMethod.name()); return mockHttpServletRequest; } }
2,943
35.345679
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/ELRequestMatcherTests.java
/* * Copyright 2010-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. * 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 org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; /** * @author Mike Wiesner * @since 3.0.2 */ public class ELRequestMatcherTests { @Test public void testHasIpAddressTrue() { ELRequestMatcher requestMatcher = new ELRequestMatcher("hasIpAddress('1.1.1.1')"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("1.1.1.1"); assertThat(requestMatcher.matches(request)).isTrue(); } @Test public void testHasIpAddressFalse() { ELRequestMatcher requestMatcher = new ELRequestMatcher("hasIpAddress('1.1.1.1')"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("1.1.1.2"); assertThat(requestMatcher.matches(request)).isFalse(); } @Test public void testHasHeaderTrue() { ELRequestMatcher requestMatcher = new ELRequestMatcher("hasHeader('User-Agent','MSIE')"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("User-Agent", "MSIE"); assertThat(requestMatcher.matches(request)).isTrue(); } @Test public void testHasHeaderTwoEntries() { ELRequestMatcher requestMatcher = new ELRequestMatcher( "hasHeader('User-Agent','MSIE') or hasHeader('User-Agent','Mozilla')"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("User-Agent", "MSIE"); assertThat(requestMatcher.matches(request)).isTrue(); request = new MockHttpServletRequest(); request.addHeader("User-Agent", "Mozilla"); assertThat(requestMatcher.matches(request)).isTrue(); } @Test public void testHasHeaderFalse() { ELRequestMatcher requestMatcher = new ELRequestMatcher("hasHeader('User-Agent','MSIE')"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("User-Agent", "wrong"); assertThat(requestMatcher.matches(request)).isFalse(); } @Test public void testHasHeaderNull() { ELRequestMatcher requestMatcher = new ELRequestMatcher("hasHeader('User-Agent','MSIE')"); MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(requestMatcher.matches(request)).isFalse(); } @Test public void toStringThenFormatted() { ELRequestMatcher requestMatcher = new ELRequestMatcher("hasHeader('User-Agent','MSIE')"); assertThat(requestMatcher.toString()).isEqualTo("EL [el=\"hasHeader('User-Agent','MSIE')\"]"); } }
3,107
33.921348
96
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcherRequestHCNSTests.java
/* * Copyright 2002-2013 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 java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.accept.ContentNegotiationStrategy; import org.springframework.web.accept.HeaderContentNegotiationStrategy; import static org.assertj.core.api.Assertions.assertThat; /** * Verify how integrates with {@link HeaderContentNegotiationStrategy}. * * @author Rob Winch * */ public class MediaTypeRequestMatcherRequestHCNSTests { private MediaTypeRequestMatcher matcher; private MockHttpServletRequest request; private ContentNegotiationStrategy negotiationStrategy; @BeforeEach public void setup() { this.negotiationStrategy = new HeaderContentNegotiationStrategy(); this.request = new MockHttpServletRequest(); } @Test public void mediaAllMatches() { this.request.addHeader("Accept", MediaType.ALL_VALUE); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); assertThat(this.matcher.matches(this.request)).isTrue(); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_XHTML_XML); assertThat(this.matcher.matches(this.request)).isTrue(); } // ignoreMediaTypeAll @Test public void mediaAllIgnoreMediaTypeAll() { this.request.addHeader("Accept", MediaType.ALL_VALUE); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void mediaAllAndTextHtmlIgnoreMediaTypeAll() { this.request.addHeader("Accept", MediaType.ALL_VALUE + "," + MediaType.TEXT_HTML_VALUE); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(this.matcher.matches(this.request)).isTrue(); } // JavaDoc @Test public void javadocJsonJson() { this.request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); assertThat(matcher.matches(this.request)).isTrue(); } @Test public void javadocAllJson() { this.request.addHeader("Accept", MediaType.ALL_VALUE); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); assertThat(matcher.matches(this.request)).isTrue(); } @Test public void javadocAllJsonIgnoreAll() { this.request.addHeader("Accept", MediaType.ALL_VALUE); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(matcher.matches(this.request)).isFalse(); } @Test public void javadocJsonJsonIgnoreAll() { this.request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); assertThat(matcher.matches(this.request)).isTrue(); } @Test public void javadocJsonJsonUseEquals() { this.request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); matcher.setUseEquals(true); assertThat(matcher.matches(this.request)).isTrue(); } @Test public void javadocAllJsonUseEquals() { this.request.addHeader("Accept", MediaType.ALL_VALUE); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); matcher.setUseEquals(true); assertThat(matcher.matches(this.request)).isFalse(); } @Test public void javadocApplicationAllJsonUseEquals() { this.request.addHeader("Accept", new MediaType("application", "*")); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); matcher.setUseEquals(true); assertThat(matcher.matches(this.request)).isFalse(); } @Test public void javadocAllJsonUseFalse() { this.request.addHeader("Accept", MediaType.ALL_VALUE); MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_JSON); matcher.setUseEquals(true); assertThat(matcher.matches(this.request)).isFalse(); } }
5,328
34.765101
104
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/HttpSessionEventPublisherTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.session; import jakarta.servlet.http.HttpSessionEvent; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * The HttpSessionEventPublisher tests * * @author Ray Krueger */ public class HttpSessionEventPublisherTests { /** * It's not that complicated so we'll just run it straight through here. */ @Test public void publishedEventIsReceivedbyListener() { HttpSessionEventPublisher publisher = new HttpSessionEventPublisher(); StaticWebApplicationContext context = new StaticWebApplicationContext(); MockServletContext servletContext = new MockServletContext(); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); context.setServletContext(servletContext); context.registerSingleton("listener", MockApplicationListener.class, null); context.refresh(); MockHttpSession session = new MockHttpSession(servletContext); MockApplicationListener listener = (MockApplicationListener) context.getBean("listener"); HttpSessionEvent event = new HttpSessionEvent(session); publisher.sessionCreated(event); assertThat(listener.getCreatedEvent()).isNotNull(); assertThat(listener.getDestroyedEvent()).isNull(); assertThat(listener.getCreatedEvent().getSession()).isEqualTo(session); listener.setCreatedEvent(null); listener.setDestroyedEvent(null); publisher.sessionDestroyed(event); assertThat(listener.getDestroyedEvent()).isNotNull(); assertThat(listener.getCreatedEvent()).isNull(); assertThat(listener.getDestroyedEvent().getSession()).isEqualTo(session); publisher.sessionIdChanged(event, "oldSessionId"); assertThat(listener.getSessionIdChangedEvent()).isNotNull(); assertThat(listener.getSessionIdChangedEvent().getOldSessionId()).isEqualTo("oldSessionId"); listener.setSessionIdChangedEvent(null); } @Test public void publishedEventIsReceivedbyListenerChildContext() { HttpSessionEventPublisher publisher = new HttpSessionEventPublisher(); StaticWebApplicationContext context = new StaticWebApplicationContext(); MockServletContext servletContext = new MockServletContext(); servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", context); context.setServletContext(servletContext); context.registerSingleton("listener", MockApplicationListener.class, null); context.refresh(); MockHttpSession session = new MockHttpSession(servletContext); MockApplicationListener listener = (MockApplicationListener) context.getBean("listener"); HttpSessionEvent event = new HttpSessionEvent(session); publisher.sessionCreated(event); assertThat(listener.getCreatedEvent()).isNotNull(); assertThat(listener.getDestroyedEvent()).isNull(); assertThat(listener.getCreatedEvent().getSession()).isEqualTo(session); listener.setCreatedEvent(null); listener.setDestroyedEvent(null); publisher.sessionDestroyed(event); assertThat(listener.getDestroyedEvent()).isNotNull(); assertThat(listener.getCreatedEvent()).isNull(); assertThat(listener.getDestroyedEvent().getSession()).isEqualTo(session); publisher.sessionIdChanged(event, "oldSessionId"); assertThat(listener.getSessionIdChangedEvent()).isNotNull(); assertThat(listener.getSessionIdChangedEvent().getOldSessionId()).isEqualTo("oldSessionId"); listener.setSessionIdChangedEvent(null); } // SEC-2599 @Test public void sessionCreatedNullApplicationContext() { HttpSessionEventPublisher publisher = new HttpSessionEventPublisher(); MockServletContext servletContext = new MockServletContext(); MockHttpSession session = new MockHttpSession(servletContext); HttpSessionEvent event = new HttpSessionEvent(session); assertThatIllegalStateException().isThrownBy(() -> publisher.sessionCreated(event)); } @Test // SEC-2599 public void sessionDestroyedNullApplicationContext() { HttpSessionEventPublisher publisher = new HttpSessionEventPublisher(); MockServletContext servletContext = new MockServletContext(); MockHttpSession session = new MockHttpSession(servletContext); HttpSessionEvent event = new HttpSessionEvent(session); assertThatIllegalStateException().isThrownBy(() -> publisher.sessionDestroyed(event)); } @Test public void sessionIdChangeNullApplicationContext() { HttpSessionEventPublisher publisher = new HttpSessionEventPublisher(); MockServletContext servletContext = new MockServletContext(); MockHttpSession session = new MockHttpSession(servletContext); HttpSessionEvent event = new HttpSessionEvent(session); assertThatIllegalStateException().isThrownBy(() -> publisher.sessionIdChanged(event, "oldSessionId")); } }
5,649
44.2
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/ForceEagerSessionCreationFilterTests.java
/* * 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. * 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.session; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; class ForceEagerSessionCreationFilterTests { @Test void createsSession() throws Exception { ForceEagerSessionCreationFilter filter = new ForceEagerSessionCreationFilter(); MockHttpServletRequest request = new MockHttpServletRequest(); MockFilterChain chain = new MockFilterChain(); filter.doFilter(request, new MockHttpServletResponse(), chain); assertThat(request.getSession(false)).isNotNull(); assertThat(chain.getRequest()).isEqualTo(request); } }
1,415
32.714286
81
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/SessionInformationExpiredEventTests.java
/* * Copyright 2012-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. * 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.session; import java.util.Date; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.session.SessionInformation; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @since 4.2 */ public class SessionInformationExpiredEventTests { @Test public void constructorWhenSessionInformationNullThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new SessionInformationExpiredEvent(null, new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test public void constructorWhenRequestNullThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new SessionInformationExpiredEvent( new SessionInformation("fake", "sessionId", new Date()), null, new MockHttpServletResponse())); } @Test public void constructorWhenResponseNullThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new SessionInformationExpiredEvent( new SessionInformation("fake", "sessionId", new Date()), new MockHttpServletRequest(), null)); } }
1,886
33.944444
99
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/DisableEncodeUrlFilterTests.java
/* * 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. * 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.session; import java.util.function.Consumer; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.verifyNoInteractions; /** * @author Rob Winch */ @ExtendWith(MockitoExtension.class) class DisableEncodeUrlFilterTests { @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; private DisableEncodeUrlFilter filter = new DisableEncodeUrlFilter(); @Test void doFilterDisablesEncodeURL() throws Exception { verifyDoFilterDoesNotInteractWithResponse((httpResponse) -> httpResponse.encodeURL("/")); } @Test void doFilterDisablesEncodeRedirectURL() throws Exception { verifyDoFilterDoesNotInteractWithResponse((httpResponse) -> httpResponse.encodeRedirectURL("/")); } private void verifyDoFilterDoesNotInteractWithResponse(Consumer<HttpServletResponse> toInvoke) throws Exception { this.filter.doFilter(this.request, this.response, (request, response) -> { HttpServletResponse httpResponse = (HttpServletResponse) response; toInvoke.accept(httpResponse); }); verifyNoInteractions(this.response); } }
1,969
30.269841
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java
/* * Copyright 2002-2020 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.session; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.session.SessionFixationProtectionEvent; import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Luke Taylor */ public class DefaultSessionAuthenticationStrategyTests { @Test public void newSessionShouldNotBeCreatedIfNoSessionExistsAndAlwaysCreateIsFalse() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); HttpServletRequest request = new MockHttpServletRequest(); strategy.onAuthentication(mock(Authentication.class), request, new MockHttpServletResponse()); assertThat(request.getSession(false)).isNull(); } @Test public void newSessionIsCreatedIfSessionAlreadyExists() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); HttpServletRequest request = new MockHttpServletRequest(); String sessionId = request.getSession().getId(); strategy.onAuthentication(mock(Authentication.class), request, new MockHttpServletResponse()); assertThat(sessionId.equals(request.getSession().getId())).isFalse(); } // SEC-2002 @Test public void newSessionIsCreatedIfSessionAlreadyExistsWithEventPublisher() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); HttpServletRequest request = new MockHttpServletRequest(); HttpSession session = request.getSession(); session.setAttribute("blah", "blah"); session.setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", "DefaultSavedRequest"); String oldSessionId = session.getId(); ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class); strategy.setApplicationEventPublisher(eventPublisher); Authentication mockAuthentication = mock(Authentication.class); strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse()); ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class); verify(eventPublisher).publishEvent(eventArgumentCaptor.capture()); assertThat(oldSessionId.equals(request.getSession().getId())).isFalse(); assertThat(request.getSession().getAttribute("blah")).isNotNull(); assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull(); assertThat(eventArgumentCaptor.getValue()).isNotNull(); assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue(); SessionFixationProtectionEvent event = (SessionFixationProtectionEvent) eventArgumentCaptor.getValue(); assertThat(event.getOldSessionId()).isEqualTo(oldSessionId); assertThat(event.getNewSessionId()).isEqualTo(request.getSession().getId()); assertThat(event.getAuthentication()).isSameAs(mockAuthentication); } // See SEC-1077 @Test public void onlySavedRequestAttributeIsMigratedIfMigrateAttributesIsFalse() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); strategy.setMigrateSessionAttributes(false); HttpServletRequest request = new MockHttpServletRequest(); HttpSession session = request.getSession(); session.setAttribute("blah", "blah"); session.setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", "DefaultSavedRequest"); strategy.onAuthentication(mock(Authentication.class), request, new MockHttpServletResponse()); assertThat(request.getSession().getAttribute("blah")).isNull(); assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull(); } // SEC-2002 @Test public void onlySavedRequestAttributeIsMigratedIfMigrateAttributesIsFalseWithEventPublisher() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); strategy.setMigrateSessionAttributes(false); HttpServletRequest request = new MockHttpServletRequest(); HttpSession session = request.getSession(); session.setAttribute("blah", "blah"); session.setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", "DefaultSavedRequest"); String oldSessionId = session.getId(); ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class); strategy.setApplicationEventPublisher(eventPublisher); Authentication mockAuthentication = mock(Authentication.class); strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse()); ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class); verify(eventPublisher).publishEvent(eventArgumentCaptor.capture()); assertThat(request.getSession().getAttribute("blah")).isNull(); assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull(); assertThat(eventArgumentCaptor.getValue()).isNotNull(); assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue(); SessionFixationProtectionEvent event = (SessionFixationProtectionEvent) eventArgumentCaptor.getValue(); assertThat(event.getOldSessionId()).isEqualTo(oldSessionId); assertThat(event.getNewSessionId()).isEqualTo(request.getSession().getId()); assertThat(event.getAuthentication()).isSameAs(mockAuthentication); } @Test public void sessionIsCreatedIfAlwaysCreateTrue() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); strategy.setAlwaysCreateSession(true); HttpServletRequest request = new MockHttpServletRequest(); strategy.onAuthentication(mock(Authentication.class), request, new MockHttpServletResponse()); assertThat(request.getSession(false)).isNotNull(); } @Test public void onAuthenticationWhenMigrateSessionAttributesTrueThenMaxInactiveIntervalIsMigrated() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); HttpServletRequest request = new MockHttpServletRequest(); HttpSession session = request.getSession(); session.setMaxInactiveInterval(1); Authentication mockAuthentication = mock(Authentication.class); strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse()); assertThat(request.getSession().getMaxInactiveInterval()).isEqualTo(1); } @Test public void onAuthenticationWhenMigrateSessionAttributesFalseThenMaxInactiveIntervalIsNotMigrated() { SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy(); strategy.setMigrateSessionAttributes(false); HttpServletRequest request = new MockHttpServletRequest(); HttpSession session = request.getSession(); session.setMaxInactiveInterval(1); Authentication mockAuthentication = mock(Authentication.class); strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse()); assertThat(request.getSession().getMaxInactiveInterval()).isNotEqualTo(1); } }
8,002
49.974522
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/HttpSessionDestroyedEventTests.java
/* * 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. * 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.session; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author Rob Winch * */ public class HttpSessionDestroyedEventTests { private MockHttpSession session; private HttpSessionDestroyedEvent destroyedEvent; @BeforeEach public void setUp() { this.session = new MockHttpSession(); this.session.setAttribute("notcontext", "notcontext"); this.session.setAttribute("null", null); this.session.setAttribute("context", new SecurityContextImpl()); this.destroyedEvent = new HttpSessionDestroyedEvent(this.session); } // SEC-1870 @Test public void getSecurityContexts() { List<SecurityContext> securityContexts = this.destroyedEvent.getSecurityContexts(); assertThat(securityContexts).hasSize(1); assertThat(securityContexts.get(0)).isSameAs(this.session.getAttribute("context")); } @Test public void getSecurityContextsMulti() { this.session.setAttribute("another", new SecurityContextImpl()); List<SecurityContext> securityContexts = this.destroyedEvent.getSecurityContexts(); assertThat(securityContexts).hasSize(2); } @Test public void getSecurityContextsDiffImpl() { this.session.setAttribute("context", mock(SecurityContext.class)); List<SecurityContext> securityContexts = this.destroyedEvent.getSecurityContexts(); assertThat(securityContexts).hasSize(1); assertThat(securityContexts.get(0)).isSameAs(this.session.getAttribute("context")); } }
2,413
31.621622
85
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/MockApplicationListener.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.session; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; /** * Listener for tests * * @author Ray Krueger */ public class MockApplicationListener implements ApplicationListener<ApplicationEvent> { private HttpSessionCreatedEvent createdEvent; private HttpSessionDestroyedEvent destroyedEvent; private HttpSessionIdChangedEvent sessionIdChangedEvent; public HttpSessionCreatedEvent getCreatedEvent() { return this.createdEvent; } public HttpSessionDestroyedEvent getDestroyedEvent() { return this.destroyedEvent; } @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof HttpSessionCreatedEvent) { this.createdEvent = (HttpSessionCreatedEvent) event; } else if (event instanceof HttpSessionDestroyedEvent) { this.destroyedEvent = (HttpSessionDestroyedEvent) event; } else if (event instanceof HttpSessionIdChangedEvent) { this.sessionIdChangedEvent = (HttpSessionIdChangedEvent) event; } } public void setCreatedEvent(HttpSessionCreatedEvent createdEvent) { this.createdEvent = createdEvent; } public void setDestroyedEvent(HttpSessionDestroyedEvent destroyedEvent) { this.destroyedEvent = destroyedEvent; } public void setSessionIdChangedEvent(HttpSessionIdChangedEvent sessionIdChangedEvent) { this.sessionIdChangedEvent = sessionIdChangedEvent; } public HttpSessionIdChangedEvent getSessionIdChangedEvent() { return this.sessionIdChangedEvent; } }
2,179
28.863014
88
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java
/* * 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. * 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.session; 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.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; 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.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.session.SessionAuthenticationException; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; import org.springframework.security.web.context.SecurityContextRepository; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Luke Taylor * @author Rob Winch */ public class SessionManagementFilterTests { @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void newSessionShouldNotBeCreatedIfSessionExistsAndUserIsNotAuthenticated() throws Exception { SecurityContextRepository repo = mock(SecurityContextRepository.class); SessionManagementFilter filter = new SessionManagementFilter(repo); HttpServletRequest request = new MockHttpServletRequest(); String sessionId = request.getSession().getId(); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertThat(request.getSession().getId()).isEqualTo(sessionId); } @Test public void strategyIsNotInvokedIfSecurityContextAlreadyExistsForRequest() throws Exception { SecurityContextRepository repo = mock(SecurityContextRepository.class); SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class); // mock that repo contains a security context given(repo.containsContext(any(HttpServletRequest.class))).willReturn(true); SessionManagementFilter filter = new SessionManagementFilter(repo, strategy); HttpServletRequest request = new MockHttpServletRequest(); authenticateUser(); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); verifyNoMoreInteractions(strategy); } @Test public void strategyIsNotInvokedIfAuthenticationIsNull() throws Exception { SecurityContextRepository repo = mock(SecurityContextRepository.class); SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class); SessionManagementFilter filter = new SessionManagementFilter(repo, strategy); HttpServletRequest request = new MockHttpServletRequest(); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); verifyNoMoreInteractions(strategy); } @Test public void strategyIsInvokedIfUserIsNewlyAuthenticated() throws Exception { SecurityContextRepository repo = mock(SecurityContextRepository.class); // repo will return false to containsContext() SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class); SessionManagementFilter filter = new SessionManagementFilter(repo, strategy); HttpServletRequest request = new MockHttpServletRequest(); authenticateUser(); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); verify(strategy).onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class)); // Check that it is only applied once to the request filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); verifyNoMoreInteractions(strategy); } @Test public void strategyFailureInvokesFailureHandler() throws Exception { SecurityContextRepository repo = mock(SecurityContextRepository.class); // repo will return false to containsContext() SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class); AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class); SessionManagementFilter filter = new SessionManagementFilter(repo, strategy); filter.setAuthenticationFailureHandler(failureHandler); HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); FilterChain fc = mock(FilterChain.class); authenticateUser(); SessionAuthenticationException exception = new SessionAuthenticationException("Failure"); willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response); filter.doFilter(request, response, fc); verifyNoMoreInteractions(fc); verify(failureHandler).onAuthenticationFailure(request, response, exception); } @Test public void responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid() throws Exception { SecurityContextRepository repo = mock(SecurityContextRepository.class); // repo will return false to containsContext() SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class); SessionManagementFilter filter = new SessionManagementFilter(repo, strategy); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestedSessionId("xxx"); request.setRequestedSessionIdValid(false); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, new MockFilterChain()); assertThat(response.getRedirectedUrl()).isNull(); // Now set a redirect URL request = new MockHttpServletRequest(); request.setRequestedSessionId("xxx"); request.setRequestedSessionIdValid(false); SimpleRedirectInvalidSessionStrategy iss = new SimpleRedirectInvalidSessionStrategy("/timedOut"); iss.setCreateNewSession(true); filter.setInvalidSessionStrategy(iss); FilterChain fc = mock(FilterChain.class); filter.doFilter(request, response, fc); verifyNoMoreInteractions(fc); assertThat(response.getRedirectedUrl()).isEqualTo("/timedOut"); } @Test public void responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid() throws Exception { SecurityContextRepository repo = mock(SecurityContextRepository.class); // repo will return false to containsContext() SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class); SessionManagementFilter filter = new SessionManagementFilter(repo, strategy); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestedSessionId("xxx"); request.setRequestedSessionIdValid(false); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, new MockFilterChain()); assertThat(response.getRedirectedUrl()).isNull(); // Now set a redirect URL request = new MockHttpServletRequest(); request.setRequestedSessionId("xxx"); request.setRequestedSessionIdValid(false); request.setRequestURI("/requested"); RequestedUrlRedirectInvalidSessionStrategy iss = new RequestedUrlRedirectInvalidSessionStrategy(); iss.setCreateNewSession(true); filter.setInvalidSessionStrategy(iss); FilterChain fc = mock(FilterChain.class); filter.doFilter(request, response, fc); verifyNoMoreInteractions(fc); assertThat(response.getRedirectedUrl()).isEqualTo("/requested"); } @Test public void customAuthenticationTrustResolver() throws Exception { AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class); SecurityContextRepository repo = mock(SecurityContextRepository.class); SessionManagementFilter filter = new SessionManagementFilter(repo); filter.setTrustResolver(trustResolver); HttpServletRequest request = new MockHttpServletRequest(); authenticateUser(); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); verify(trustResolver).isAnonymous(any(Authentication.class)); } @Test public void setTrustResolverNull() { SecurityContextRepository repo = mock(SecurityContextRepository.class); SessionManagementFilter filter = new SessionManagementFilter(repo); assertThatIllegalArgumentException().isThrownBy(() -> filter.setTrustResolver(null)); } private void authenticateUser() { SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user", "pass")); } }
9,464
46.089552
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/bind/support/AuthenticationPrincipalArgumentResolverTests.java
/* * Copyright 2002-2013 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.bind.support; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.MethodParameter; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch * */ @SuppressWarnings("deprecation") public class AuthenticationPrincipalArgumentResolverTests { private Object expectedPrincipal; private AuthenticationPrincipalArgumentResolver resolver; @BeforeEach public void setup() { this.resolver = new AuthenticationPrincipalArgumentResolver(); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void supportsParameterNoAnnotation() { assertThat(this.resolver.supportsParameter(showUserNoAnnotation())).isFalse(); } @Test public void supportsParameterAnnotation() { assertThat(this.resolver.supportsParameter(showUserAnnotationObject())).isTrue(); } @Test public void supportsParameterCustomAnnotation() { assertThat(this.resolver.supportsParameter(showUserCustomAnnotation())).isTrue(); } @Test public void resolveArgumentNullAuthentication() throws Exception { assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull(); } @Test public void resolveArgumentNullPrincipal() throws Exception { setAuthenticationPrincipal(null); assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull(); } @Test public void resolveArgumentString() throws Exception { setAuthenticationPrincipal("john"); assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentPrincipalStringOnObject() throws Exception { setAuthenticationPrincipal("john"); assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentUserDetails() throws Exception { setAuthenticationPrincipal(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"))); assertThat(this.resolver.resolveArgument(showUserAnnotationUserDetails(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentCustomUserPrincipal() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThat(this.resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentCustomAnnotation() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThat(this.resolver.resolveArgument(showUserCustomAnnotation(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentNullOnInvalidType() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull(); } @Test public void resolveArgumentErrorOnInvalidType() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThatExceptionOfType(ClassCastException.class).isThrownBy( () -> this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null)); } @Test public void resolveArgumentCustomserErrorOnInvalidType() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> this.resolver .resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null)); } @Test public void resolveArgumentObject() throws Exception { setAuthenticationPrincipal(new Object()); assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null)) .isEqualTo(this.expectedPrincipal); } private MethodParameter showUserNoAnnotation() { return getMethodParameter("showUserNoAnnotation", String.class); } private MethodParameter showUserAnnotationString() { return getMethodParameter("showUserAnnotation", String.class); } private MethodParameter showUserAnnotationErrorOnInvalidType() { return getMethodParameter("showUserAnnotationErrorOnInvalidType", String.class); } private MethodParameter showUserAnnotationCurrentUserErrorOnInvalidType() { return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType", String.class); } private MethodParameter showUserAnnotationUserDetails() { return getMethodParameter("showUserAnnotation", UserDetails.class); } private MethodParameter showUserAnnotationCustomUserPrincipal() { return getMethodParameter("showUserAnnotation", CustomUserPrincipal.class); } private MethodParameter showUserCustomAnnotation() { return getMethodParameter("showUserCustomAnnotation", CustomUserPrincipal.class); } private MethodParameter showUserAnnotationObject() { return getMethodParameter("showUserAnnotation", Object.class); } private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) { Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes); return new MethodParameter(method, 0); } private void setAuthenticationPrincipal(Object principal) { this.expectedPrincipal = principal; SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER")); } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @AuthenticationPrincipal static @interface CurrentUser { } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @AuthenticationPrincipal(errorOnInvalidType = true) static @interface CurrentUserErrorOnInvalidType { } public static class TestController { public void showUserNoAnnotation(String user) { } public void showUserAnnotation(@AuthenticationPrincipal String user) { } public void showUserAnnotationErrorOnInvalidType( @AuthenticationPrincipal(errorOnInvalidType = true) String user) { } public void showUserAnnotationCurrentUserErrorOnInvalidType(@CurrentUserErrorOnInvalidType String user) { } public void showUserAnnotation(@AuthenticationPrincipal UserDetails user) { } public void showUserAnnotation(@AuthenticationPrincipal CustomUserPrincipal user) { } public void showUserCustomAnnotation(@CurrentUser CustomUserPrincipal user) { } public void showUserAnnotation(@AuthenticationPrincipal Object user) { } } private static class CustomUserPrincipal { } }
8,029
32.319502
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java
/* * Copyright 2012-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. * 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.csrf; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch */ @ExtendWith(MockitoExtension.class) public class LazyCsrfTokenRepositoryTests { @Mock CsrfTokenRepository delegate; @Mock HttpServletRequest request; @Mock HttpServletResponse response; @InjectMocks LazyCsrfTokenRepository repository; DefaultCsrfToken token; @BeforeEach public void setup() { this.token = new DefaultCsrfToken("header", "param", "token"); } @Test public void constructNullDelegateThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new LazyCsrfTokenRepository(null)); } @Test public void generateTokenNullResponseAttribute() { assertThatIllegalArgumentException() .isThrownBy(() -> this.repository.generateToken(mock(HttpServletRequest.class))); } @Test public void generateTokenGetTokenSavesToken() { given(this.delegate.generateToken(this.request)).willReturn(this.token); given(this.request.getAttribute(HttpServletResponse.class.getName())).willReturn(this.response); CsrfToken newToken = this.repository.generateToken(this.request); newToken.getToken(); verify(this.delegate).saveToken(this.token, this.request, this.response); } @Test public void saveNonNullDoesNothing() { this.repository.saveToken(this.token, this.request, this.response); verifyNoMoreInteractions(this.delegate); } @Test public void saveNullDelegates() { this.repository.saveToken(null, this.request, this.response); verify(this.delegate).saveToken(null, this.request, this.response); } @Test public void loadTokenDelegates() { given(this.delegate.loadToken(this.request)).willReturn(this.token); CsrfToken loadToken = this.repository.loadToken(this.request); assertThat(loadToken).isSameAs(this.token); verify(this.delegate).loadToken(this.request); } @Test public void loadTokenWhenDeferLoadToken() { given(this.delegate.loadToken(this.request)).willReturn(this.token); this.repository.setDeferLoadToken(true); CsrfToken loadToken = this.repository.loadToken(this.request); verifyNoInteractions(this.delegate); assertThat(loadToken.getToken()).isEqualTo(this.token.getToken()); assertThat(loadToken.getHeaderName()).isEqualTo(this.token.getHeaderName()); assertThat(loadToken.getParameterName()).isEqualTo(this.token.getParameterName()); } }
3,687
31.637168
98
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/XorCsrfTokenRequestAttributeHandlerTests.java
/* * 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. * 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.csrf; import java.security.SecureRandom; import java.util.Arrays; import java.util.Base64; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests for {@link XorCsrfTokenRequestAttributeHandler}. * * @author Steve Riesenberg * @since 5.8 */ public class XorCsrfTokenRequestAttributeHandlerTests { private static final byte[] XOR_CSRF_TOKEN_BYTES = new byte[] { 1, 1, 1, 96, 99, 98 }; private static final String XOR_CSRF_TOKEN_VALUE = Base64.getEncoder().encodeToString(XOR_CSRF_TOKEN_BYTES); private MockHttpServletRequest request; private MockHttpServletResponse response; private CsrfToken token; private SecureRandom secureRandom; private XorCsrfTokenRequestAttributeHandler handler; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.token = new DefaultCsrfToken("headerName", "paramName", "abc"); this.secureRandom = mock(SecureRandom.class); this.handler = new XorCsrfTokenRequestAttributeHandler(); } @Test public void setSecureRandomWhenNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.setSecureRandom(null)) .withMessage("secureRandom cannot be null"); // @formatter:on } @Test public void handleWhenRequestIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(null, this.response, () -> this.token)) .withMessage("request cannot be null"); // @formatter:on } @Test public void handleWhenResponseIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(this.request, null, () -> this.token)) .withMessage("response cannot be null"); // @formatter:on } @Test public void handleWhenCsrfTokenSupplierIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(this.request, this.response, null)) .withMessage("deferredCsrfToken cannot be null"); // @formatter:on } @Test public void handleWhenCsrfTokenIsNullThenThrowsIllegalStateException() { this.handler.handle(this.request, this.response, () -> null); CsrfToken csrfTokenAttribute = (CsrfToken) this.request.getAttribute("_csrf"); // @formatter:off assertThatIllegalStateException() .isThrownBy(csrfTokenAttribute::getToken) .withMessage("csrfToken supplier returned null"); // @formatter:on } @Test public void handleWhenCsrfRequestAttributeSetThenUsed() { willAnswer(fillByteArray()).given(this.secureRandom).nextBytes(anyByteArray()); this.handler.setSecureRandom(this.secureRandom); this.handler.setCsrfRequestAttributeName("_csrf"); this.handler.handle(this.request, this.response, () -> this.token); assertThat(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute("_csrf")).isNotNull(); CsrfToken csrfTokenAttribute = (CsrfToken) this.request.getAttribute("_csrf"); assertThat(csrfTokenAttribute.getToken()).isEqualTo(XOR_CSRF_TOKEN_VALUE); } @Test public void handleWhenSecureRandomSetThenUsed() { willAnswer(fillByteArray()).given(this.secureRandom).nextBytes(anyByteArray()); this.handler.setSecureRandom(this.secureRandom); this.handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfTokenAttribute = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); assertThat(csrfTokenAttribute.getToken()).isEqualTo(XOR_CSRF_TOKEN_VALUE); verify(this.secureRandom).nextBytes(anyByteArray()); verifyNoMoreInteractions(this.secureRandom); } @Test public void handleWhenValidParametersThenRequestAttributesSet() { willAnswer(fillByteArray()).given(this.secureRandom).nextBytes(anyByteArray()); this.handler.setSecureRandom(this.secureRandom); this.handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfTokenAttribute = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); assertThat(csrfTokenAttribute.getToken()).isEqualTo(XOR_CSRF_TOKEN_VALUE); verify(this.secureRandom).nextBytes(anyByteArray()); assertThat(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute("_csrf")).isNotNull(); } @Test public void handleWhenCsrfTokenRequestedTwiceThenCached() { this.handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfTokenAttribute = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); assertThat(csrfTokenAttribute.getToken()).isNotEqualTo(this.token.getToken()); assertThat(csrfTokenAttribute.getToken()).isEqualTo(csrfTokenAttribute.getToken()); } @Test public void resolveCsrfTokenValueWhenRequestIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.resolveCsrfTokenValue(null, this.token)) .withMessage("request cannot be null"); // @formatter:on } @Test public void resolveCsrfTokenValueWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.resolveCsrfTokenValue(this.request, null)) .withMessage("csrfToken cannot be null"); // @formatter:on } @Test public void resolveCsrfTokenValueWhenTokenNotSetThenReturnsNull() { String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isNull(); } @Test public void resolveCsrfTokenValueWhenParameterSetThenReturnsTokenValue() { this.request.setParameter(this.token.getParameterName(), XOR_CSRF_TOKEN_VALUE); String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isEqualTo(this.token.getToken()); } @Test public void resolveCsrfTokenValueWhenHeaderSetThenReturnsTokenValue() { this.request.addHeader(this.token.getHeaderName(), XOR_CSRF_TOKEN_VALUE); String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isEqualTo(this.token.getToken()); } @Test public void resolveCsrfTokenValueWhenHeaderAndParameterSetThenHeaderIsPreferred() { this.request.addHeader(this.token.getHeaderName(), XOR_CSRF_TOKEN_VALUE); this.request.setParameter(this.token.getParameterName(), "invalid"); String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isEqualTo(this.token.getToken()); } private static Answer<Void> fillByteArray() { return (invocation) -> { byte[] bytes = invocation.getArgument(0); Arrays.fill(bytes, (byte) 1); return null; }; } private static byte[] anyByteArray() { return any(byte[].class); } }
8,193
35.580357
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/TestDeferredCsrfToken.java
/* * 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. * 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.csrf; final class TestDeferredCsrfToken implements DeferredCsrfToken { private final CsrfToken csrfToken; private final boolean isGenerated; TestDeferredCsrfToken(CsrfToken csrfToken, boolean isGenerated) { this.csrfToken = csrfToken; this.isGenerated = isGenerated; } @Override public CsrfToken get() { return this.csrfToken; } @Override public boolean isGenerated() { return this.isGenerated; } }
1,088
25.560976
75
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java
/* * 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.csrf; import java.io.IOException; import java.util.Arrays; import java.util.Base64; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.crypto.codec.Utf8; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.springframework.security.web.csrf.CsrfTokenAssert.assertThatCsrfToken; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class CsrfFilterTests { @Mock private RequestMatcher requestMatcher; @Mock private CsrfTokenRepository tokenRepository; @Mock private FilterChain filterChain; @Mock private AccessDeniedHandler deniedHandler; private MockHttpServletRequest request; private MockHttpServletResponse response; private CsrfToken token; private String csrfAttrName = "_csrf"; private CsrfFilter filter; @BeforeEach public void setup() { this.token = new DefaultCsrfToken("headerName", "paramName", "csrfTokenValue"); resetRequestResponse(); this.filter = createCsrfFilter(this.tokenRepository); } private CsrfFilter createCsrfFilter(CsrfTokenRepository repository) { CsrfFilter filter = new CsrfFilter(repository); filter.setRequireCsrfProtectionMatcher(this.requestMatcher); filter.setAccessDeniedHandler(this.deniedHandler); return filter; } private void resetRequestResponse() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test public void constructorNullRepository() { assertThatIllegalArgumentException().isThrownBy(() -> new CsrfFilter(null)); } // SEC-2276 @Test public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException, IOException { this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository)); given(this.requestMatcher.matches(this.request)).willReturn(false); given(this.tokenRepository.generateToken(this.request)).willReturn(this.token); this.filter.doFilter(this.request, this.response, this.filterChain); CsrfToken attrToken = (CsrfToken) this.request.getAttribute(this.csrfAttrName); // no CsrfToken should have been saved yet verify(this.tokenRepository, times(0)).saveToken(any(CsrfToken.class), any(HttpServletRequest.class), any(HttpServletResponse.class)); verify(this.filterChain).doFilter(this.request, this.response); // access the token attrToken.getToken(); // now the CsrfToken should have been saved verify(this.tokenRepository).saveToken(eq(this.token), any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void doFilterAccessDeniedNoTokenPresent() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class)); verifyNoMoreInteractions(this.filterChain); } @Test public void doFilterAccessDeniedIncorrectTokenPresent() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.request.setParameter(this.token.getParameterName(), this.token.getToken() + " INVALID"); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class)); verifyNoMoreInteractions(this.filterChain); } @Test public void doFilterAccessDeniedIncorrectTokenPresentHeader() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.request.addHeader(this.token.getHeaderName(), this.token.getToken() + " INVALID"); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class)); verifyNoMoreInteractions(this.filterChain); } @Test public void doFilterAccessDeniedIncorrectTokenPresentHeaderPreferredOverParameter() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); CsrfTokenRequestHandler handler = new XorCsrfTokenRequestAttributeHandler(); handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfToken = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); this.request.setParameter(csrfToken.getParameterName(), csrfToken.getToken()); this.request.addHeader(csrfToken.getHeaderName(), csrfToken.getToken() + " INVALID"); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class)); verifyNoMoreInteractions(this.filterChain); } @Test public void doFilterNotCsrfRequestExistingToken() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(false); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.filterChain).doFilter(this.request, this.response); verifyNoMoreInteractions(this.deniedHandler); } @Test public void doFilterNotCsrfRequestGenerateToken() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(false); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, true); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.filterChain).doFilter(this.request, this.response); verifyNoMoreInteractions(this.deniedHandler); } @Test public void doFilterIsCsrfRequestExistingTokenHeader() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); CsrfTokenRequestHandler handler = new XorCsrfTokenRequestAttributeHandler(); handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfToken = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); this.request.addHeader(csrfToken.getHeaderName(), csrfToken.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.filterChain).doFilter(this.request, this.response); verifyNoMoreInteractions(this.deniedHandler); } @Test public void doFilterIsCsrfRequestExistingTokenHeaderPreferredOverInvalidParam() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); CsrfTokenRequestHandler handler = new XorCsrfTokenRequestAttributeHandler(); handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfToken = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); this.request.setParameter(csrfToken.getParameterName(), csrfToken.getToken() + " INVALID"); this.request.addHeader(csrfToken.getHeaderName(), csrfToken.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.filterChain).doFilter(this.request, this.response); verifyNoMoreInteractions(this.deniedHandler); } @Test public void doFilterIsCsrfRequestExistingToken() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); CsrfTokenRequestHandler handler = new XorCsrfTokenRequestAttributeHandler(); handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfToken = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); this.request.setParameter(csrfToken.getParameterName(), csrfToken.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.filterChain).doFilter(this.request, this.response); verifyNoMoreInteractions(this.deniedHandler); verify(this.tokenRepository, never()).saveToken(any(CsrfToken.class), any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void doFilterIsCsrfRequestGenerateToken() throws ServletException, IOException { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, true); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); CsrfTokenRequestHandler handler = new XorCsrfTokenRequestAttributeHandler(); handler.handle(this.request, this.response, () -> this.token); CsrfToken csrfToken = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); this.request.setParameter(csrfToken.getParameterName(), csrfToken.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); // LazyCsrfTokenRepository requires the response as an attribute assertThat(this.request.getAttribute(HttpServletResponse.class.getName())).isEqualTo(this.response); verify(this.filterChain).doFilter(this.request, this.response); verifyNoMoreInteractions(this.deniedHandler); } @Test public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethods() throws ServletException, IOException { this.filter = new CsrfFilter(this.tokenRepository); this.filter.setAccessDeniedHandler(this.deniedHandler); for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) { resetRequestResponse(); given(this.tokenRepository.loadDeferredToken(this.request, this.response)) .willReturn(new TestDeferredCsrfToken(this.token, false)); this.request.setMethod(method); this.filter.doFilter(this.request, this.response, this.filterChain); verify(this.filterChain).doFilter(this.request, this.response); verifyNoMoreInteractions(this.deniedHandler); } } /** * SEC-2292 Should not allow other cases through since spec states HTTP method is case * sensitive https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1 * @throws Exception if an error occurs * */ @Test public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethodsCaseSensitive() throws Exception { this.filter = new CsrfFilter(this.tokenRepository); this.filter.setAccessDeniedHandler(this.deniedHandler); for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) { resetRequestResponse(); given(this.tokenRepository.loadDeferredToken(this.request, this.response)) .willReturn(new TestDeferredCsrfToken(this.token, false)); this.request.setMethod(method); this.filter.doFilter(this.request, this.response, this.filterChain); verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class)); verifyNoMoreInteractions(this.filterChain); } } @Test public void doFilterDefaultRequireCsrfProtectionMatcherDeniedMethods() throws ServletException, IOException { this.filter = new CsrfFilter(this.tokenRepository); this.filter.setAccessDeniedHandler(this.deniedHandler); for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE", "INVALID")) { resetRequestResponse(); given(this.tokenRepository.loadDeferredToken(this.request, this.response)) .willReturn(new TestDeferredCsrfToken(this.token, false)); this.request.setMethod(method); this.filter.doFilter(this.request, this.response, this.filterChain); verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class)); verifyNoMoreInteractions(this.filterChain); } } @Test public void doFilterDefaultAccessDenied() throws ServletException, IOException { this.filter = new CsrfFilter(this.tokenRepository); this.filter.setRequireCsrfProtectionMatcher(this.requestMatcher); given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.filter.doFilter(this.request, this.response, this.filterChain); assertThatCsrfToken(this.request.getAttribute(this.csrfAttrName)).isNotNull(); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); verifyNoMoreInteractions(this.filterChain); } @Test public void doFilterWhenSkipRequestInvokedThenSkips() throws Exception { CsrfTokenRepository repository = mock(CsrfTokenRepository.class); CsrfFilter filter = new CsrfFilter(repository); lenient().when(repository.loadToken(any(HttpServletRequest.class))).thenReturn(this.token); MockHttpServletRequest request = new MockHttpServletRequest(); CsrfFilter.skipRequest(request); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); verifyNoMoreInteractions(repository); } // gh-9561 @Test public void doFilterWhenTokenIsNullThenNoNullPointer() throws Exception { CsrfFilter filter = createCsrfFilter(this.tokenRepository); CsrfToken token = mock(CsrfToken.class); given(token.getToken()).willReturn(null); given(token.getHeaderName()).willReturn(this.token.getHeaderName()); given(token.getParameterName()).willReturn(this.token.getParameterName()); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); given(this.requestMatcher.matches(this.request)).willReturn(true); filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test public void doFilterWhenRequestHandlerThenUsed() throws Exception { DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); CsrfTokenRequestHandler requestHandler = mock(CsrfTokenRequestHandler.class); this.filter = createCsrfFilter(this.tokenRepository); this.filter.setRequestHandler(requestHandler); this.request.setParameter(this.token.getParameterName(), this.token.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.tokenRepository).loadDeferredToken(this.request, this.response); verify(requestHandler).handle(eq(this.request), eq(this.response), any()); verify(this.filterChain).doFilter(this.request, this.response); } @Test public void doFilterWhenXorCsrfTokenRequestAttributeHandlerAndValidTokenThenSuccess() throws Exception { given(this.requestMatcher.matches(this.request)).willReturn(false); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.request.getAttribute(CsrfToken.class.getName())).isNotNull(); assertThat(this.request.getAttribute("_csrf")).isNotNull(); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.filterChain).doFilter(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); CsrfToken csrfTokenAttribute = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); byte[] csrfTokenAttributeBytes = Base64.getUrlDecoder().decode(csrfTokenAttribute.getToken()); byte[] actualTokenBytes = Utf8.encode(this.token.getToken()); // XOR'd token length is 2x due to containing the random bytes assertThat(csrfTokenAttributeBytes).hasSize(actualTokenBytes.length * 2); given(this.requestMatcher.matches(this.request)).willReturn(true); this.request.setParameter(this.token.getParameterName(), csrfTokenAttribute.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); verify(this.filterChain, times(2)).doFilter(this.request, this.response); } @Test public void doFilterWhenXorCsrfTokenRequestAttributeHandlerAndRawTokenThenAccessDeniedException() throws Exception { given(this.requestMatcher.matches(this.request)).willReturn(true); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(this.token, false); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); this.request.setParameter(this.token.getParameterName(), this.token.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(AccessDeniedException.class)); verifyNoMoreInteractions(this.filterChain); } @Test public void setRequireCsrfProtectionMatcherNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequireCsrfProtectionMatcher(null)); } @Test public void setAccessDeniedHandlerNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAccessDeniedHandler(null)); } // This ensures that the HttpSession on get requests unless the CsrfToken is used @Test public void doFilterWhenCsrfRequestAttributeNameThenNoCsrfTokenMethodInvokedOnGet() throws ServletException, IOException { CsrfFilter filter = createCsrfFilter(this.tokenRepository); String csrfAttrName = "_csrf"; CsrfTokenRequestAttributeHandler requestHandler = new XorCsrfTokenRequestAttributeHandler(); requestHandler.setCsrfRequestAttributeName(csrfAttrName); filter.setRequestHandler(requestHandler); CsrfToken expectedCsrfToken = mock(CsrfToken.class); DeferredCsrfToken deferredCsrfToken = new TestDeferredCsrfToken(expectedCsrfToken, true); given(this.tokenRepository.loadDeferredToken(this.request, this.response)).willReturn(deferredCsrfToken); filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.request.getAttribute(DeferredCsrfToken.class.getName())).isSameAs(deferredCsrfToken); verifyNoInteractions(expectedCsrfToken); CsrfToken tokenFromRequest = (CsrfToken) this.request.getAttribute(csrfAttrName); assertThatCsrfToken(tokenFromRequest).isNotNull(); } }
24,748
52.223656
117
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/CsrfLogoutHandlerTests.java
/* * Copyright 2002-2013 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.csrf; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 3.2 */ @ExtendWith(MockitoExtension.class) public class CsrfLogoutHandlerTests { @Mock private CsrfTokenRepository csrfTokenRepository; private MockHttpServletRequest request; private MockHttpServletResponse response; private CsrfLogoutHandler handler; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.handler = new CsrfLogoutHandler(this.csrfTokenRepository); } @Test public void constructorNullCsrfTokenRepository() { assertThatIllegalArgumentException().isThrownBy(() -> new CsrfLogoutHandler(null)); } @Test public void logoutRemovesCsrfToken() { this.handler.logout(this.request, this.response, new TestingAuthenticationToken("user", "password", "ROLE_USER")); verify(this.csrfTokenRepository).saveToken(null, this.request, this.response); } }
2,106
29.985294
85
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/DefaultCsrfTokenTests.java
/* * Copyright 2002-2013 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.csrf; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * */ public class DefaultCsrfTokenTests { private final String headerName = "headerName"; private final String parameterName = "parameterName"; private final String tokenValue = "tokenValue"; @Test public void constructorNullHeaderName() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultCsrfToken(null, this.parameterName, this.tokenValue)); } @Test public void constructorEmptyHeaderName() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultCsrfToken("", this.parameterName, this.tokenValue)); } @Test public void constructorNullParameterName() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultCsrfToken(this.headerName, null, this.tokenValue)); } @Test public void constructorEmptyParameterName() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultCsrfToken(this.headerName, "", this.tokenValue)); } @Test public void constructorNullTokenValue() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultCsrfToken(this.headerName, this.parameterName, null)); } @Test public void constructorEmptyTokenValue() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultCsrfToken(this.headerName, this.parameterName, "")); } }
2,101
28.194444
87
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java
/* * 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. * 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.csrf; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class CsrfAuthenticationStrategyTests { @Mock private CsrfTokenRepository csrfTokenRepository; private MockHttpServletRequest request; private MockHttpServletResponse response; private CsrfAuthenticationStrategy strategy; private CsrfToken existingToken; private CsrfToken generatedToken; @BeforeEach public void setup() { this.response = new MockHttpServletResponse(); this.request = new MockHttpServletRequest(); this.request.setAttribute(HttpServletResponse.class.getName(), this.response); this.strategy = new CsrfAuthenticationStrategy(this.csrfTokenRepository); this.existingToken = new DefaultCsrfToken("_csrf", "_csrf", "1"); this.generatedToken = new DefaultCsrfToken("_csrf", "_csrf", "2"); } @Test public void constructorNullCsrfTokenRepository() { assertThatIllegalArgumentException().isThrownBy(() -> new CsrfAuthenticationStrategy(null)); } @Test public void setRequestHandlerWhenNullThenIllegalStateException() { assertThatIllegalArgumentException().isThrownBy(() -> this.strategy.setRequestHandler(null)) .withMessage("requestHandler cannot be null"); } @Test public void onAuthenticationWhenCustomRequestHandlerThenUsed() { given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken); given(this.csrfTokenRepository.loadDeferredToken(this.request, this.response)) .willReturn(new TestDeferredCsrfToken(this.existingToken, false)); CsrfTokenRequestHandler requestHandler = mock(CsrfTokenRequestHandler.class); this.strategy.setRequestHandler(requestHandler); this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request, this.response); verify(this.csrfTokenRepository).loadToken(this.request); verify(this.csrfTokenRepository).loadDeferredToken(this.request, this.response); verify(requestHandler).handle(eq(this.request), eq(this.response), any()); verifyNoMoreInteractions(requestHandler); } @Test public void logoutRemovesCsrfTokenAndLoadsNewDeferredCsrfToken() { given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken); given(this.csrfTokenRepository.loadDeferredToken(this.request, this.response)) .willReturn(new TestDeferredCsrfToken(this.generatedToken, false)); this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request, this.response); verify(this.csrfTokenRepository).loadToken(this.request); verify(this.csrfTokenRepository).saveToken(null, this.request, this.response); verify(this.csrfTokenRepository).loadDeferredToken(this.request, this.response); // SEC-2404, SEC-2832 CsrfToken tokenInRequest = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); assertThat(tokenInRequest.getToken()).isNotEmpty(); assertThat(tokenInRequest.getToken()).isNotEqualTo(this.generatedToken.getToken()); assertThat(tokenInRequest.getHeaderName()).isEqualTo(this.generatedToken.getHeaderName()); assertThat(tokenInRequest.getParameterName()).isEqualTo(this.generatedToken.getParameterName()); assertThat(this.request.getAttribute(this.generatedToken.getParameterName())).isSameAs(tokenInRequest); } // SEC-2872 @Test public void delaySavingCsrf() { this.strategy = new CsrfAuthenticationStrategy(new LazyCsrfTokenRepository(this.csrfTokenRepository)); given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken, (CsrfToken) null); given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken); this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request, this.response); verify(this.csrfTokenRepository).saveToken(null, this.request, this.response); verify(this.csrfTokenRepository, never()).saveToken(eq(this.generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class)); CsrfToken tokenInRequest = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName()); tokenInRequest.getToken(); verify(this.csrfTokenRepository, times(2)).loadToken(this.request); verify(this.csrfTokenRepository).generateToken(this.request); verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class)); } }
6,073
43.014493
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/CsrfTokenRequestAttributeHandlerTests.java
/* * 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. * 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.csrf; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.springframework.security.web.csrf.CsrfTokenAssert.assertThatCsrfToken; /** * Tests for {@link CsrfTokenRequestAttributeHandler}. * * @author Steve Riesenberg * @since 5.8 */ public class CsrfTokenRequestAttributeHandlerTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private CsrfToken token; private CsrfTokenRequestAttributeHandler handler; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.token = new DefaultCsrfToken("headerName", "paramName", "csrfTokenValue"); this.handler = new CsrfTokenRequestAttributeHandler(); } @Test public void handleWhenRequestIsNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(null, this.response, () -> this.token)) .withMessage("request cannot be null"); } @Test public void handleWhenResponseIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(this.request, null, () -> this.token)) .withMessage("response cannot be null"); // @formatter:on } @Test public void handleWhenCsrfTokenSupplierIsNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.handle(this.request, this.response, null)) .withMessage("deferredCsrfToken cannot be null"); } @Test public void handleWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() { // @formatter:off this.handler.setCsrfRequestAttributeName(null); assertThatIllegalStateException() .isThrownBy(() -> this.handler.handle(this.request, this.response, () -> null)) .withMessage("csrfTokenSupplier returned null delegate"); // @formatter:on } @Test public void handleWhenCsrfRequestAttributeSetThenUsed() { this.handler.setCsrfRequestAttributeName("_csrf"); this.handler.handle(this.request, this.response, () -> this.token); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token); assertThatCsrfToken(this.request.getAttribute("_csrf")).isEqualTo(this.token); } @Test public void handleWhenValidParametersThenRequestAttributesSet() { this.handler.handle(this.request, this.response, () -> this.token); assertThatCsrfToken(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token); assertThatCsrfToken(this.request.getAttribute("_csrf")).isEqualTo(this.token); } @Test public void resolveCsrfTokenValueWhenRequestIsNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.resolveCsrfTokenValue(null, this.token)) .withMessage("request cannot be null"); } @Test public void resolveCsrfTokenValueWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.resolveCsrfTokenValue(this.request, null)) .withMessage("csrfToken cannot be null"); } @Test public void resolveCsrfTokenValueWhenTokenNotSetThenReturnsNull() { String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isNull(); } @Test public void resolveCsrfTokenValueWhenParameterSetThenReturnsTokenValue() { this.request.setParameter(this.token.getParameterName(), this.token.getToken()); String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isEqualTo(this.token.getToken()); } @Test public void resolveCsrfTokenValueWhenHeaderSetThenReturnsTokenValue() { this.request.addHeader(this.token.getHeaderName(), this.token.getToken()); String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isEqualTo(this.token.getToken()); } @Test public void resolveCsrfTokenValueWhenHeaderAndParameterSetThenHeaderIsPreferred() { this.request.addHeader(this.token.getHeaderName(), "header"); this.request.setParameter(this.token.getParameterName(), "parameter"); String tokenValue = this.handler.resolveCsrfTokenValue(this.request, this.token); assertThat(tokenValue).isEqualTo("header"); } }
5,342
36.626761
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/MissingCsrfTokenExceptionTests.java
/* * Copyright 2002-2015 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.csrf; import org.junit.jupiter.api.Test; /** * @author Rob Winch * */ public class MissingCsrfTokenExceptionTests { // CsrfChannelInterceptor requires this to work @Test public void nullExpectedTokenDoesNotFail() { new MissingCsrfTokenException(null); } }
933
26.470588
75
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepositoryTests.java
/* * 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. * 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.csrf; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.springframework.security.web.csrf.CsrfTokenAssert.assertThatCsrfToken; /** * @author Rob Winch * */ public class HttpSessionCsrfTokenRepositoryTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private CsrfToken token; private HttpSessionCsrfTokenRepository repo; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.repo = new HttpSessionCsrfTokenRepository(); } @Test public void generateToken() { this.token = this.repo.generateToken(this.request); assertThat(this.token.getParameterName()).isEqualTo("_csrf"); assertThat(this.token.getToken()).isNotEmpty(); CsrfToken loadedToken = this.repo.loadToken(this.request); assertThat(loadedToken).isNull(); } @Test public void generateCustomParameter() { String paramName = "_csrf"; this.repo.setParameterName(paramName); this.token = this.repo.generateToken(this.request); assertThat(this.token.getParameterName()).isEqualTo(paramName); assertThat(this.token.getToken()).isNotEmpty(); } @Test public void generateCustomHeader() { String headerName = "CSRF"; this.repo.setHeaderName(headerName); this.token = this.repo.generateToken(this.request); assertThat(this.token.getHeaderName()).isEqualTo(headerName); assertThat(this.token.getToken()).isNotEmpty(); } @Test public void loadTokenNull() { assertThat(this.repo.loadToken(this.request)).isNull(); assertThat(this.request.getSession(false)).isNull(); } @Test public void loadTokenNullWhenSessionExists() { this.request.getSession(); assertThat(this.repo.loadToken(this.request)).isNull(); } @Test public void loadDeferredTokenWhenDoesNotExistThenGeneratedAndSaved() { DeferredCsrfToken deferredCsrfToken = this.repo.loadDeferredToken(this.request, this.response); CsrfToken csrfToken = deferredCsrfToken.get(); assertThat(csrfToken).isNotNull(); assertThat(deferredCsrfToken.isGenerated()).isTrue(); String attrName = this.request.getSession().getAttributeNames().nextElement(); assertThatCsrfToken(this.request.getSession().getAttribute(attrName)).isEqualTo(csrfToken); } @Test public void loadDeferredTokenWhenExistsThenLoaded() { CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def"); this.repo.saveToken(tokenToSave, this.request, this.response); DeferredCsrfToken deferredCsrfToken = this.repo.loadDeferredToken(this.request, this.response); CsrfToken csrfToken = deferredCsrfToken.get(); assertThatCsrfToken(csrfToken).isEqualTo(tokenToSave); assertThat(deferredCsrfToken.isGenerated()).isFalse(); } @Test public void saveToken() { CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def"); this.repo.saveToken(tokenToSave, this.request, this.response); String attrName = this.request.getSession().getAttributeNames().nextElement(); CsrfToken loadedToken = (CsrfToken) this.request.getSession().getAttribute(attrName); assertThat(loadedToken).isEqualTo(tokenToSave); } @Test public void saveTokenCustomSessionAttribute() { CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def"); String sessionAttributeName = "custom"; this.repo.setSessionAttributeName(sessionAttributeName); this.repo.saveToken(tokenToSave, this.request, this.response); CsrfToken loadedToken = (CsrfToken) this.request.getSession().getAttribute(sessionAttributeName); assertThat(loadedToken).isEqualTo(tokenToSave); } @Test public void saveTokenNullToken() { saveToken(); this.repo.saveToken(null, this.request, this.response); assertThat(this.request.getSession().getAttributeNames().hasMoreElements()).isFalse(); } @Test public void saveTokenNullTokenWhenSessionNotExists() { this.repo.saveToken(null, this.request, this.response); assertThat(this.request.getSession(false)).isNull(); } @Test public void setSessionAttributeNameEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> this.repo.setSessionAttributeName("")); } @Test public void setSessionAttributeNameNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.repo.setSessionAttributeName(null)); } @Test public void setParameterNameEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> this.repo.setParameterName("")); } @Test public void setParameterNameNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.repo.setParameterName(null)); } }
5,491
32.901235
99
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/CookieCsrfTokenRepositoryTests.java
/* * 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.csrf; 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; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.springframework.security.web.csrf.CsrfTokenAssert.assertThatCsrfToken; /** * @author Rob Winch * @author Alex Montoya * @since 4.1 */ class CookieCsrfTokenRepositoryTests { CookieCsrfTokenRepository repository; MockHttpServletResponse response; MockHttpServletRequest request; @BeforeEach void setup() { this.repository = new CookieCsrfTokenRepository(); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.request.setContextPath("/context"); } @Test void generateToken() { CsrfToken generateToken = this.repository.generateToken(this.request); assertThat(generateToken).isNotNull(); assertThat(generateToken.getHeaderName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_HEADER_NAME); assertThat(generateToken.getParameterName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_PARAMETER_NAME); assertThat(generateToken.getToken()).isNotEmpty(); } @Test void generateTokenCustom() { String headerName = "headerName"; String parameterName = "paramName"; this.repository.setHeaderName(headerName); this.repository.setParameterName(parameterName); CsrfToken generateToken = this.repository.generateToken(this.request); assertThat(generateToken).isNotNull(); assertThat(generateToken.getHeaderName()).isEqualTo(headerName); assertThat(generateToken.getParameterName()).isEqualTo(parameterName); assertThat(generateToken.getToken()).isNotEmpty(); } @Test 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); assertThat(tokenCookie.getMaxAge()).isEqualTo(-1); assertThat(tokenCookie.getName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME); assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath()); assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure()); assertThat(tokenCookie.getValue()).isEqualTo(token.getToken()); assertThat(tokenCookie.isHttpOnly()).isTrue(); } @Test void saveTokenSecure() { this.request.setSecure(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 saveTokenSecureFlagTrue() { this.request.setSecure(false); this.repository.setSecure(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 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() { this.request.setSecure(true); this.repository.setSecure(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 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() { this.request.setSecure(true); this.repository.saveToken(null, this.request, this.response); Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME); assertThat(tokenCookie.getMaxAge()).isZero(); assertThat(tokenCookie.getName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME); assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath()); assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure()); assertThat(tokenCookie.getValue()).isEmpty(); } @Test void saveTokenHttpOnlyTrue() { this.repository.setCookieHttpOnly(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 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() { this.repository.setCookieHttpOnly(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 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() { this.repository = CookieCsrfTokenRepository.withHttpOnlyFalse(); 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 saveTokenCustomPath() { String customPath = "/custompath"; this.repository.setCookiePath(customPath); 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.getPath()).isEqualTo(this.repository.getCookiePath()); } @Test void saveTokenEmptyCustomPath() { String customPath = ""; this.repository.setCookiePath(customPath); 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.getPath()).isEqualTo(this.request.getContextPath()); } @Test void saveTokenNullCustomPath() { String customPath = null; this.repository.setCookiePath(customPath); 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.getPath()).isEqualTo(this.request.getContextPath()); } @Test void saveTokenWithCookieDomain() { String domainName = "example.com"; this.repository.setCookieDomain(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 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() { int maxAge = 1200; this.repository.setCookieMaxAge(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 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() { assertThat(this.repository.loadToken(this.request)).isNull(); } @Test void loadTokenCookieIncorrectNameNull() { this.request.setCookies(new Cookie("other", "name")); assertThat(this.repository.loadToken(this.request)).isNull(); } @Test void loadTokenCookieValueEmptyString() { this.request.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, "")); assertThat(this.repository.loadToken(this.request)).isNull(); } @Test void loadToken() { CsrfToken generateToken = this.repository.generateToken(this.request); this.request .setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generateToken.getToken())); CsrfToken loadToken = this.repository.loadToken(this.request); assertThat(loadToken).isNotNull(); assertThat(loadToken.getHeaderName()).isEqualTo(generateToken.getHeaderName()); assertThat(loadToken.getParameterName()).isEqualTo(generateToken.getParameterName()); assertThat(loadToken.getToken()).isNotEmpty(); } @Test void loadTokenCustom() { String cookieName = "cookieName"; String value = "value"; String headerName = "headerName"; String parameterName = "paramName"; this.repository.setHeaderName(headerName); this.repository.setParameterName(parameterName); this.repository.setCookieName(cookieName); this.request.setCookies(new Cookie(cookieName, value)); CsrfToken loadToken = this.repository.loadToken(this.request); assertThat(loadToken).isNotNull(); assertThat(loadToken.getHeaderName()).isEqualTo(headerName); assertThat(loadToken.getParameterName()).isEqualTo(parameterName); assertThat(loadToken.getToken()).isEqualTo(value); } @Test void loadDeferredTokenWhenDoesNotExistThenGeneratedAndSaved() { DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response); CsrfToken csrfToken = deferredCsrfToken.get(); assertThat(csrfToken).isNotNull(); assertThat(deferredCsrfToken.isGenerated()).isTrue(); Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME); assertThat(tokenCookie).isNotNull(); assertThat(tokenCookie.getMaxAge()).isEqualTo(-1); assertThat(tokenCookie.getName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME); assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath()); assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure()); assertThat(tokenCookie.getValue()).isEqualTo(csrfToken.getToken()); assertThat(tokenCookie.isHttpOnly()).isEqualTo(true); } @Test void loadDeferredTokenWhenExistsAndNullSavedThenGeneratedAndSaved() { CsrfToken generatedToken = this.repository.generateToken(this.request); this.request .setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken())); this.repository.saveToken(null, this.request, this.response); DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response); CsrfToken csrfToken = deferredCsrfToken.get(); assertThat(csrfToken).isNotNull(); assertThat(generatedToken).isNotEqualTo(csrfToken); assertThat(deferredCsrfToken.isGenerated()).isTrue(); } @Test void loadDeferredTokenWhenExistsAndNullSavedAndNonNullSavedThenLoaded() { CsrfToken generatedToken = this.repository.generateToken(this.request); this.request .setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken())); this.repository.saveToken(null, this.request, this.response); this.repository.saveToken(generatedToken, this.request, this.response); DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response); CsrfToken csrfToken = deferredCsrfToken.get(); assertThatCsrfToken(csrfToken).isEqualTo(generatedToken); assertThat(deferredCsrfToken.isGenerated()).isFalse(); } @Test void loadDeferredTokenWhenExistsThenLoaded() { CsrfToken generatedToken = this.repository.generateToken(this.request); this.request .setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken())); DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response); CsrfToken csrfToken = deferredCsrfToken.get(); assertThatCsrfToken(csrfToken).isEqualTo(generatedToken); assertThat(deferredCsrfToken.isGenerated()).isFalse(); } @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); } @Test void setCookieNameNullIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCookieName(null)); } @Test void setParameterNameNullIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setParameterName(null)); } @Test void setHeaderNameNullIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setHeaderName(null)); } @Test void setCookieMaxAgeZeroIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCookieMaxAge(0)); } }
18,898
41.279642
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/csrf/CsrfTokenAssert.java
/* * 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. * 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.csrf; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.Assertions; /** * Assertion for validating the properties on CsrfToken are the same. */ public class CsrfTokenAssert extends AbstractAssert<CsrfTokenAssert, CsrfToken> { protected CsrfTokenAssert(CsrfToken csrfToken) { super(csrfToken, CsrfTokenAssert.class); } public static CsrfTokenAssert assertThatCsrfToken(Object csrfToken) { return new CsrfTokenAssert((CsrfToken) csrfToken); } public static CsrfTokenAssert assertThat(CsrfToken csrfToken) { return new CsrfTokenAssert(csrfToken); } public CsrfTokenAssert isEqualTo(CsrfToken csrfToken) { isNotNull(); assertThat(csrfToken).isNotNull(); Assertions.assertThat(this.actual.getHeaderName()).isEqualTo(csrfToken.getHeaderName()); Assertions.assertThat(this.actual.getParameterName()).isEqualTo(csrfToken.getParameterName()); Assertions.assertThat(this.actual.getToken()).isEqualTo(csrfToken.getToken()); return this; } }
1,651
32.714286
96
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/SecurityContextHolderFilterTests.java
/* * 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. * 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.context; import java.util.function.Supplier; import jakarta.servlet.DispatcherType; 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.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockFilterChain; import org.springframework.security.authentication.TestAuthentication; import org.springframework.security.core.Authentication; 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.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @ExtendWith(MockitoExtension.class) class SecurityContextHolderFilterTests { private static final String FILTER_APPLIED = "org.springframework.security.web.context.SecurityContextHolderFilter.APPLIED"; @Mock private SecurityContextRepository repository; @Mock private SecurityContextHolderStrategy strategy; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Captor private ArgumentCaptor<HttpServletRequest> requestArg; private SecurityContextHolderFilter filter; @BeforeEach void setup() { this.filter = new SecurityContextHolderFilter(this.repository); } @AfterEach void cleanup() { SecurityContextHolder.clearContext(); } @Test void doFilterThenSetsAndClearsSecurityContextHolder() throws Exception { Authentication authentication = TestAuthentication.authenticatedUser(); SecurityContext expectedContext = new SecurityContextImpl(authentication); given(this.repository.loadDeferredContext(this.requestArg.capture())) .willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy)); FilterChain filterChain = (request, response) -> assertThat(SecurityContextHolder.getContext()) .isEqualTo(expectedContext); this.filter.doFilter(this.request, this.response, filterChain); assertThat(SecurityContextHolder.getContext()).isEqualTo(SecurityContextHolder.createEmptyContext()); } @Test void doFilterThenSetsAndClearsSecurityContextHolderStrategy() throws Exception { Authentication authentication = TestAuthentication.authenticatedUser(); SecurityContext expectedContext = new SecurityContextImpl(authentication); given(this.repository.loadDeferredContext(this.requestArg.capture())) .willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy)); FilterChain filterChain = (request, response) -> { }; this.filter.setSecurityContextHolderStrategy(this.strategy); this.filter.doFilter(this.request, this.response, filterChain); ArgumentCaptor<Supplier<SecurityContext>> deferredContextArg = ArgumentCaptor.forClass(Supplier.class); verify(this.strategy).setDeferredContext(deferredContextArg.capture()); assertThat(deferredContextArg.getValue().get()).isEqualTo(expectedContext); verify(this.strategy).clearContext(); } @Test void doFilterWhenFilterAppliedThenDoNothing() throws Exception { given(this.request.getAttribute(FILTER_APPLIED)).willReturn(true); this.filter.doFilter(this.request, this.response, new MockFilterChain()); verify(this.request, times(1)).getAttribute(FILTER_APPLIED); verifyNoInteractions(this.repository, this.response); } @Test void doFilterWhenNotAppliedThenSetsAndRemovesAttribute() throws Exception { given(this.repository.loadDeferredContext(this.requestArg.capture())).willReturn( new SupplierDeferredSecurityContext(SecurityContextHolder::createEmptyContext, this.strategy)); this.filter.doFilter(this.request, this.response, new MockFilterChain()); InOrder inOrder = inOrder(this.request, this.repository); inOrder.verify(this.request).setAttribute(FILTER_APPLIED, true); inOrder.verify(this.repository).loadDeferredContext(this.request); inOrder.verify(this.request).removeAttribute(FILTER_APPLIED); } @ParameterizedTest @EnumSource(DispatcherType.class) void doFilterWhenAnyDispatcherTypeThenFilter(DispatcherType dispatcherType) throws Exception { lenient().when(this.request.getDispatcherType()).thenReturn(dispatcherType); Authentication authentication = TestAuthentication.authenticatedUser(); SecurityContext expectedContext = new SecurityContextImpl(authentication); given(this.repository.loadDeferredContext(this.requestArg.capture())) .willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy)); FilterChain filterChain = (request, response) -> assertThat(SecurityContextHolder.getContext()) .isEqualTo(expectedContext); this.filter.doFilter(this.request, this.response, filterChain); } }
6,111
38.947712
125
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/RequestAttributeSecurityContextRepositoryTests.java
/* * 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. * 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.context; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestAuthentication; 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.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch */ class RequestAttributeSecurityContextRepositoryTests { private MockHttpServletRequest request = new MockHttpServletRequest(); private MockHttpServletResponse response = new MockHttpServletResponse(); private RequestAttributeSecurityContextRepository repository = new RequestAttributeSecurityContextRepository(); private SecurityContext expectedSecurityContext = new SecurityContextImpl(TestAuthentication.authenticatedUser()); @Test void setSecurityContextHolderStrategyWhenNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.repository.setSecurityContextHolderStrategy(null)) .withMessage("securityContextHolderStrategy cannot be null"); // @formatter:on } @Test void saveContextAndLoadContextThenFound() { this.repository.saveContext(this.expectedSecurityContext, this.request, this.response); SecurityContext securityContext = this.repository .loadContext(new HttpRequestResponseHolder(this.request, this.response)); assertThat(securityContext).isEqualTo(this.expectedSecurityContext); } @Test void saveContextWhenLoadContextAndNewRequestThenNotFound() { this.repository.saveContext(this.expectedSecurityContext, this.request, this.response); SecurityContext securityContext = this.repository.loadContext( new HttpRequestResponseHolder(new MockHttpServletRequest(), new MockHttpServletResponse())); assertThat(securityContext).isEqualTo(SecurityContextHolder.createEmptyContext()); } @Test void containsContextWhenNotSavedThenFalse() { assertThat(this.repository.containsContext(this.request)).isFalse(); } @Test void containsContextWhenSavedThenTrue() { this.repository.saveContext(this.expectedSecurityContext, this.request, this.response); assertThat(this.repository.containsContext(this.request)).isTrue(); } @Test void loadDeferredContextWhenNotPresentThenEmptyContext() { Supplier<SecurityContext> deferredContext = this.repository.loadDeferredContext(this.request); assertThat(deferredContext.get()).isEqualTo(SecurityContextHolder.createEmptyContext()); } @Test void loadContextWhenNotPresentThenEmptyContext() { SecurityContext context = this.repository .loadContext(new HttpRequestResponseHolder(this.request, this.response)); assertThat(context).isEqualTo(SecurityContextHolder.createEmptyContext()); } @Test void loadContextWhenCustomSecurityContextHolderStrategySetThenUsed() { SecurityContextHolderStrategy securityContextHolderStrategy = mock(SecurityContextHolderStrategy.class); given(securityContextHolderStrategy.createEmptyContext()).willReturn(new SecurityContextImpl()); this.repository.setSecurityContextHolderStrategy(securityContextHolderStrategy); Supplier<SecurityContext> deferredContext = this.repository.loadDeferredContext(this.request); assertThat(deferredContext.get()).isNotNull(); verify(securityContextHolderStrategy).createEmptyContext(); verifyNoMoreInteractions(securityContextHolderStrategy); } }
4,601
39.725664
115
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/SecurityContextRepositoryTests.java
/* * 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. * 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.context; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.security.core.context.DeferredSecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch */ class SecurityContextRepositoryTests { SecurityContextRepository repository = spy(SecurityContextRepository.class); @Test void loadContextHttpRequestResponseHolderWhenInvokeSupplierTwiceThenOnlyInvokesLoadContextOnce() { given(this.repository.loadContext(any(HttpRequestResponseHolder.class))).willReturn(new SecurityContextImpl()); DeferredSecurityContext deferredContext = this.repository.loadDeferredContext(mock(HttpServletRequest.class)); verify(this.repository).loadDeferredContext(any(HttpServletRequest.class)); deferredContext.get(); verify(this.repository).loadContext(any(HttpRequestResponseHolder.class)); deferredContext.get(); verifyNoMoreInteractions(this.repository); } }
1,915
36.568627
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java
/* * 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.context; import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collections; import jakarta.servlet.Filter; import jakarta.servlet.ServletException; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponseWrapper; import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.TestAuthentication; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.Transient; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.context.TransientSecurityContext; import org.springframework.security.core.userdetails.PasswordEncodedUser; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * @author Luke Taylor * @author Rob Winch */ public class HttpSessionSecurityContextRepositoryTests { private final TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A"); @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void startAsyncDisablesSaveOnCommit() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); repo.loadContext(holder); reset(request); holder.getRequest().startAsync(); holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST); // ensure that sendError did cause interaction with the HttpSession verify(request, never()).getSession(anyBoolean()); verify(request, never()).getSession(); } @Test public void startAsyncRequestResponseDisablesSaveOnCommit() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); repo.loadContext(holder); reset(request); holder.getRequest().startAsync(request, response); holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST); // ensure that sendError did cause interaction with the HttpSession verify(request, never()).getSession(anyBoolean()); verify(request, never()).getSession(); } @Test public void sessionIsntCreatedIfContextDoesntChange() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); assertThat(request.getSession(false)).isNull(); repo.saveContext(context, holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNull(); } @Test public void sessionIsntCreatedIfAllowSessionCreationIsFalse() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setAllowSessionCreation(false); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); // Change context context.setAuthentication(this.testToken); repo.saveContext(context, holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNull(); } @Test public void loadContextWhenNullResponse() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, null); assertThat(repo.loadContext(holder)).isEqualTo(SecurityContextHolder.createEmptyContext()); } @Test public void loadContextHttpServletRequestWhenNotSavedThenEmptyContextReturned() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(repo.loadDeferredContext(request).get()).isEqualTo(SecurityContextHolder.createEmptyContext()); } @Test public void loadContextHttpServletRequestWhenSavedThenSavedContextReturned() { SecurityContextImpl expectedContext = new SecurityContextImpl(this.testToken); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.saveContext(expectedContext, request, response); assertThat(repo.loadDeferredContext(request).get()).isEqualTo(expectedContext); } @Test public void loadContextHttpServletRequestWhenNotAccessedThenHttpSessionNotAccessed() { HttpSession session = mock(HttpSession.class); HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); repo.loadDeferredContext(request); verifyNoInteractions(session); } @Test public void existingContextIsSuccessFullyLoadedFromSessionAndSavedBack() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContextHolder.getContext().setAuthentication(this.testToken); request.getSession().setAttribute("imTheContext", SecurityContextHolder.getContext()); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); assertThat(context).isNotNull(); assertThat(context.getAuthentication()).isEqualTo(this.testToken); // Won't actually be saved as it hasn't changed, but go through the use case // anyway repo.saveContext(context, holder.getRequest(), holder.getResponse()); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(context); } // SEC-1528 @Test public void saveContextCallsSetAttributeIfContextIsModifiedDirectlyDuringRequest() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); // Set up an existing authenticated context, mocking that it is in the session // already SecurityContext ctx = SecurityContextHolder.getContext(); ctx.setAuthentication(this.testToken); HttpSession session = mock(HttpSession.class); given(session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).willReturn(ctx); request.setSession(session); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); assertThat(repo.loadContext(holder)).isSameAs(ctx); // Modify context contents. Same user, different role SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("someone", "passwd", "ROLE_B")); repo.saveContext(ctx, holder.getRequest(), holder.getResponse()); // Must be called even though the value in the local VM is already the same verify(session).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctx); } @Test public void saveContextWhenSaveNewContextThenOriginalContextThenOriginalContextSaved() throws Exception { HttpSessionSecurityContextRepository repository = new HttpSessionSecurityContextRepository(); SecurityContextPersistenceFilter securityContextPersistenceFilter = new SecurityContextPersistenceFilter( repository); UserDetails original = User.withUsername("user").password("password").roles("USER").build(); SecurityContext originalContext = createSecurityContext(original); UserDetails impersonate = User.withUserDetails(original).username("impersonate").build(); SecurityContext impersonateContext = createSecurityContext(impersonate); MockHttpServletRequest mockRequest = new MockHttpServletRequest(); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); Filter saveImpersonateContext = (request, response, chain) -> { SecurityContextHolder.setContext(impersonateContext); // ensure the response is committed to trigger save response.flushBuffer(); chain.doFilter(request, response); }; Filter saveOriginalContext = (request, response, chain) -> { SecurityContextHolder.setContext(originalContext); chain.doFilter(request, response); }; HttpServlet servlet = new HttpServlet() { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("Hi"); } }; SecurityContextHolder.setContext(originalContext); MockFilterChain chain = new MockFilterChain(servlet, saveImpersonateContext, saveOriginalContext); securityContextPersistenceFilter.doFilter(mockRequest, mockResponse, chain); assertThat( mockRequest.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) .isEqualTo(originalContext); } @Test public void nonSecurityContextInSessionIsIgnored() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContextHolder.getContext().setAuthentication(this.testToken); request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, "NotASecurityContextInstance"); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); assertThat(context).isNotNull(); assertThat(context.getAuthentication()).isNull(); } @Test public void sessionIsCreatedAndContextStoredWhenContextChanges() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); assertThat(request.getSession(false)).isNull(); // Simulate authentication during the request context.setAuthentication(this.testToken); repo.saveContext(context, holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNotNull(); assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) .isEqualTo(context); } @Test public void redirectCausesEarlySaveOfContext() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().sendRedirect("/doesntmatter"); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); } @Test public void sendErrorCausesEarlySaveOfContext() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().sendError(404); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); } // SEC-2005 @Test public void flushBufferCausesEarlySaveOfContext() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().flushBuffer(); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); } // SEC-2005 @Test public void writerFlushCausesEarlySaveOfContext() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().getWriter().flush(); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); } // SEC-2005 @Test public void writerCloseCausesEarlySaveOfContext() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().getWriter().close(); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); } // SEC-2005 @Test public void outputStreamFlushCausesEarlySaveOfContext() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().getOutputStream().flush(); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); } // SEC-2005 @Test public void outputStreamCloseCausesEarlySaveOfContext() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().getOutputStream().close(); assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext()); } // SEC-SEC-2055 @Test public void outputStreamCloseDelegate() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream outputstream = mock(ServletOutputStream.class); given(response.getOutputStream()).willReturn(outputstream); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().getOutputStream().close(); verify(outputstream).close(); } // SEC-SEC-2055 @Test public void outputStreamFlushesDelegate() throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream outputstream = mock(ServletOutputStream.class); given(response.getOutputStream()).willReturn(outputstream); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); holder.getResponse().getOutputStream().flush(); verify(outputstream).flush(); } @Test public void noSessionIsCreatedIfSessionWasInvalidatedDuringTheRequest() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); request.getSession().invalidate(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNull(); } // SEC-1315 @Test public void noSessionIsCreatedIfAnonymousTokenIsUsed() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication( new AnonymousAuthenticationToken("key", "anon", AuthorityUtils.createAuthorityList("ANON"))); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNull(); } // SEC-1587 @Test public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); ctxInSession.setAuthentication(this.testToken); request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctxInSession); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); SecurityContextHolder.getContext() .setAuthentication(new AnonymousAuthenticationToken("x", "x", this.testToken.getAuthorities())); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) .isNull(); } @Test public void contextIsRemovedFromSessionIfCurrentContextIsEmpty() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); repo.setSpringSecurityContextKey("imTheContext"); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); ctxInSession.setAuthentication(this.testToken); request.getSession().setAttribute("imTheContext", ctxInSession); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); // Save an empty context repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); assertThat(request.getSession().getAttribute("imTheContext")).isNull(); } // SEC-1735 @Test public void contextIsNotRemovedFromSessionIfContextBeforeExecutionDefault() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); ctxInSession.setAuthentication(this.testToken); request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctxInSession); SecurityContextHolder.getContext().setAuthentication( new AnonymousAuthenticationToken("x", "x", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); assertThat(ctxInSession).isSameAs( request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); } // SEC-3070 @Test public void logoutInvalidateSessionFalseFails() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); ctxInSession.setAuthentication(this.testToken); request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctxInSession); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); ctxInSession.setAuthentication(null); repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse()); assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) .isNull(); } @Test @SuppressWarnings("deprecation") public void sessionDisableUrlRewritingPreventsSessionIdBeingWrittenToUrl() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); final String sessionId = ";jsessionid=id"; MockHttpServletResponse response = new MockHttpServletResponse() { @Override public String encodeRedirectURL(String url) { return url + sessionId; } @Override public String encodeURL(String url) { return url + sessionId; } }; HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); repo.loadContext(holder); String url = "/aUrl"; assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo(url + sessionId); assertThat(holder.getResponse().encodeURL(url)).isEqualTo(url + sessionId); repo.setDisableUrlRewriting(true); holder = new HttpRequestResponseHolder(request, response); repo.loadContext(holder); assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo(url); assertThat(holder.getResponse().encodeURL(url)).isEqualTo(url); } @Test public void saveContextCustomTrustResolver() { SecurityContext contextToSave = SecurityContextHolder.createEmptyContext(); contextToSave.setAuthentication(this.testToken); HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class); repo.setTrustResolver(trustResolver); repo.saveContext(contextToSave, holder.getRequest(), holder.getResponse()); verify(trustResolver).isAnonymous(contextToSave.getAuthentication()); } @Test public void setTrustResolverNull() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); assertThatIllegalArgumentException().isThrownBy(() -> repo.setTrustResolver(null)); } // SEC-2578 @Test public void traverseWrappedRequests() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); assertThat(request.getSession(false)).isNull(); // Simulate authentication during the request context.setAuthentication(this.testToken); repo.saveContext(context, new HttpServletRequestWrapper(holder.getRequest()), new HttpServletResponseWrapper(holder.getResponse())); assertThat(request.getSession(false)).isNotNull(); assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) .isEqualTo(context); } @Test public void standardResponseWorks() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(this.testToken); repo.saveContext(context, request, response); assertThat(request.getSession(false)).isNotNull(); assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) .isEqualTo(context); } @Test public void saveContextWhenTransientSecurityContextThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SecurityContext transientSecurityContext = new TransientSecurityContext(); Authentication authentication = TestAuthentication.authenticatedUser(); transientSecurityContext.setAuthentication(authentication); repo.saveContext(transientSecurityContext, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(session).isNull(); } @Test public void saveContextWhenTransientSecurityContextSubclassThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SecurityContext transientSecurityContext = new TransientSecurityContext() { }; Authentication authentication = TestAuthentication.authenticatedUser(); transientSecurityContext.setAuthentication(authentication); repo.saveContext(transientSecurityContext, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(session).isNull(); } @Test public void saveContextWhenTransientSecurityContextAndSessionExistsThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession(); // ensure the session exists MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SecurityContext transientSecurityContext = new TransientSecurityContext(); Authentication authentication = TestAuthentication.authenticatedUser(); transientSecurityContext.setAuthentication(authentication); repo.saveContext(transientSecurityContext, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(Collections.list(session.getAttributeNames())).isEmpty(); } @Test public void saveContextWhenTransientSecurityContextWithCustomAnnotationThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SecurityContext transientSecurityContext = new TransientSecurityContext(); Authentication authentication = TestAuthentication.authenticatedUser(); transientSecurityContext.setAuthentication(authentication); repo.saveContext(transientSecurityContext, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(session).isNull(); } @Test public void saveContextWhenTransientAuthenticationThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SomeTransientAuthentication authentication = new SomeTransientAuthentication(); context.setAuthentication(authentication); repo.saveContext(context, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(session).isNull(); } @Test public void saveContextWhenTransientAuthenticationSubclassThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SomeTransientAuthenticationSubclass authentication = new SomeTransientAuthenticationSubclass(); context.setAuthentication(authentication); repo.saveContext(context, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(session).isNull(); } @Test public void saveContextWhenTransientAuthenticationAndSessionExistsThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession(); // ensure the session exists MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SomeTransientAuthentication authentication = new SomeTransientAuthentication(); context.setAuthentication(authentication); repo.saveContext(context, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(Collections.list(session.getAttributeNames())).isEmpty(); } @Test public void saveContextWhenTransientAuthenticationWithCustomAnnotationThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); SomeOtherTransientAuthentication authentication = new SomeOtherTransientAuthentication(); context.setAuthentication(authentication); repo.saveContext(context, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(session).isNull(); } // gh-8947 @Test public void saveContextWhenSecurityContextAuthenticationUpdatedToNullThenSkipped() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SomeOtherTransientAuthentication authentication = new SomeOtherTransientAuthentication(); repo.loadContext(holder); SecurityContext context = mock(SecurityContext.class); given(context.getAuthentication()).willReturn(authentication).willReturn(null); repo.saveContext(context, holder.getRequest(), holder.getResponse()); MockHttpSession session = (MockHttpSession) request.getSession(false); assertThat(session).isNull(); } @Test public void saveContextWhenSecurityContextEmptyThenRemoveAttributeFromSession() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext emptyContext = SecurityContextHolder.createEmptyContext(); MockHttpSession session = (MockHttpSession) request.getSession(true); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, emptyContext); repo.saveContext(emptyContext, request, response); Object attributeAfterSave = session .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); assertThat(attributeAfterSave).isNull(); } @Test public void saveContextWhenSecurityContextEmptyAndNoSessionThenDoesNotCreateSession() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext emptyContext = SecurityContextHolder.createEmptyContext(); repo.saveContext(emptyContext, request, response); assertThat(request.getSession(false)).isNull(); } @Test public void saveContextWhenSecurityContextThenSaveInSession() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext context = createSecurityContext(PasswordEncodedUser.user()); repo.saveContext(context, request, response); Object savedContext = request.getSession() .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); assertThat(savedContext).isEqualTo(context); } @Test public void saveContextWhenTransientAuthenticationThenDoNotSave() { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new SomeTransientAuthentication()); repo.saveContext(context, request, response); assertThat(request.getSession(false)).isNull(); } private SecurityContext createSecurityContext(UserDetails userDetails) { UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.authenticated(userDetails, userDetails.getPassword(), userDetails.getAuthorities()); SecurityContext securityContext = new SecurityContextImpl(token); return securityContext; } @Transient private static class SomeTransientAuthentication extends AbstractAuthenticationToken { SomeTransientAuthentication() { super(null); } @Override public Object getCredentials() { return null; } @Override public Object getPrincipal() { return null; } } private static class SomeTransientAuthenticationSubclass extends SomeTransientAuthentication { } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Transient public @interface TestTransientAuthentication { } @TestTransientAuthentication private static class SomeOtherTransientAuthentication extends AbstractAuthenticationToken { SomeOtherTransientAuthentication() { super(null); } @Override public Object getCredentials() { return null; } @Override public Object getPrincipal() { return null; } } }
42,859
49.070093
116
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/SaveContextOnUpdateOrErrorResponseWrapperTests.java
/* * 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. * 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.context; 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.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class SaveContextOnUpdateOrErrorResponseWrapperTests { @Mock private SecurityContext securityContext; private MockHttpServletResponse response; private SaveContextOnUpdateOrErrorResponseWrapperStub wrappedResponse; @BeforeEach public void setUp() { this.response = new MockHttpServletResponse(); this.wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(this.response, true); SecurityContextHolder.setContext(this.securityContext); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void sendErrorSavesSecurityContext() throws Exception { int error = HttpServletResponse.SC_FORBIDDEN; this.wrappedResponse.sendError(error); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); assertThat(this.response.getStatus()).isEqualTo(error); } @Test public void sendErrorSkipsSaveSecurityContextDisables() throws Exception { final int error = HttpServletResponse.SC_FORBIDDEN; this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.sendError(error); assertThat(this.wrappedResponse.securityContext).isNull(); assertThat(this.response.getStatus()).isEqualTo(error); } @Test public void sendErrorWithMessageSavesSecurityContext() throws Exception { int error = HttpServletResponse.SC_FORBIDDEN; String message = "Forbidden"; this.wrappedResponse.sendError(error, message); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); assertThat(this.response.getStatus()).isEqualTo(error); assertThat(this.response.getErrorMessage()).isEqualTo(message); } @Test public void sendErrorWithMessageSkipsSaveSecurityContextDisables() throws Exception { final int error = HttpServletResponse.SC_FORBIDDEN; final String message = "Forbidden"; this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.sendError(error, message); assertThat(this.wrappedResponse.securityContext).isNull(); assertThat(this.response.getStatus()).isEqualTo(error); assertThat(this.response.getErrorMessage()).isEqualTo(message); } @Test public void sendRedirectSavesSecurityContext() throws Exception { String url = "/location"; this.wrappedResponse.sendRedirect(url); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); assertThat(this.response.getRedirectedUrl()).isEqualTo(url); } @Test public void sendRedirectSkipsSaveSecurityContextDisables() throws Exception { final String url = "/location"; this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.sendRedirect(url); assertThat(this.wrappedResponse.securityContext).isNull(); assertThat(this.response.getRedirectedUrl()).isEqualTo(url); } @Test public void outputFlushSavesSecurityContext() throws Exception { this.wrappedResponse.getOutputStream().flush(); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); } @Test public void outputFlushSkipsSaveSecurityContextDisables() throws Exception { this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.getOutputStream().flush(); assertThat(this.wrappedResponse.securityContext).isNull(); } @Test public void outputCloseSavesSecurityContext() throws Exception { this.wrappedResponse.getOutputStream().close(); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); } @Test public void outputCloseSkipsSaveSecurityContextDisables() throws Exception { this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.getOutputStream().close(); assertThat(this.wrappedResponse.securityContext).isNull(); } @Test public void writerFlushSavesSecurityContext() throws Exception { this.wrappedResponse.getWriter().flush(); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); } @Test public void writerFlushSkipsSaveSecurityContextDisables() throws Exception { this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.getWriter().flush(); assertThat(this.wrappedResponse.securityContext).isNull(); } @Test public void writerCloseSavesSecurityContext() throws Exception { this.wrappedResponse.getWriter().close(); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); } @Test public void writerCloseSkipsSaveSecurityContextDisables() throws Exception { this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.getWriter().close(); assertThat(this.wrappedResponse.securityContext).isNull(); } @Test public void flushBufferSavesSecurityContext() throws Exception { this.wrappedResponse.flushBuffer(); assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext); } @Test public void flushBufferSkipsSaveSecurityContextDisables() throws Exception { this.wrappedResponse.disableSaveOnResponseCommitted(); this.wrappedResponse.flushBuffer(); assertThat(this.wrappedResponse.securityContext).isNull(); } private static class SaveContextOnUpdateOrErrorResponseWrapperStub extends SaveContextOnUpdateOrErrorResponseWrapper { private SecurityContext securityContext; SaveContextOnUpdateOrErrorResponseWrapperStub(HttpServletResponse response, boolean disableUrlRewriting) { super(response, disableUrlRewriting); } @Override protected void saveContext(SecurityContext context) { this.securityContext = context; } } }
6,795
33.673469
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java
/* * 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. * 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.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; import jakarta.servlet.Filter; import jakarta.servlet.FilterRegistration; import jakarta.servlet.ServletContext; import jakarta.servlet.SessionTrackingMode; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.session.HttpSessionEventPublisher; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.filter.DelegatingFilterProxy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willDoNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @author Josh Cummings */ public class AbstractSecurityWebApplicationInitializerTests { private static final EnumSet<DispatcherType> DEFAULT_DISPATCH = EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC, DispatcherType.FORWARD, DispatcherType.INCLUDE); @Test public void onStartupWhenDefaultContextThenRegistersSpringSecurityFilterChain() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { }.onStartup(context); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(registration).setAsyncSupported(true); verifyNoAddListener(context); } @Test public void onStartupWhenConfigurationClassThenAddsContextLoaderListener() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) { }.onStartup(context); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(registration).setAsyncSupported(true); verify(context).addListener(any(ContextLoaderListener.class)); } @Test public void onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override protected boolean enableHttpSessionEventPublisher() { return true; } }.onStartup(context); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(registration).setAsyncSupported(true); verify(context).addListener(HttpSessionEventPublisher.class.getName()); } @Test public void onStartupWhenCustomSecurityDispatcherTypesThenUses() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override protected EnumSet<DispatcherType> getSecurityDispatcherTypes() { return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD); } }.onStartup(context); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*"); verify(registration).setAsyncSupported(true); verifyNoAddListener(context); } @Test public void onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override protected String getDispatcherWebApplicationContextSuffix() { return "dispatcher"; } }.onStartup(context); DelegatingFilterProxy proxy = proxyCaptor.getValue(); assertThat(proxy.getContextAttribute()) .isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher"); assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain"); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(registration).setAsyncSupported(true); verifyNoAddListener(context); } @Test public void onStartupWhenSpringSecurityFilterChainAlreadyRegisteredThenException() { ServletContext context = mock(ServletContext.class); assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { }.onStartup(context)).withMessage("Duplicate Filter registration for 'springSecurityFilterChain'. " + "Check to ensure the Filter is only configured once."); } @Test public void onStartupWhenInsertFiltersThenInserted() { Filter filter1 = mock(Filter.class); Filter filter2 = mock(Filter.class); ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); given(context.addFilter(anyString(), eq(filter1))).willReturn(registration); given(context.addFilter(anyString(), eq(filter2))).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(context, filter1, filter2); } }.onStartup(context); assertProxyDefaults(proxyCaptor.getValue()); verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(registration, times(3)).setAsyncSupported(true); verifyNoAddListener(context); verify(context).addFilter(anyString(), eq(filter1)); verify(context).addFilter(anyString(), eq(filter2)); } @Test public void onStartupWhenDuplicateFilterInsertedThenException() { Filter filter1 = mock(Filter.class); ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(context, filter1); } }.onStartup(context)).withMessage( "Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once."); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(context).addFilter(anyString(), eq(filter1)); } @Test public void onStartupWhenInsertFiltersEmptyThenException() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(context); } }.onStartup(context)).withMessage("filters cannot be null or empty"); assertProxyDefaults(proxyCaptor.getValue()); } @Test public void onStartupWhenNullFilterInsertedThenException() { Filter filter = mock(Filter.class); ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); given(context.addFilter(anyString(), eq(filter))).willReturn(registration); assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(context, filter, null); } }.onStartup(context)).withMessageContaining("filters cannot contain null values"); verify(context, times(2)).addFilter(anyString(), any(Filter.class)); } @Test public void onStartupWhenAppendFiltersThenAppended() { Filter filter1 = mock(Filter.class); Filter filter2 = mock(Filter.class); ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); given(context.addFilter(anyString(), eq(filter1))).willReturn(registration); given(context.addFilter(anyString(), eq(filter2))).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { appendFilters(context, filter1, filter2); } }.onStartup(context); verify(registration, times(1)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(registration, times(2)).addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*"); verify(registration, times(3)).setAsyncSupported(true); verifyNoAddListener(context); verify(context, times(3)).addFilter(anyString(), any(Filter.class)); } @Test public void onStartupWhenDuplicateFilterAppendedThenException() { Filter filter1 = mock(Filter.class); ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { appendFilters(context, filter1); } }.onStartup(context)).withMessage( "Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once."); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(context).addFilter(anyString(), eq(filter1)); } @Test public void onStartupWhenAppendFiltersEmptyThenException() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { appendFilters(context); } }.onStartup(context)).withMessage("filters cannot be null or empty"); assertProxyDefaults(proxyCaptor.getValue()); } @Test public void onStartupWhenNullFilterAppendedThenException() { Filter filter = mock(Filter.class); ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); given(context.addFilter(anyString(), eq(filter))).willReturn(registration); assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { appendFilters(context, filter, null); } }.onStartup(context)).withMessageContaining("filters cannot contain null values"); verify(context, times(2)).addFilter(anyString(), any(Filter.class)); } @Test public void onStartupWhenDefaultsThenSessionTrackingModes() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.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); assertProxyDefaults(proxyCaptor.getValue()); Set<SessionTrackingMode> modes = modesCaptor.getValue(); assertThat(modes).hasSize(1); assertThat(modes).containsExactly(SessionTrackingMode.COOKIE); } @Test public void onStartupWhenSessionTrackingModesConfiguredThenUsed() { ServletContext context = mock(ServletContext.class); FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.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() { @Override public Set<SessionTrackingMode> getSessionTrackingModes() { return Collections.singleton(SessionTrackingMode.SSL); } }.onStartup(context); assertProxyDefaults(proxyCaptor.getValue()); Set<SessionTrackingMode> modes = modesCaptor.getValue(); assertThat(modes).hasSize(1); assertThat(modes).containsExactly(SessionTrackingMode.SSL); } @Test public void defaultFilterNameEqualsSpringSecurityFilterChain() { assertThat(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) .isEqualTo("springSecurityFilterChain"); } private static void verifyNoAddListener(ServletContext context) { verify(context, times(0)).addListener(anyString()); verify(context, times(0)).addListener(any(EventListener.class)); verify(context, times(0)).addListener(any(Class.class)); } private static void assertProxyDefaults(DelegatingFilterProxy proxy) { assertThat(proxy.getContextAttribute()).isNull(); assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain"); } @Configuration static class MyRootConfiguration { } }
17,832
46.302387
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/DelegatingSecurityContextRepositoryTests.java
/* * 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.context; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.context.DeferredSecurityContext; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests for {@link DelegatingSecurityContextRepository}. * * @author Steve Riesenberg * @since 5.8 */ public class DelegatingSecurityContextRepositoryTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private SecurityContextHolderStrategy strategy; private SecurityContext securityContext; @BeforeEach public void setUp() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.strategy = mock(SecurityContextHolderStrategy.class); this.securityContext = mock(SecurityContext.class); } @ParameterizedTest @CsvSource({ "0,false", "1,false", "2,false", "-1,true" }) public void loadDeferredContextWhenIsGeneratedThenReturnsSecurityContext(int expectedIndex, boolean isGenerated) { SecurityContext actualSecurityContext = new SecurityContextImpl( new TestingAuthenticationToken("user", "password")); SecurityContext emptySecurityContext = new SecurityContextImpl(); given(this.strategy.createEmptyContext()).willReturn(emptySecurityContext); List<SecurityContextRepository> delegates = new ArrayList<>(); for (int i = 0; i < 3; i++) { SecurityContext context = (i == expectedIndex) ? actualSecurityContext : null; SecurityContextRepository repository = mock(SecurityContextRepository.class); SupplierDeferredSecurityContext supplier = new SupplierDeferredSecurityContext(() -> context, this.strategy); given(repository.loadDeferredContext(this.request)).willReturn(supplier); delegates.add(repository); } DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegates); DeferredSecurityContext deferredSecurityContext = repository.loadDeferredContext(this.request); SecurityContext expectedSecurityContext = (isGenerated) ? emptySecurityContext : actualSecurityContext; assertThat(deferredSecurityContext.get()).isEqualTo(expectedSecurityContext); assertThat(deferredSecurityContext.isGenerated()).isEqualTo(isGenerated); for (SecurityContextRepository delegate : delegates) { verify(delegate).loadDeferredContext(this.request); verifyNoMoreInteractions(delegate); } } @Test public void saveContextAlwaysCallsDelegates() { List<SecurityContextRepository> delegates = new ArrayList<>(); for (int i = 0; i < 3; i++) { SecurityContextRepository repository = mock(SecurityContextRepository.class); delegates.add(repository); } DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegates); repository.saveContext(this.securityContext, this.request, this.response); for (SecurityContextRepository delegate : delegates) { verify(delegate).saveContext(this.securityContext, this.request, this.response); verifyNoMoreInteractions(delegate); } } @Test public void containsContextWhenAllDelegatesReturnFalseThenReturnsFalse() { List<SecurityContextRepository> delegates = new ArrayList<>(); for (int i = 0; i < 3; i++) { SecurityContextRepository repository = mock(SecurityContextRepository.class); given(repository.containsContext(this.request)).willReturn(false); delegates.add(repository); } DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegates); assertThat(repository.containsContext(this.request)).isFalse(); for (SecurityContextRepository delegate : delegates) { verify(delegate).containsContext(this.request); verifyNoMoreInteractions(delegate); } } @Test public void containsContextWhenFirstDelegatesReturnTrueThenReturnsTrue() { List<SecurityContextRepository> delegates = new ArrayList<>(); for (int i = 0; i < 3; i++) { SecurityContextRepository repository = mock(SecurityContextRepository.class); given(repository.containsContext(this.request)).willReturn(true); delegates.add(repository); } DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegates); assertThat(repository.containsContext(this.request)).isTrue(); verify(delegates.get(0)).containsContext(this.request); verifyNoInteractions(delegates.get(1)); verifyNoInteractions(delegates.get(2)); } // gh-12314 @Test public void loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate() { SecurityContextRepository delegate1 = mock(SecurityContextRepository.class); SecurityContextRepository delegate2 = mock(SecurityContextRepository.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response); SecurityContext securityContext1 = mock(SecurityContext.class); SecurityContext securityContext2 = mock(SecurityContext.class); given(delegate1.loadContext(holder)).willReturn(securityContext1); given(delegate1.containsContext(holder.getRequest())).willReturn(false); given(delegate2.loadContext(holder)).willReturn(securityContext2); given(delegate2.containsContext(holder.getRequest())).willReturn(true); DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2); SecurityContext returnedSecurityContext = repository.loadContext(holder); assertThat(returnedSecurityContext).isSameAs(securityContext2); } // gh-12314 @Test public void loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate() { SecurityContextRepository delegate1 = mock(SecurityContextRepository.class); SecurityContextRepository delegate2 = mock(SecurityContextRepository.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response); SecurityContext securityContext1 = mock(SecurityContext.class); SecurityContext securityContext2 = mock(SecurityContext.class); given(delegate1.loadContext(holder)).willReturn(securityContext1); given(delegate1.containsContext(holder.getRequest())).willReturn(true); given(delegate2.loadContext(holder)).willReturn(securityContext2); given(delegate2.containsContext(holder.getRequest())).willReturn(true); DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2); SecurityContext returnedSecurityContext = repository.loadContext(holder); assertThat(returnedSecurityContext).isSameAs(securityContext2); } // gh-12314 @Test public void loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate() { SecurityContextRepository delegate1 = mock(SecurityContextRepository.class); SecurityContextRepository delegate2 = mock(SecurityContextRepository.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response); SecurityContext securityContext1 = mock(SecurityContext.class); SecurityContext securityContext2 = mock(SecurityContext.class); given(delegate1.loadContext(holder)).willReturn(securityContext1); given(delegate1.containsContext(holder.getRequest())).willReturn(true); given(delegate2.loadContext(holder)).willReturn(securityContext2); given(delegate2.containsContext(holder.getRequest())).willReturn(false); DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2); SecurityContext returnedSecurityContext = repository.loadContext(holder); assertThat(returnedSecurityContext).isSameAs(securityContext1); } }
8,998
42.897561
115
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java
/* * 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. * 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.context; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIOException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class SecurityContextPersistenceFilterTests { TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A"); @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void contextIsClearedAfterChainProceeds() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); SecurityContextHolder.getContext().setAuthentication(this.testToken); filter.doFilter(request, response, chain); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); SecurityContextHolder.getContext().setAuthentication(this.testToken); willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThatIOException().isThrownBy(() -> filter.doFilter(request, response, chain)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test public void loadedContextContextIsCopiedToSecurityContextHolderAndUpdatedContextIsStored() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final TestingAuthenticationToken beforeAuth = new TestingAuthenticationToken("someoneelse", "passwd", "ROLE_B"); final SecurityContext scBefore = new SecurityContextImpl(); final SecurityContext scExpectedAfter = new SecurityContextImpl(); scExpectedAfter.setAuthentication(this.testToken); scBefore.setAuthentication(beforeAuth); final SecurityContextRepository repo = mock(SecurityContextRepository.class); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo); given(repo.loadContext(any(HttpRequestResponseHolder.class))).willReturn(scBefore); final FilterChain chain = (request1, response1) -> { assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth); // Change the context here SecurityContextHolder.setContext(scExpectedAfter); }; filter.doFilter(request, response, chain); verify(repo).saveContext(scExpectedAfter, request, response); } @Test public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter( mock(SecurityContextRepository.class)); request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); } @Test public void sessionIsEagerlyCreatedWhenConfigured() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); filter.setForceEagerSessionCreation(true); filter.doFilter(request, response, chain); assertThat(request.getSession(false)).isNotNull(); } @Test public void nullSecurityContextRepoDoesntSaveContextOrCreateSession() throws Exception { final FilterChain chain = mock(FilterChain.class); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextRepository repo = new NullSecurityContextRepository(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo); filter.doFilter(request, response, chain); assertThat(repo.containsContext(request)).isFalse(); assertThat(request.getSession(false)).isNull(); } }
6,189
45.893939
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/request/async/SecurityContextCallableProcessingInterceptorTests.java
/* * 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. * 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.context.request.async; import java.util.concurrent.Callable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.context.request.NativeWebRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class SecurityContextCallableProcessingInterceptorTests { @Mock private SecurityContext securityContext; @Mock private Callable<?> callable; @Mock private NativeWebRequest webRequest; @AfterEach public void clearSecurityContext() { SecurityContextHolder.clearContext(); } @Test public void constructorNull() { assertThatIllegalArgumentException().isThrownBy(() -> new SecurityContextCallableProcessingInterceptor(null)); } @Test public void currentSecurityContext() throws Exception { SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor(); SecurityContextHolder.setContext(this.securityContext); interceptor.beforeConcurrentHandling(this.webRequest, this.callable); SecurityContextHolder.clearContext(); interceptor.preProcess(this.webRequest, this.callable); assertThat(SecurityContextHolder.getContext()).isSameAs(this.securityContext); interceptor.postProcess(this.webRequest, this.callable, null); assertThat(SecurityContextHolder.getContext()).isNotSameAs(this.securityContext); } @Test public void specificSecurityContext() throws Exception { SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor( this.securityContext); interceptor.preProcess(this.webRequest, this.callable); assertThat(SecurityContextHolder.getContext()).isSameAs(this.securityContext); interceptor.postProcess(this.webRequest, this.callable, null); assertThat(SecurityContextHolder.getContext()).isNotSameAs(this.securityContext); } }
2,931
34.325301
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java
/* * 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. * 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.context.request.async; import java.util.concurrent.Callable; import java.util.concurrent.ThreadFactory; 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.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mock.web.MockFilterChain; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.async.AsyncWebRequest; import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class WebAsyncManagerIntegrationFilterTests { @Mock private SecurityContext securityContext; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private AsyncWebRequest asyncWebRequest; private WebAsyncManager asyncManager; private JoinableThreadFactory threadFactory; private MockFilterChain filterChain; private WebAsyncManagerIntegrationFilter filter; @BeforeEach public void setUp() { this.filterChain = new MockFilterChain(); this.threadFactory = new JoinableThreadFactory(); SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(); executor.setThreadFactory(this.threadFactory); this.asyncManager = WebAsyncUtils.getAsyncManager(this.request); this.asyncManager.setAsyncWebRequest(this.asyncWebRequest); this.asyncManager.setTaskExecutor(executor); given(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).willReturn(this.asyncManager); this.filter = new WebAsyncManagerIntegrationFilter(); } @AfterEach public void clearSecurityContext() { SecurityContextHolder.clearContext(); } @Test public void doFilterInternalRegistersSecurityContextCallableProcessor() throws Exception { SecurityContextHolder.setContext(this.securityContext); this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptor() { @Override public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { assertThat(SecurityContextHolder.getContext()) .isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext); } }); this.filter.doFilterInternal(this.request, this.response, this.filterChain); VerifyingCallable verifyingCallable = new VerifyingCallable(); this.asyncManager.startCallableProcessing(verifyingCallable); this.threadFactory.join(); assertThat(this.asyncManager.getConcurrentResult()).isSameAs(this.securityContext); } @Test public void doFilterInternalRegistersSecurityContextCallableProcessorContextUpdated() throws Exception { SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptor() { @Override public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { assertThat(SecurityContextHolder.getContext()) .isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext); } }); this.filter.doFilterInternal(this.request, this.response, this.filterChain); SecurityContextHolder.setContext(this.securityContext); VerifyingCallable verifyingCallable = new VerifyingCallable(); this.asyncManager.startCallableProcessing(verifyingCallable); this.threadFactory.join(); assertThat(this.asyncManager.getConcurrentResult()).isSameAs(this.securityContext); } private static final class JoinableThreadFactory implements ThreadFactory { private Thread t; @Override public Thread newThread(Runnable r) { this.t = new Thread(r); return this.t; } void join() throws InterruptedException { this.t.join(); } } private class VerifyingCallable implements Callable<SecurityContext> { @Override public SecurityContext call() { return SecurityContextHolder.getContext(); } } }
5,202
33.686667
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/aot/hint/WebMvcSecurityRuntimeHintsTests.java
/* * 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. * 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.aot.hint; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.security.web.access.expression.WebSecurityExpressionRoot; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WebMvcSecurityRuntimeHints} * * @author Marcus Da Coregio */ class WebMvcSecurityRuntimeHintsTests { private final RuntimeHints hints = new RuntimeHints(); @BeforeEach void setup() { SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(RuntimeHintsRegistrar.class) .forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader())); } @Test void webSecurityExpressionRootHasHints() { assertThat(RuntimeHintsPredicates.reflection().onType(WebSecurityExpressionRoot.class) .withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS)) .accepts(this.hints); } }
1,943
34.345455
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java
/* * 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. * 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.method; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import org.aopalliance.intercept.MethodInterceptor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.target.EmptyTargetSource; import org.springframework.cglib.core.SpringNamingPolicy; 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.MethodIntrospector; import org.springframework.core.MethodParameter; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.annotation.SynthesizingMethodParameter; import org.springframework.objenesis.ObjenesisException; import org.springframework.objenesis.SpringObjenesis; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.web.bind.annotation.ValueConstants; /** * Convenience class to resolve method parameters from hints. * * <h1>Background</h1> * * <p> * When testing annotated methods we create test classes such as "TestController" with a * diverse range of method signatures representing supported annotations and argument * types. It becomes challenging to use naming strategies to keep track of methods and * arguments especially in combination with variables for reflection metadata. * * <p> * The idea with {@link ResolvableMethod} is NOT to rely on naming techniques but to use * hints to zero in on method parameters. Such hints can be strongly typed and explicit * about what is being tested. * * <h2>1. Declared Return Type</h2> * * When testing return types it's likely to have many methods with a unique return type, * possibly with or without an annotation. * * <pre> * * import static org.springframework.web.method.ResolvableMethod.on; * import static org.springframework.web.method.MvcAnnotationPredicates.requestMapping; * * // Return type * on(TestController.class).resolveReturnType(Foo.class); * on(TestController.class).resolveReturnType(List.class, Foo.class); * on(TestController.class).resolveReturnType(Mono.class, responseEntity(Foo.class)); * * // Annotation + return type * on(TestController.class).annotPresent(RequestMapping.class).resolveReturnType(Bar.class); * * // Annotation not present * on(TestController.class).annotNotPresent(RequestMapping.class).resolveReturnType(); * * // Annotation with attributes * on(TestController.class).annot(requestMapping("/foo").params("p")).resolveReturnType(); * </pre> * * <h2>2. Method Arguments</h2> * * When testing method arguments it's more likely to have one or a small number of methods * with a wide array of argument types and parameter annotations. * * <pre> * * import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; * * ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build(); * * testMethod.arg(Foo.class); * testMethod.annotPresent(RequestParam.class).arg(Integer.class); * testMethod.annotNotPresent(RequestParam.class)).arg(Integer.class); * testMethod.annot(requestParam().name("c").notRequired()).arg(Integer.class); * </pre> * * <h3>3. Mock Handler Method Invocation</h3> * * Locate a method by invoking it through a proxy of the target handler: * * <pre> * * ResolvableMethod.on(TestController.class).mockCall((o) -> o.handle(null)).method(); * </pre> * * @author Rossen Stoyanchev * @since 5.0 */ public final class ResolvableMethod { private static final Log logger = LogFactory.getLog(ResolvableMethod.class); private static final SpringObjenesis objenesis = new SpringObjenesis(); private static final ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer(); private final Method method; private ResolvableMethod(Method method) { Assert.notNull(method, "method is required"); this.method = method; } /** * Return the resolved method. */ public Method method() { return this.method; } /** * Return the declared return type of the resolved method. */ public MethodParameter returnType() { return new SynthesizingMethodParameter(this.method, -1); } /** * Find a unique argument matching the given type. * @param type the expected type * @param generics optional array of generic types */ public MethodParameter arg(Class<?> type, Class<?>... generics) { return new ArgResolver().arg(type, generics); } /** * Find a unique argument matching the given type. * @param type the expected type * @param generic at least one generic type * @param generics optional array of generic types */ public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) { return new ArgResolver().arg(type, generic, generics); } /** * Find a unique argument matching the given type. * @param type the expected type */ public MethodParameter arg(ResolvableType type) { return new ArgResolver().arg(type); } /** * Filter on method arguments with annotation. See {@link MvcAnnotationPredicates}. */ @SafeVarargs public final ArgResolver annot(Predicate<MethodParameter>... filter) { return new ArgResolver(filter); } @SafeVarargs public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) { return new ArgResolver().annotPresent(annotationTypes); } /** * Filter on method arguments that don't have the given annotation type(s). * @param annotationTypes the annotation types */ @SafeVarargs public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) { return new ArgResolver().annotNotPresent(annotationTypes); } @Override public String toString() { return "ResolvableMethod=" + formatMethod(); } private String formatMethod() { return this.method().getName() + Arrays.stream(this.method.getParameters()).map(this::formatParameter) .collect(Collectors.joining(",\n\t", "(\n\t", "\n)")); } private String formatParameter(Parameter param) { Annotation[] annot = param.getAnnotations(); return (annot.length > 0) ? Arrays.stream(annot).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " " + param : param.toString(); } private String formatAnnotation(Annotation annotation) { Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation); map.forEach((key, value) -> { if (value.equals(ValueConstants.DEFAULT_NONE)) { map.put(key, "NONE"); } }); return annotation.annotationType().getName() + map; } private static ResolvableType toResolvableType(Class<?> type, Class<?>... generics) { return ObjectUtils.isEmpty(generics) ? ResolvableType.forClass(type) : ResolvableType.forClassWithGenerics(type, generics); } private static ResolvableType toResolvableType(Class<?> type, ResolvableType generic, ResolvableType... generics) { ResolvableType[] genericTypes = new ResolvableType[generics.length + 1]; genericTypes[0] = generic; System.arraycopy(generics, 0, genericTypes, 1, generics.length); return ResolvableType.forClassWithGenerics(type, genericTypes); } /** * Main entry point providing access to a {@code ResolvableMethod} builder. */ public static <T> Builder<T> on(Class<T> objectClass) { return new Builder<>(objectClass); } @SuppressWarnings("unchecked") private static <T> T initProxy(Class<?> type, MethodInvocationInterceptor interceptor) { Assert.notNull(type, "'type' must not be null"); if (type.isInterface()) { ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE); factory.addInterface(type); factory.addInterface(Supplier.class); factory.addAdvice(interceptor); return (T) factory.getProxy(); } else { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(type); enhancer.setInterfaces(new Class<?>[] { Supplier.class }); enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class); Class<?> proxyClass = enhancer.createClass(); Object proxy = null; if (objenesis.isWorthTrying()) { try { proxy = objenesis.newInstance(proxyClass, enhancer.getUseCache()); } catch (ObjenesisException ex) { logger.debug("Objenesis failed, falling back to default constructor", ex); } } if (proxy == null) { try { proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance(); } catch (Throwable ex) { throw new IllegalStateException( "Unable to instantiate proxy " + "via both Objenesis and default constructor fails as well", ex); } } ((Factory) proxy).setCallbacks(new Callback[] { interceptor }); return (T) proxy; } } /** * Builder for {@code ResolvableMethod}. */ public static final class Builder<T> { private final Class<?> objectClass; private final List<Predicate<Method>> filters = new ArrayList<>(4); private Builder(Class<?> objectClass) { Assert.notNull(objectClass, "Class must not be null"); this.objectClass = objectClass; } private void addFilter(String message, Predicate<Method> filter) { this.filters.add(new LabeledPredicate<>(message, filter)); } /** * Filter on methods with the given name. */ public Builder<T> named(String methodName) { addFilter("methodName=" + methodName, (m) -> m.getName().equals(methodName)); return this; } /** * Filter on annotated methods. See {@link MvcAnnotationPredicates}. */ @SafeVarargs public final Builder<T> annot(Predicate<Method>... filters) { this.filters.addAll(Arrays.asList(filters)); return this; } /** * Filter on methods annotated with the given annotation type. * @see #annot(Predicate[]) * @see MvcAnnotationPredicates */ @SafeVarargs public final Builder<T> annotPresent(Class<? extends Annotation>... annotationTypes) { String message = "annotationPresent=" + Arrays.toString(annotationTypes); addFilter(message, (candidate) -> Arrays.stream(annotationTypes) .allMatch((annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null)); return this; } /** * Filter on methods not annotated with the given annotation type. */ @SafeVarargs public final Builder<T> annotNotPresent(Class<? extends Annotation>... annotationTypes) { String message = "annotationNotPresent=" + Arrays.toString(annotationTypes); addFilter(message, (candidate) -> { if (annotationTypes.length != 0) { return Arrays.stream(annotationTypes).noneMatch( (annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null); } else { return candidate.getAnnotations().length == 0; } }); return this; } /** * Filter on methods returning the given type. * @param returnType the return type * @param generics optional array of generic types */ public Builder<T> returning(Class<?> returnType, Class<?>... generics) { return returning(toResolvableType(returnType, generics)); } /** * Filter on methods returning the given type with generics. * @param returnType the return type * @param generic at least one generic type * @param generics optional extra generic types */ public Builder<T> returning(Class<?> returnType, ResolvableType generic, ResolvableType... generics) { return returning(toResolvableType(returnType, generic, generics)); } /** * Filter on methods returning the given type. * @param returnType the return type */ public Builder<T> returning(ResolvableType returnType) { String expected = returnType.toString(); String message = "returnType=" + expected; addFilter(message, (m) -> expected.equals(ResolvableType.forMethodReturnType(m).toString())); return this; } /** * Build a {@code ResolvableMethod} from the provided filters which must resolve * to a unique, single method. * * <p> * See additional resolveXxx shortcut methods going directly to {@link Method} or * return type parameter. * @throws IllegalStateException for no match or multiple matches */ public ResolvableMethod build() { Set<Method> methods = MethodIntrospector.selectMethods(this.objectClass, this::isMatch); Assert.state(!methods.isEmpty(), () -> "No matching method: " + this); Assert.state(methods.size() == 1, () -> "Multiple matching methods: " + this + formatMethods(methods)); return new ResolvableMethod(methods.iterator().next()); } private boolean isMatch(Method method) { return this.filters.stream().allMatch((p) -> p.test(method)); } private String formatMethods(Set<Method> methods) { return "\nMatched:\n" + methods.stream().map(Method::toGenericString) .collect(Collectors.joining(",\n\t", "[\n\t", "\n]")); } public ResolvableMethod mockCall(Consumer<T> invoker) { MethodInvocationInterceptor interceptor = new MethodInvocationInterceptor(); T proxy = initProxy(this.objectClass, interceptor); invoker.accept(proxy); Method method = interceptor.getInvokedMethod(); return new ResolvableMethod(method); } // Build & resolve shortcuts... /** * Resolve and return the {@code Method} equivalent to: * <p> * {@code build().method()} */ public Method resolveMethod() { return build().method(); } /** * Resolve and return the {@code Method} equivalent to: * <p> * {@code named(methodName).build().method()} */ public Method resolveMethod(String methodName) { return named(methodName).build().method(); } /** * Resolve and return the declared return type equivalent to: * <p> * {@code build().returnType()} */ public MethodParameter resolveReturnType() { return build().returnType(); } /** * Shortcut to the unique return type equivalent to: * <p> * {@code returning(returnType).build().returnType()} * @param returnType the return type * @param generics optional array of generic types */ public MethodParameter resolveReturnType(Class<?> returnType, Class<?>... generics) { return returning(returnType, generics).build().returnType(); } /** * Shortcut to the unique return type equivalent to: * <p> * {@code returning(returnType).build().returnType()} * @param returnType the return type * @param generic at least one generic type * @param generics optional extra generic types */ public MethodParameter resolveReturnType(Class<?> returnType, ResolvableType generic, ResolvableType... generics) { return returning(returnType, generic, generics).build().returnType(); } public MethodParameter resolveReturnType(ResolvableType returnType) { return returning(returnType).build().returnType(); } @Override public String toString() { return "ResolvableMethod.Builder[\n" + "\tobjectClass = " + this.objectClass.getName() + ",\n" + "\tfilters = " + formatFilters() + "\n]"; } private String formatFilters() { return this.filters.stream().map(Object::toString) .collect(Collectors.joining(",\n\t\t", "[\n\t\t", "\n\t]")); } } /** * Predicate with a descriptive label. */ private static final class LabeledPredicate<T> implements Predicate<T> { private final String label; private final Predicate<T> delegate; private LabeledPredicate(String label, Predicate<T> delegate) { this.label = label; this.delegate = delegate; } @Override public boolean test(T method) { return this.delegate.test(method); } @Override public Predicate<T> and(Predicate<? super T> other) { return this.delegate.and(other); } @Override public Predicate<T> negate() { return this.delegate.negate(); } @Override public Predicate<T> or(Predicate<? super T> other) { return this.delegate.or(other); } @Override public String toString() { return this.label; } } /** * Resolver for method arguments. */ public final class ArgResolver { private final List<Predicate<MethodParameter>> filters = new ArrayList<>(4); @SafeVarargs private ArgResolver(Predicate<MethodParameter>... filter) { this.filters.addAll(Arrays.asList(filter)); } /** * Filter on method arguments with annotations. See * {@link MvcAnnotationPredicates}. */ @SafeVarargs public final ArgResolver annot(Predicate<MethodParameter>... filters) { this.filters.addAll(Arrays.asList(filters)); return this; } /** * Filter on method arguments that have the given annotations. * @param annotationTypes the annotation types * @see #annot(Predicate[]) * @see MvcAnnotationPredicates */ @SafeVarargs public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) { this.filters.add((param) -> Arrays.stream(annotationTypes).allMatch(param::hasParameterAnnotation)); return this; } /** * Filter on method arguments that don't have the given annotations. * @param annotationTypes the annotation types */ @SafeVarargs public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) { this.filters.add((param) -> (annotationTypes.length != 0) ? Arrays.stream(annotationTypes).noneMatch(param::hasParameterAnnotation) : param.getParameterAnnotations().length == 0); return this; } /** * Resolve the argument also matching to the given type. * @param type the expected type */ public MethodParameter arg(Class<?> type, Class<?>... generics) { return arg(toResolvableType(type, generics)); } /** * Resolve the argument also matching to the given type. * @param type the expected type */ public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) { return arg(toResolvableType(type, generic, generics)); } /** * Resolve the argument also matching to the given type. * @param type the expected type */ public MethodParameter arg(ResolvableType type) { this.filters.add((p) -> type.toString().equals(ResolvableType.forMethodParameter(p).toString())); return arg(); } /** * Resolve the argument. */ public MethodParameter arg() { List<MethodParameter> matches = applyFilters(); Assert.state(!matches.isEmpty(), () -> "No matching arg in method\n" + formatMethod()); Assert.state(matches.size() == 1, () -> "Multiple matching args in method\n" + formatMethod() + "\nMatches:\n\t" + matches); return matches.get(0); } private List<MethodParameter> applyFilters() { List<MethodParameter> matches = new ArrayList<>(); for (int i = 0; i < ResolvableMethod.this.method.getParameterCount(); i++) { MethodParameter param = new SynthesizingMethodParameter(ResolvableMethod.this.method, i); param.initParameterNameDiscovery(nameDiscoverer); if (this.filters.stream().allMatch((p) -> p.test(param))) { matches.add(param); } } return matches; } } private static class MethodInvocationInterceptor implements org.springframework.cglib.proxy.MethodInterceptor, MethodInterceptor { private Method invokedMethod; Method getInvokedMethod() { return this.invokedMethod; } @Override public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) { if (ReflectionUtils.isObjectMethod(method)) { return ReflectionUtils.invokeMethod(method, object, args); } else { this.invokedMethod = method; return null; } } @Override public Object invoke(org.aopalliance.intercept.MethodInvocation inv) { return intercept(inv.getThis(), inv.getMethod(), inv.getArguments(), null); } } }
21,070
31.071537
116
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/method/annotation/AuthenticationPrincipalArgumentResolverTests.java
/* * Copyright 2002-2021 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.method.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.MethodParameter; import org.springframework.expression.BeanResolver; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; import static org.mockito.BDDMockito.verify; /** * @author Rob Winch * */ public class AuthenticationPrincipalArgumentResolverTests { private BeanResolver beanResolver; private Object expectedPrincipal; private AuthenticationPrincipalArgumentResolver resolver; @BeforeEach public void setup() { this.beanResolver = mock(BeanResolver.class); this.resolver = new AuthenticationPrincipalArgumentResolver(); this.resolver.setBeanResolver(this.beanResolver); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void supportsParameterNoAnnotation() { assertThat(this.resolver.supportsParameter(showUserNoAnnotation())).isFalse(); } @Test public void supportsParameterAnnotation() { assertThat(this.resolver.supportsParameter(showUserAnnotationObject())).isTrue(); } @Test public void supportsParameterCustomAnnotation() { assertThat(this.resolver.supportsParameter(showUserCustomAnnotation())).isTrue(); } @Test public void resolveArgumentNullAuthentication() throws Exception { assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull(); } @Test public void resolveArgumentNullPrincipal() throws Exception { setAuthenticationPrincipal(null); assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull(); } @Test public void resolveArgumentString() throws Exception { setAuthenticationPrincipal("john"); assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentPrincipalStringOnObject() throws Exception { setAuthenticationPrincipal("john"); assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentUserDetails() throws Exception { setAuthenticationPrincipal(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"))); assertThat(this.resolver.resolveArgument(showUserAnnotationUserDetails(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentCustomUserPrincipal() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThat(this.resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentCustomAnnotation() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThat(this.resolver.resolveArgument(showUserCustomAnnotation(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentSpel() throws Exception { CustomUserPrincipal principal = new CustomUserPrincipal(); setAuthenticationPrincipal(principal); this.expectedPrincipal = principal.property; assertThat(this.resolver.resolveArgument(showUserSpel(), null, null, null)).isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentSpelBean() throws Exception { CustomUserPrincipal principal = new CustomUserPrincipal(); setAuthenticationPrincipal(principal); given(this.beanResolver.resolve(any(), eq("test"))).willReturn(principal.property); this.expectedPrincipal = principal.property; assertThat(this.resolver.resolveArgument(showUserSpelBean(), null, null, null)) .isEqualTo(this.expectedPrincipal); verify(this.beanResolver).resolve(any(), eq("test")); } @Test public void resolveArgumentSpelCopy() throws Exception { CopyUserPrincipal principal = new CopyUserPrincipal("property"); setAuthenticationPrincipal(principal); Object resolveArgument = this.resolver.resolveArgument(showUserSpelCopy(), null, null, null); assertThat(resolveArgument).isEqualTo(principal); assertThat(resolveArgument).isNotSameAs(principal); } @Test public void resolveArgumentSpelPrimitive() throws Exception { CustomUserPrincipal principal = new CustomUserPrincipal(); setAuthenticationPrincipal(principal); this.expectedPrincipal = principal.id; assertThat(this.resolver.resolveArgument(showUserSpelPrimitive(), null, null, null)) .isEqualTo(this.expectedPrincipal); } @Test public void resolveArgumentNullOnInvalidType() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull(); } @Test public void resolveArgumentErrorOnInvalidType() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThatExceptionOfType(ClassCastException.class).isThrownBy( () -> this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null)); } @Test public void resolveArgumentCustomserErrorOnInvalidType() throws Exception { setAuthenticationPrincipal(new CustomUserPrincipal()); assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> this.resolver .resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null)); } @Test public void resolveArgumentObject() throws Exception { setAuthenticationPrincipal(new Object()); assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null)) .isEqualTo(this.expectedPrincipal); } private MethodParameter showUserNoAnnotation() { return getMethodParameter("showUserNoAnnotation", String.class); } private MethodParameter showUserAnnotationString() { return getMethodParameter("showUserAnnotation", String.class); } private MethodParameter showUserAnnotationErrorOnInvalidType() { return getMethodParameter("showUserAnnotationErrorOnInvalidType", String.class); } private MethodParameter showUserAnnotationCurrentUserErrorOnInvalidType() { return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType", String.class); } private MethodParameter showUserAnnotationUserDetails() { return getMethodParameter("showUserAnnotation", UserDetails.class); } private MethodParameter showUserAnnotationCustomUserPrincipal() { return getMethodParameter("showUserAnnotation", CustomUserPrincipal.class); } private MethodParameter showUserCustomAnnotation() { return getMethodParameter("showUserCustomAnnotation", CustomUserPrincipal.class); } private MethodParameter showUserSpel() { return getMethodParameter("showUserSpel", String.class); } private MethodParameter showUserSpelBean() { return getMethodParameter("showUserSpelBean", String.class); } private MethodParameter showUserSpelCopy() { return getMethodParameter("showUserSpelCopy", CopyUserPrincipal.class); } private MethodParameter showUserSpelPrimitive() { return getMethodParameter("showUserSpelPrimitive", int.class); } private MethodParameter showUserAnnotationObject() { return getMethodParameter("showUserAnnotation", Object.class); } private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) { Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes); return new MethodParameter(method, 0); } private void setAuthenticationPrincipal(Object principal) { this.expectedPrincipal = principal; SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER")); } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @AuthenticationPrincipal static @interface CurrentUser { } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @AuthenticationPrincipal(errorOnInvalidType = true) static @interface CurrentUserErrorOnInvalidType { } public static class TestController { public void showUserNoAnnotation(String user) { } public void showUserAnnotation(@AuthenticationPrincipal String user) { } public void showUserAnnotationErrorOnInvalidType( @AuthenticationPrincipal(errorOnInvalidType = true) String user) { } public void showUserAnnotationCurrentUserErrorOnInvalidType(@CurrentUserErrorOnInvalidType String user) { } public void showUserAnnotation(@AuthenticationPrincipal UserDetails user) { } public void showUserAnnotation(@AuthenticationPrincipal CustomUserPrincipal user) { } public void showUserCustomAnnotation(@CurrentUser CustomUserPrincipal user) { } public void showUserAnnotation(@AuthenticationPrincipal Object user) { } public void showUserSpel(@AuthenticationPrincipal(expression = "property") String user) { } public void showUserSpelBean(@AuthenticationPrincipal(expression = "@test") String user) { } public void showUserSpelCopy(@AuthenticationPrincipal( expression = "new org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolverTests$CopyUserPrincipal(#this)") CopyUserPrincipal user) { } public void showUserSpelPrimitive(@AuthenticationPrincipal(expression = "id") int id) { } } static class CustomUserPrincipal { public final String property = "property"; public final int id = 1; } public static class CopyUserPrincipal { public final String property; public CopyUserPrincipal(String property) { this.property = property; } public CopyUserPrincipal(CopyUserPrincipal toCopy) { this.property = toCopy.property; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CopyUserPrincipal other = (CopyUserPrincipal) obj; if (this.property == null) { if (other.property != null) { return false; } } else if (!this.property.equals(other.property)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.property == null) ? 0 : this.property.hashCode()); return result; } } }
11,891
31.580822
170
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/method/annotation/CsrfTokenArgumentResolverTests.java
/* * Copyright 2002-2015 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.method.annotation; import java.lang.reflect.Method; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.MethodParameter; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.DefaultCsrfToken; import org.springframework.util.ReflectionUtils; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class CsrfTokenArgumentResolverTests { @Mock private ModelAndViewContainer mavContainer; @Mock private WebDataBinderFactory binderFactory; private MockHttpServletRequest request; private NativeWebRequest webRequest; private CsrfToken token; private CsrfTokenArgumentResolver resolver; @BeforeEach public void setup() { this.token = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "secret"); this.resolver = new CsrfTokenArgumentResolver(); this.request = new MockHttpServletRequest(); this.webRequest = new ServletWebRequest(this.request); } @Test public void supportsParameterFalse() { assertThat(this.resolver.supportsParameter(noToken())).isFalse(); } @Test public void supportsParameterTrue() { assertThat(this.resolver.supportsParameter(token())).isTrue(); } @Test public void resolveArgumentNotFound() throws Exception { assertThat(this.resolver.resolveArgument(token(), this.mavContainer, this.webRequest, this.binderFactory)) .isNull(); } @Test public void resolveArgumentFound() throws Exception { this.request.setAttribute(CsrfToken.class.getName(), this.token); assertThat(this.resolver.resolveArgument(token(), this.mavContainer, this.webRequest, this.binderFactory)) .isSameAs(this.token); } private MethodParameter noToken() { return getMethodParameter("noToken", String.class); } private MethodParameter token() { return getMethodParameter("token", CsrfToken.class); } private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) { Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes); return new MethodParameter(method, 0); } public static class TestController { public void noToken(String user) { } public void token(CsrfToken token) { } } }
3,410
28.66087
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/method/annotation/CurrentSecurityContextArgumentResolverTests.java
/* * Copyright 2002-2019 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.method.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.MethodParameter; import org.springframework.expression.BeanResolver; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.CurrentSecurityContext; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; import static org.mockito.BDDMockito.verify; /** * @author Dan Zheng * @since 5.2 * */ public class CurrentSecurityContextArgumentResolverTests { private BeanResolver beanResolver; private CurrentSecurityContextArgumentResolver resolver; @BeforeEach public void setup() { this.beanResolver = mock(BeanResolver.class); this.resolver = new CurrentSecurityContextArgumentResolver(); this.resolver.setBeanResolver(this.beanResolver); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void supportsParameterNoAnnotation() { assertThat(this.resolver.supportsParameter(showSecurityContextNoAnnotation())).isFalse(); } @Test public void supportsParameterAnnotation() { assertThat(this.resolver.supportsParameter(showSecurityContextAnnotation())).isTrue(); } @Test public void resolveArgumentWithCustomSecurityContext() { String principal = "custom_security_context"; setAuthenticationPrincipalWithCustomSecurityContext(principal); CustomSecurityContext customSecurityContext = (CustomSecurityContext) this.resolver .resolveArgument(showAnnotationWithCustomSecurityContext(), null, null, null); assertThat(customSecurityContext.getAuthentication().getPrincipal()).isEqualTo(principal); } @Test public void resolveArgumentWithCustomSecurityContextTypeMatch() { String principal = "custom_security_context_type_match"; setAuthenticationPrincipalWithCustomSecurityContext(principal); CustomSecurityContext customSecurityContext = (CustomSecurityContext) this.resolver .resolveArgument(showAnnotationWithCustomSecurityContext(), null, null, null); assertThat(customSecurityContext.getAuthentication().getPrincipal()).isEqualTo(principal); } @Test public void resolveArgumentNullAuthentication() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); context.setAuthentication(null); assertThat(this.resolver.resolveArgument(showSecurityContextAuthenticationAnnotation(), null, null, null)) .isNull(); context.setAuthentication(authentication); } @Test public void resolveArgumentWithAuthentication() { String principal = "john"; setAuthenticationPrincipal(principal); Authentication auth1 = (Authentication) this.resolver .resolveArgument(showSecurityContextAuthenticationAnnotation(), null, null, null); assertThat(auth1.getPrincipal()).isEqualTo(principal); } @Test public void resolveArgumentWithAuthenticationWithBean() throws Exception { String principal = "john"; given(this.beanResolver.resolve(any(), eq("test"))).willReturn(principal); assertThat(this.resolver.resolveArgument(showSecurityContextAuthenticationWithBean(), null, null, null)) .isEqualTo(principal); verify(this.beanResolver).resolve(any(), eq("test")); } @Test public void resolveArgumentWithNullAuthentication() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); context.setAuthentication(null); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> this.resolver .resolveArgument(showSecurityContextAuthenticationWithPrincipal(), null, null, null)); context.setAuthentication(authentication); } @Test public void resolveArgumentWithOptionalPrincipal() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); context.setAuthentication(null); Object principalResult = this.resolver.resolveArgument(showSecurityContextAuthenticationWithOptionalPrincipal(), null, null, null); assertThat(principalResult).isNull(); context.setAuthentication(authentication); } @Test public void resolveArgumentWithPrincipal() { String principal = "smith"; setAuthenticationPrincipal(principal); String principalResult = (String) this.resolver .resolveArgument(showSecurityContextAuthenticationWithPrincipal(), null, null, null); assertThat(principalResult).isEqualTo(principal); } @Test public void resolveArgumentUserDetails() { setAuthenticationDetail(new User("my_user", "my_password", AuthorityUtils.createAuthorityList("ROLE_USER"))); User u = (User) this.resolver.resolveArgument(showSecurityContextWithUserDetail(), null, null, null); assertThat(u.getUsername()).isEqualTo("my_user"); } @Test public void resolveArgumentSecurityContextErrorOnInvalidTypeImplicit() { String principal = "invalid_type_implicit"; setAuthenticationPrincipal(principal); assertThat(this.resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeImplicit(), null, null, null)) .isNull(); } @Test public void resolveArgumentSecurityContextErrorOnInvalidTypeFalse() { String principal = "invalid_type_false"; setAuthenticationPrincipal(principal); assertThat(this.resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeFalse(), null, null, null)) .isNull(); } @Test public void resolveArgumentSecurityContextErrorOnInvalidTypeTrue() { String principal = "invalid_type_true"; setAuthenticationPrincipal(principal); assertThatExceptionOfType(ClassCastException.class).isThrownBy( () -> this.resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeTrue(), null, null, null)); } @Test public void metaAnnotationWhenCurrentCustomSecurityContextThenInjectSecurityContext() { assertThat(this.resolver.resolveArgument(showCurrentCustomSecurityContext(), null, null, null)).isNotNull(); } @Test public void metaAnnotationWhenCurrentAuthenticationThenInjectAuthentication() { String principal = "current_authentcation"; setAuthenticationPrincipal(principal); Authentication auth1 = (Authentication) this.resolver.resolveArgument(showCurrentAuthentication(), null, null, null); assertThat(auth1.getPrincipal()).isEqualTo(principal); } @Test public void metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenInjectSecurityContext() { assertThat(this.resolver.resolveArgument(showCurrentSecurityWithErrorOnInvalidType(), null, null, null)) .isNotNull(); } @Test public void metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenMisMatch() { assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> this.resolver .resolveArgument(showCurrentSecurityWithErrorOnInvalidTypeMisMatch(), null, null, null)); } private MethodParameter showSecurityContextNoAnnotation() { return getMethodParameter("showSecurityContextNoAnnotation", String.class); } private MethodParameter showSecurityContextAnnotation() { return getMethodParameter("showSecurityContextAnnotation", SecurityContext.class); } private MethodParameter showAnnotationWithCustomSecurityContext() { return getMethodParameter("showAnnotationWithCustomSecurityContext", CustomSecurityContext.class); } private MethodParameter showAnnotationWithCustomSecurityContextTypeMatch() { return getMethodParameter("showAnnotationWithCustomSecurityContextTypeMatch", SecurityContext.class); } private MethodParameter showSecurityContextAuthenticationAnnotation() { return getMethodParameter("showSecurityContextAuthenticationAnnotation", Authentication.class); } public MethodParameter showSecurityContextAuthenticationWithBean() { return getMethodParameter("showSecurityContextAuthenticationWithBean", String.class); } private MethodParameter showSecurityContextAuthenticationWithOptionalPrincipal() { return getMethodParameter("showSecurityContextAuthenticationWithOptionalPrincipal", Object.class); } private MethodParameter showSecurityContextAuthenticationWithPrincipal() { return getMethodParameter("showSecurityContextAuthenticationWithPrincipal", Object.class); } private MethodParameter showSecurityContextWithUserDetail() { return getMethodParameter("showSecurityContextWithUserDetail", Object.class); } private MethodParameter showSecurityContextErrorOnInvalidTypeImplicit() { return getMethodParameter("showSecurityContextErrorOnInvalidTypeImplicit", String.class); } private MethodParameter showSecurityContextErrorOnInvalidTypeFalse() { return getMethodParameter("showSecurityContextErrorOnInvalidTypeFalse", String.class); } private MethodParameter showSecurityContextErrorOnInvalidTypeTrue() { return getMethodParameter("showSecurityContextErrorOnInvalidTypeTrue", String.class); } public MethodParameter showCurrentCustomSecurityContext() { return getMethodParameter("showCurrentCustomSecurityContext", SecurityContext.class); } public MethodParameter showCurrentAuthentication() { return getMethodParameter("showCurrentAuthentication", Authentication.class); } public MethodParameter showCurrentSecurityWithErrorOnInvalidType() { return getMethodParameter("showCurrentSecurityWithErrorOnInvalidType", SecurityContext.class); } public MethodParameter showCurrentSecurityWithErrorOnInvalidTypeMisMatch() { return getMethodParameter("showCurrentSecurityWithErrorOnInvalidTypeMisMatch", String.class); } private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) { Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes); return new MethodParameter(method, 0); } private void setAuthenticationPrincipal(Object principal) { SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(principal, "password", "ROLE_USER")); } private void setAuthenticationPrincipalWithCustomSecurityContext(Object principal) { CustomSecurityContext csc = new CustomSecurityContext(); csc.setAuthentication(new TestingAuthenticationToken(principal, "password", "ROLE_USER")); SecurityContextHolder.setContext(csc); } private void setAuthenticationDetail(Object detail) { TestingAuthenticationToken tat = new TestingAuthenticationToken("user", "password", "ROLE_USER"); tat.setDetails(detail); SecurityContextHolder.getContext().setAuthentication(tat); } public static class TestController { public void showSecurityContextNoAnnotation(String user) { } public void showSecurityContextAnnotation(@CurrentSecurityContext SecurityContext context) { } public void showAnnotationWithCustomSecurityContext(@CurrentSecurityContext CustomSecurityContext context) { } public void showAnnotationWithCustomSecurityContextTypeMatch( @CurrentSecurityContext(errorOnInvalidType = true) SecurityContext context) { } public void showSecurityContextAuthenticationAnnotation( @CurrentSecurityContext(expression = "authentication") Authentication authentication) { } public void showSecurityContextAuthenticationWithBean( @CurrentSecurityContext(expression = "@test") String name) { } public void showSecurityContextAuthenticationWithOptionalPrincipal( @CurrentSecurityContext(expression = "authentication?.principal") Object principal) { } public void showSecurityContextAuthenticationWithPrincipal( @CurrentSecurityContext(expression = "authentication.principal") Object principal) { } public void showSecurityContextWithUserDetail( @CurrentSecurityContext(expression = "authentication.details") Object detail) { } public void showSecurityContextErrorOnInvalidTypeImplicit(@CurrentSecurityContext String implicit) { } public void showSecurityContextErrorOnInvalidTypeFalse( @CurrentSecurityContext(errorOnInvalidType = false) String implicit) { } public void showSecurityContextErrorOnInvalidTypeTrue( @CurrentSecurityContext(errorOnInvalidType = true) String implicit) { } public void showCurrentCustomSecurityContext(@CurrentCustomSecurityContext SecurityContext context) { } public void showCurrentAuthentication(@CurrentAuthentication Authentication authentication) { } public void showCurrentSecurityWithErrorOnInvalidType( @CurrentSecurityWithErrorOnInvalidType SecurityContext context) { } public void showCurrentSecurityWithErrorOnInvalidTypeMisMatch( @CurrentSecurityWithErrorOnInvalidType String typeMisMatch) { } } static class CustomSecurityContext implements SecurityContext { private Authentication authentication; @Override public Authentication getAuthentication() { return this.authentication; } @Override public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @CurrentSecurityContext @interface CurrentCustomSecurityContext { } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @CurrentSecurityContext(expression = "authentication") @interface CurrentAuthentication { } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @CurrentSecurityContext(errorOnInvalidType = true) static @interface CurrentSecurityWithErrorOnInvalidType { } }
14,898
36.154613
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jackson2/DefaultCsrfTokenMixinTests.java
/* * Copyright 2015-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. * 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.jackson2; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.web.csrf.DefaultCsrfToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Jitendra Singh * @since 4.2 */ public class DefaultCsrfTokenMixinTests extends AbstractMixinTests { // @formatter:off public static final String CSRF_JSON = "{" + "\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", " + "\"headerName\": \"csrf-header\", " + "\"parameterName\": \"_csrf\", " + "\"token\": \"1\"" + "}"; // @formatter:on @Test public void defaultCsrfTokenSerializedTest() throws JsonProcessingException, JSONException { DefaultCsrfToken token = new DefaultCsrfToken("csrf-header", "_csrf", "1"); String serializedJson = this.mapper.writeValueAsString(token); JSONAssert.assertEquals(CSRF_JSON, serializedJson, true); } @Test public void defaultCsrfTokenDeserializeTest() throws IOException { DefaultCsrfToken token = this.mapper.readValue(CSRF_JSON, DefaultCsrfToken.class); assertThat(token).isNotNull(); assertThat(token.getHeaderName()).isEqualTo("csrf-header"); assertThat(token.getParameterName()).isEqualTo("_csrf"); assertThat(token.getToken()).isEqualTo("1"); } @Test public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException { String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}"; assertThatExceptionOfType(JsonMappingException.class) .isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class)); } @Test public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException { String tokenJson = "{\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}"; assertThatExceptionOfType(JsonMappingException.class) .isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class)); } }
2,915
36.87013
161
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jackson2/WebAuthenticationDetailsMixinTests.java
/* * Copyright 2015-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. * 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.jackson2; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.web.authentication.WebAuthenticationDetails; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jitendra Singh * @since 4.2 */ public class WebAuthenticationDetailsMixinTests extends AbstractMixinTests { // @formatter:off private static final String AUTHENTICATION_DETAILS_JSON = "{" + "\"@class\": \"org.springframework.security.web.authentication.WebAuthenticationDetails\"," + "\"sessionId\": \"1\", " + "\"remoteAddress\": " + "\"/localhost\"" + "}"; // @formatter:on @Test public void buildWebAuthenticationDetailsUsingDifferentConstructors() throws IOException { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("localhost"); request.setSession(new MockHttpSession(null, "1")); WebAuthenticationDetails details = new WebAuthenticationDetails(request); WebAuthenticationDetails authenticationDetails = this.mapper.readValue(AUTHENTICATION_DETAILS_JSON, WebAuthenticationDetails.class); assertThat(details.equals(authenticationDetails)); } @Test public void webAuthenticationDetailsSerializeTest() throws JsonProcessingException, JSONException { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("/localhost"); request.setSession(new MockHttpSession(null, "1")); WebAuthenticationDetails details = new WebAuthenticationDetails(request); String actualJson = this.mapper.writeValueAsString(details); JSONAssert.assertEquals(AUTHENTICATION_DETAILS_JSON, actualJson, true); } @Test public void webAuthenticationDetailsJackson2SerializeTest() throws JsonProcessingException, JSONException { WebAuthenticationDetails details = new WebAuthenticationDetails("/localhost", "1"); String actualJson = this.mapper.writeValueAsString(details); JSONAssert.assertEquals(AUTHENTICATION_DETAILS_JSON, actualJson, true); } @Test public void webAuthenticationDetailsDeserializeTest() throws IOException { WebAuthenticationDetails details = this.mapper.readValue(AUTHENTICATION_DETAILS_JSON, WebAuthenticationDetails.class); assertThat(details).isNotNull(); assertThat(details.getRemoteAddress()).isEqualTo("/localhost"); assertThat(details.getSessionId()).isEqualTo("1"); } }
3,258
37.797619
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jackson2/PreAuthenticatedAuthenticationTokenMixinTests.java
/* * Copyright 2015-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. * 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.jackson2; import com.fasterxml.jackson.core.JsonProcessingException; import org.json.JSONException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.jackson2.SimpleGrantedAuthorityMixinTests; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 4.2 */ public class PreAuthenticatedAuthenticationTokenMixinTests extends AbstractMixinTests { // @formatter:off private static final String PREAUTH_JSON = "{" + "\"@class\": \"org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken\"," + "\"principal\": \"principal\", " + "\"credentials\": \"credentials\", " + "\"authenticated\": true, " + "\"details\": null, " + "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON + "}"; // @formatter:on PreAuthenticatedAuthenticationToken expected; @BeforeEach public void setupExpected() { this.expected = new PreAuthenticatedAuthenticationToken("principal", "credentials", AuthorityUtils.createAuthorityList("ROLE_USER")); } @Test public void serializeWhenPrincipalCredentialsAuthoritiesThenSuccess() throws JsonProcessingException, JSONException { String serializedJson = this.mapper.writeValueAsString(this.expected); JSONAssert.assertEquals(PREAUTH_JSON, serializedJson, true); } @Test public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws Exception { PreAuthenticatedAuthenticationToken deserialized = this.mapper.readValue(PREAUTH_JSON, PreAuthenticatedAuthenticationToken.class); assertThat(deserialized).isNotNull(); assertThat(deserialized.isAuthenticated()).isTrue(); assertThat(deserialized.getAuthorities()).isEqualTo(this.expected.getAuthorities()); } }
2,696
36.458333
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jackson2/SavedCookieMixinTests.java
/* * Copyright 2015-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. * 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.jackson2; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonProcessingException; import jakarta.servlet.http.Cookie; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.web.savedrequest.SavedCookie; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jitendra Singh. */ public class SavedCookieMixinTests extends AbstractMixinTests { // @formatter:off private static final String COOKIE_JSON = "{" + "\"@class\": \"org.springframework.security.web.savedrequest.SavedCookie\", " + "\"name\": \"SESSION\", " + "\"value\": \"123456789\", " + "\"comment\": null, " + "\"maxAge\": -1, " + "\"path\": null, " + "\"secure\":false, " + "\"version\": 0, " + "\"domain\": null" + "}"; // @formatter:on // @formatter:off private static final String COOKIES_JSON = "[\"java.util.ArrayList\", [" + COOKIE_JSON + "]]"; // @formatter:on @Test public void serializeWithDefaultConfigurationTest() throws JsonProcessingException, JSONException { SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789")); String actualJson = this.mapper.writeValueAsString(savedCookie); JSONAssert.assertEquals(COOKIE_JSON, actualJson, true); } @Test public void serializeWithOverrideConfigurationTest() throws JsonProcessingException, JSONException { SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789")); this.mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY) .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY); String actualJson = this.mapper.writeValueAsString(savedCookie); JSONAssert.assertEquals(COOKIE_JSON, actualJson, true); } @Test public void serializeSavedCookieWithList() throws JsonProcessingException, JSONException { List<SavedCookie> savedCookies = new ArrayList<>(); savedCookies.add(new SavedCookie(new Cookie("SESSION", "123456789"))); String actualJson = this.mapper.writeValueAsString(savedCookies); JSONAssert.assertEquals(COOKIES_JSON, actualJson, true); } @Test @SuppressWarnings("unchecked") public void deserializeSavedCookieWithList() throws IOException { List<SavedCookie> savedCookies = (List<SavedCookie>) this.mapper.readValue(COOKIES_JSON, Object.class); assertThat(savedCookies).isNotNull().hasSize(1); assertThat(savedCookies.get(0).getName()).isEqualTo("SESSION"); assertThat(savedCookies.get(0).getValue()).isEqualTo("123456789"); } @Test public void deserializeSavedCookieJsonTest() throws IOException { SavedCookie savedCookie = (SavedCookie) this.mapper.readValue(COOKIE_JSON, Object.class); assertThat(savedCookie).isNotNull(); assertThat(savedCookie.getName()).isEqualTo("SESSION"); assertThat(savedCookie.getValue()).isEqualTo("123456789"); assertThat(savedCookie.isSecure()).isEqualTo(false); assertThat(savedCookie.getVersion()).isZero(); assertThat(savedCookie.getComment()).isNull(); } }
3,865
36.533981
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jackson2/DefaultSavedRequestMixinTests.java
/* * Copyright 2015-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. * 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.jackson2; import java.io.IOException; import java.util.Collections; import java.util.Locale; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.web.PortResolverImpl; import org.springframework.security.web.savedrequest.DefaultSavedRequest; import org.springframework.security.web.savedrequest.SavedCookie; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jitendra Singh * @since 4.2 */ public class DefaultSavedRequestMixinTests extends AbstractMixinTests { // @formatter:off private static final String COOKIES_JSON = "[\"java.util.ArrayList\", [{" + "\"@class\": \"org.springframework.security.web.savedrequest.SavedCookie\", " + "\"name\": \"SESSION\", " + "\"value\": \"123456789\", " + "\"comment\": null, " + "\"maxAge\": -1, " + "\"path\": null, " + "\"secure\":false, " + "\"version\": 0, " + "\"domain\": null" + "}]]"; // @formatter:on // @formatter:off private static final String REQUEST_JSON = "{" + "\"@class\": \"org.springframework.security.web.savedrequest.DefaultSavedRequest\", " + "\"cookies\": " + COOKIES_JSON + "," + "\"locales\": [\"java.util.ArrayList\", [\"en\"]], " + "\"headers\": {\"@class\": \"java.util.TreeMap\", \"x-auth-token\": [\"java.util.ArrayList\", [\"12\"]]}, " + "\"parameters\": {\"@class\": \"java.util.TreeMap\"}," + "\"contextPath\": \"\", " + "\"method\": \"\", " + "\"pathInfo\": null, " + "\"queryString\": null, " + "\"requestURI\": \"\", " + "\"requestURL\": \"http://localhost\", " + "\"scheme\": \"http\", " + "\"serverName\": \"localhost\", " + "\"servletPath\": \"\", " + "\"serverPort\": 80" + "}"; // @formatter:on // @formatter:off private static final String REQUEST_WITH_MATCHING_REQUEST_PARAM_NAME_JSON = "{" + "\"@class\": \"org.springframework.security.web.savedrequest.DefaultSavedRequest\", " + "\"cookies\": " + COOKIES_JSON + "," + "\"locales\": [\"java.util.ArrayList\", [\"en\"]], " + "\"headers\": {\"@class\": \"java.util.TreeMap\", \"x-auth-token\": [\"java.util.ArrayList\", [\"12\"]]}, " + "\"parameters\": {\"@class\": \"java.util.TreeMap\"}," + "\"contextPath\": \"\", " + "\"method\": \"\", " + "\"pathInfo\": null, " + "\"queryString\": null, " + "\"requestURI\": \"\", " + "\"requestURL\": \"http://localhost\", " + "\"scheme\": \"http\", " + "\"serverName\": \"localhost\", " + "\"servletPath\": \"\", " + "\"serverPort\": 80, " + "\"matchingRequestParameterName\": \"success\"" + "}"; // @formatter:on @Test public void matchRequestBuildWithConstructorAndBuilder() { DefaultSavedRequest request = new DefaultSavedRequest.Builder() .setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789")))) .setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12"))).setScheme("http") .setRequestURL("http://localhost").setServerName("localhost").setRequestURI("") .setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("") .setServletPath("").build(); MockHttpServletRequest mockRequest = new MockHttpServletRequest(); mockRequest.setCookies(new Cookie("SESSION", "123456789")); mockRequest.addHeader("x-auth-token", "12"); assertThat(request.doesRequestMatch(mockRequest, new PortResolverImpl())).isTrue(); } @Test public void serializeDefaultRequestBuildWithConstructorTest() throws IOException, JSONException { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("x-auth-token", "12"); // Spring 5 MockHttpServletRequest automatically adds a header when the cookies // are set. To get consistency we override the request. HttpServletRequest requestToWrite = new HttpServletRequestWrapper(request) { @Override public Cookie[] getCookies() { return new Cookie[] { new Cookie("SESSION", "123456789") }; } }; String actualString = this.mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(new DefaultSavedRequest(requestToWrite, new PortResolverImpl())); JSONAssert.assertEquals(REQUEST_JSON, actualString, true); } @Test public void serializeDefaultRequestBuildWithBuilderTest() throws IOException, JSONException { DefaultSavedRequest request = new DefaultSavedRequest.Builder() .setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789")))) .setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12"))).setScheme("http") .setRequestURL("http://localhost").setServerName("localhost").setRequestURI("") .setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("") .setServletPath("").build(); String actualString = this.mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request); JSONAssert.assertEquals(REQUEST_JSON, actualString, true); } @Test public void deserializeDefaultSavedRequest() throws IOException { DefaultSavedRequest request = (DefaultSavedRequest) this.mapper.readValue(REQUEST_JSON, Object.class); assertThat(request).isNotNull(); assertThat(request.getCookies()).hasSize(1); assertThat(request.getLocales()).hasSize(1).contains(new Locale("en")); assertThat(request.getHeaderNames()).hasSize(1).contains("x-auth-token"); assertThat(request.getHeaderValues("x-auth-token")).hasSize(1).contains("12"); } @Test public void deserializeWhenMatchingRequestParameterNameThenRedirectUrlContainsParam() throws IOException { DefaultSavedRequest request = (DefaultSavedRequest) this.mapper .readValue(REQUEST_WITH_MATCHING_REQUEST_PARAM_NAME_JSON, Object.class); assertThat(request.getRedirectUrl()).isEqualTo("http://localhost?success"); } @Test public void deserializeWhenNullMatchingRequestParameterNameThenRedirectUrlDoesNotContainParam() throws IOException { DefaultSavedRequest request = (DefaultSavedRequest) this.mapper.readValue(REQUEST_JSON, Object.class); assertThat(request.getRedirectUrl()).isEqualTo("http://localhost"); } }
6,986
42.12963
117
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jackson2/CookieMixinTests.java
/* * 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. * 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.jackson2; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import jakarta.servlet.http.Cookie; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jitendra Singh * @since 4.2 */ public class CookieMixinTests extends AbstractMixinTests { // @formatter:off private static final String COOKIE_JSON = "{" + " \"@class\": \"jakarta.servlet.http.Cookie\"," + " \"name\": \"demo\"," + " \"value\": \"cookie1\"," + " \"attributes\":{\"@class\":\"java.util.Collections$EmptyMap\"}," + " \"comment\": null," + " \"maxAge\": -1," + " \"path\": null," + " \"secure\": false," + " \"version\": 0," + " \"domain\": null" + "}"; // @formatter:on // @formatter:off private static final String COOKIE_HTTP_ONLY_JSON = "{" + " \"@class\": \"jakarta.servlet.http.Cookie\"," + " \"name\": \"demo\"," + " \"value\": \"cookie1\"," + " \"attributes\":{\"@class\":\"java.util.Collections$UnmodifiableMap\", \"HttpOnly\": \"true\"}," + " \"comment\": null," + " \"maxAge\": -1," + " \"path\": null," + " \"secure\": false," + " \"version\": 0," + " \"domain\": null" + "}"; // @formatter:on @Test public void serializeCookie() throws JsonProcessingException, JSONException { Cookie cookie = new Cookie("demo", "cookie1"); String actualString = this.mapper.writeValueAsString(cookie); JSONAssert.assertEquals(COOKIE_JSON, actualString, true); } @Test public void deserializeCookie() throws IOException { Cookie cookie = this.mapper.readValue(COOKIE_JSON, Cookie.class); assertThat(cookie).isNotNull(); assertThat(cookie.getName()).isEqualTo("demo"); assertThat(cookie.getDomain()).isEqualTo(""); } @Test public void serializeCookieWithHttpOnly() throws JsonProcessingException, JSONException { Cookie cookie = new Cookie("demo", "cookie1"); cookie.setHttpOnly(true); String actualString = this.mapper.writeValueAsString(cookie); JSONAssert.assertEquals(COOKIE_HTTP_ONLY_JSON, actualString, true); } @Test public void deserializeCookieWithHttpOnly() throws IOException { Cookie cookie = this.mapper.readValue(COOKIE_HTTP_ONLY_JSON, Cookie.class); assertThat(cookie).isNotNull(); assertThat(cookie.getName()).isEqualTo("demo"); assertThat(cookie.getDomain()).isEqualTo(""); assertThat(cookie.isHttpOnly()).isEqualTo(true); } }
3,141
31.061224
101
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/jackson2/AbstractMixinTests.java
/* * Copyright 2015-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. * 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.jackson2; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.springframework.security.jackson2.SecurityJackson2Modules; /** * @author Jitenra Singh * @since 4.2 */ public abstract class AbstractMixinTests { protected ObjectMapper mapper; @BeforeEach public void setup() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } }
1,169
28.25
75
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java
/* * 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. * 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.header; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests for the {@code HeadersFilter} * * @author Marten Deinum * @author Rob Winch * @since 3.2 */ @ExtendWith(MockitoExtension.class) public class HeaderWriterFilterTests { @Mock private HeaderWriter writer1; @Mock private HeaderWriter writer2; @Test public void noHeadersConfigured() { assertThatIllegalArgumentException().isThrownBy(() -> new HeaderWriterFilter(new ArrayList<>())); } @Test public void constructorNullWriters() { assertThatIllegalArgumentException().isThrownBy(() -> new HeaderWriterFilter(null)); } @Test public void additionalHeadersShouldBeAddedToTheResponse() throws Exception { List<HeaderWriter> headerWriters = new ArrayList<>(); headerWriters.add(this.writer1); headerWriters.add(this.writer2); HeaderWriterFilter filter = new HeaderWriterFilter(headerWriters); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); filter.doFilter(request, response, filterChain); verify(this.writer1).writeHeaders(request, response); verify(this.writer2).writeHeaders(request, response); HeaderWriterFilter.HeaderWriterRequest wrappedRequest = (HeaderWriterFilter.HeaderWriterRequest) filterChain .getRequest(); assertThat(wrappedRequest.getRequest()).isEqualTo(request); // verify the // filterChain // continued } // gh-2953 @Test public void headersDelayed() throws Exception { HeaderWriterFilter filter = new HeaderWriterFilter(Arrays.<HeaderWriter>asList(this.writer1)); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, (request1, response1) -> { verifyNoMoreInteractions(HeaderWriterFilterTests.this.writer1); response1.flushBuffer(); verify(HeaderWriterFilterTests.this.writer1).writeHeaders(any(HttpServletRequest.class), any(HttpServletResponse.class)); }); verifyNoMoreInteractions(this.writer1); } // gh-5499 @Test public void doFilterWhenRequestContainsIncludeThenHeadersStillWritten() throws Exception { HeaderWriterFilter filter = new HeaderWriterFilter(Collections.singletonList(this.writer1)); MockHttpServletRequest mockRequest = new MockHttpServletRequest(); MockHttpServletResponse mockResponse = new MockHttpServletResponse(); filter.doFilter(mockRequest, mockResponse, (request, response) -> { verifyNoMoreInteractions(HeaderWriterFilterTests.this.writer1); request.getRequestDispatcher("/").include(request, response); verify(HeaderWriterFilterTests.this.writer1).writeHeaders(any(HttpServletRequest.class), any(HttpServletResponse.class)); }); verifyNoMoreInteractions(this.writer1); } @Test public void headersWrittenAtBeginningOfRequest() throws Exception { HeaderWriterFilter filter = new HeaderWriterFilter(Collections.singletonList(this.writer1)); filter.setShouldWriteHeadersEagerly(true); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, (request1, response1) -> verify(HeaderWriterFilterTests.this.writer1) .writeHeaders(any(HttpServletRequest.class), any(HttpServletResponse.class))); verifyNoMoreInteractions(this.writer1); } }
4,916
37.414063
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/StaticHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; import java.util.Arrays; import java.util.Collections; 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 org.springframework.security.web.header.Header; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Test for the {@code StaticHeadersWriter} * * @author Marten Deinum * @author Rob Winch * @author Ankur Pathak * @since 3.2 */ public class StaticHeaderWriterTests { private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test public void constructorNullHeaders() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticHeadersWriter(null)); } @Test public void constructorEmptyHeaders() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticHeadersWriter(Collections.<Header>emptyList())); } @Test public void constructorNullHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticHeadersWriter(null, "value1")); } @Test public void constructorNullHeaderValues() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticHeadersWriter("name", (String[]) null)); } @Test public void constructorContainsNullHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticHeadersWriter("name", "value1", null)); } @Test public void sameHeaderShouldBeReturned() { String headerName = "X-header"; String headerValue = "foo"; StaticHeadersWriter factory = new StaticHeadersWriter(headerName, headerValue); factory.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderValues(headerName)).isEqualTo(Arrays.asList(headerValue)); } @Test public void writeHeadersMulti() { Header pragma = new Header("Pragma", "no-cache"); Header cacheControl = new Header("Cache-Control", "no-cache", "no-store", "must-revalidate"); StaticHeadersWriter factory = new StaticHeadersWriter(Arrays.asList(pragma, cacheControl)); factory.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(2); assertThat(this.response.getHeaderValues(pragma.getName())).isEqualTo(pragma.getValues()); assertThat(this.response.getHeaderValues(cacheControl.getName())).isEqualTo(cacheControl.getValues()); } @Test public void writeHeaderWhenNotPresent() { String pragmaValue = new String("pragmaValue"); String cacheControlValue = new String("cacheControlValue"); this.response.setHeader("Pragma", pragmaValue); this.response.setHeader("Cache-Control", cacheControlValue); Header pragma = new Header("Pragma", "no-cache"); Header cacheControl = new Header("Cache-Control", "no-cache", "no-store", "must-revalidate"); StaticHeadersWriter factory = new StaticHeadersWriter(Arrays.asList(pragma, cacheControl)); factory.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(2); assertThat(this.response.getHeader("Pragma")).isSameAs(pragmaValue); assertThat(this.response.getHeader("Cache-Control")).isSameAs(cacheControlValue); } }
4,056
34.902655
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/HpkpHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Tim Ysewyn * @author Ankur Pathak * */ public class HpkpHeaderWriterTests { private static final Map<String, String> DEFAULT_PINS; static { Map<String, String> defaultPins = new LinkedHashMap<>(); defaultPins.put("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "sha256"); DEFAULT_PINS = Collections.unmodifiableMap(defaultPins); } private MockHttpServletRequest request; private MockHttpServletResponse response; private HpkpHeaderWriter writer; private static final String HPKP_HEADER_NAME = "Public-Key-Pins"; private static final String HPKP_RO_HEADER_NAME = "Public-Key-Pins-Report-Only"; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.writer = new HpkpHeaderWriter(); Map<String, String> defaultPins = new LinkedHashMap<>(); defaultPins.put("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "sha256"); this.writer.setPins(defaultPins); this.request.setSecure(true); } @Test public void writeHeadersDefaultValues() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")) .isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""); } @Test public void maxAgeCustomConstructorWriteHeaders() { this.writer = new HpkpHeaderWriter(2592000); this.writer.setPins(DEFAULT_PINS); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")) .isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""); } @Test public void maxAgeAndIncludeSubdomainsCustomConstructorWriteHeaders() { this.writer = new HpkpHeaderWriter(2592000, true); this.writer.setPins(DEFAULT_PINS); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo( "max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains"); } @Test public void allArgsCustomConstructorWriteHeaders() { this.writer = new HpkpHeaderWriter(2592000, true, false); this.writer.setPins(DEFAULT_PINS); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins")).isEqualTo( "max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains"); } @Test public void writeHeadersCustomMaxAgeInSeconds() { this.writer.setMaxAgeInSeconds(2592000); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")) .isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""); } @Test public void writeHeadersIncludeSubDomains() { this.writer.setIncludeSubDomains(true); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo( "max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains"); } @Test public void writeHeadersTerminateConnection() { this.writer.setReportOnly(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins")) .isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""); } @Test public void writeHeadersTerminateConnectionWithURI() throws URISyntaxException { this.writer.setReportOnly(false); this.writer.setReportUri(new URI("https://example.com/pkp-report")); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins")).isEqualTo( "max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.com/pkp-report\""); } @Test public void writeHeadersTerminateConnectionWithURIAsString() { this.writer.setReportOnly(false); this.writer.setReportUri("https://example.com/pkp-report"); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins")).isEqualTo( "max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.com/pkp-report\""); } @Test public void writeHeadersAddSha256Pins() { this.writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo( "max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\""); } @Test public void writeHeadersInsecureRequestDoesNotWriteHeader() { this.request.setSecure(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).isEmpty(); } @Test public void setMaxAgeInSecondsToNegative() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setMaxAgeInSeconds(-1)); } @Test public void addSha256PinsWithNullPin() { assertThatIllegalArgumentException() .isThrownBy(() -> this.writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", null)); } @Test public void setIncorrectReportUri() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setReportUri("some url here...")); } @Test public void writePublicKeyPinsHeaderOnlyWhenNotPresent() { String value = new String("value"); this.response.setHeader(HPKP_HEADER_NAME, value); this.writer.setReportOnly(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HPKP_HEADER_NAME)).isSameAs(value); } @Test public void writePublicKeyPinsReportOnlyHeaderWhenNotPresent() { String value = new String("value"); this.response.setHeader(HPKP_RO_HEADER_NAME, value); this.writer.setReportOnly(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HPKP_RO_HEADER_NAME)).isSameAs(value); } }
7,926
37.668293
147
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; import java.util.Arrays; import java.util.Collections; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.springframework.security.web.header.HeaderWriter; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for class {@link CompositeHeaderWriter}/. * * @author Ankur Pathak * @since 5.2 */ public class CompositeHeaderWriterTests { @Test public void writeHeadersWhenConfiguredWithDelegatesThenInvokesEach() { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HeaderWriter one = mock(HeaderWriter.class); HeaderWriter two = mock(HeaderWriter.class); CompositeHeaderWriter headerWriter = new CompositeHeaderWriter(Arrays.asList(one, two)); headerWriter.writeHeaders(request, response); verify(one).writeHeaders(request, response); verify(two).writeHeaders(request, response); } @Test public void constructorWhenPassingEmptyListThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new CompositeHeaderWriter(Collections.emptyList())); } }
1,969
32.965517
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Joe Grandja * @author Ankur Pathak */ public class ContentSecurityPolicyHeaderWriterTests { private static final String DEFAULT_POLICY_DIRECTIVES = "default-src 'self'"; private MockHttpServletRequest request; private MockHttpServletResponse response; private ContentSecurityPolicyHeaderWriter writer; private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; private static final String CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only"; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.request.setSecure(true); this.response = new MockHttpServletResponse(); this.writer = new ContentSecurityPolicyHeaderWriter(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersWhenNoPolicyDirectivesThenUsesDefault() { ContentSecurityPolicyHeaderWriter noPolicyWriter = new ContentSecurityPolicyHeaderWriter(); noPolicyWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersContentSecurityPolicyDefault() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersContentSecurityPolicyCustom() { String policyDirectives = "default-src 'self'; " + "object-src plugins1.example.com plugins2.example.com; " + "script-src trustedscripts.example.com"; this.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(policyDirectives); } @Test public void writeHeadersWhenNoPolicyDirectivesReportOnlyThenUsesDefault() { ContentSecurityPolicyHeaderWriter noPolicyWriter = new ContentSecurityPolicyHeaderWriter(); this.writer.setReportOnly(true); noPolicyWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersContentSecurityPolicyReportOnlyDefault() { this.writer.setReportOnly(true); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersContentSecurityPolicyReportOnlyCustom() { String policyDirectives = "default-src https:; report-uri https://example.com/"; this.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives); this.writer.setReportOnly(true); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(policyDirectives); } @Test public void writeHeadersContentSecurityPolicyInvalid() { assertThatIllegalArgumentException().isThrownBy(() -> new ContentSecurityPolicyHeaderWriter("")); assertThatIllegalArgumentException().isThrownBy(() -> new ContentSecurityPolicyHeaderWriter(null)); } @Test public void writeContentSecurityPolicyHeaderWhenNotPresent() { String value = new String("value"); this.response.setHeader(CONTENT_SECURITY_POLICY_HEADER, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(CONTENT_SECURITY_POLICY_HEADER)).isSameAs(value); } @Test public void writeContentSecurityPolicyReportOnlyHeaderWhenNotPresent() { String value = new String("value"); this.response.setHeader(CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER, value); this.writer.setReportOnly(true); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER)).isSameAs(value); } }
5,244
39.346154
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/ReferrerPolicyHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; 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 org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Eddú Meléndez * @author Ankur Pathak */ public class ReferrerPolicyHeaderWriterTests { private final String DEFAULT_REFERRER_POLICY = "no-referrer"; private MockHttpServletRequest request; private MockHttpServletResponse response; private ReferrerPolicyHeaderWriter writer; private static final String REFERRER_POLICY_HEADER = "Referrer-Policy"; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.request.setSecure(true); this.response = new MockHttpServletResponse(); this.writer = new ReferrerPolicyHeaderWriter(); } @Test public void writeHeadersReferrerPolicyDefault() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Referrer-Policy")).isEqualTo(this.DEFAULT_REFERRER_POLICY); } @Test public void writeHeadersReferrerPolicyCustom() { this.writer = new ReferrerPolicyHeaderWriter(ReferrerPolicy.SAME_ORIGIN); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Referrer-Policy")).isEqualTo("same-origin"); } @Test public void writeHeaderReferrerPolicyInvalid() { assertThatIllegalArgumentException().isThrownBy(() -> new ReferrerPolicyHeaderWriter(null)); } @Test public void writeHeaderWhenNotPresent() { String value = new String("value"); this.response.setHeader(REFERRER_POLICY_HEADER, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(REFERRER_POLICY_HEADER)).isSameAs(value); } }
2,763
32.707317
97
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/CacheControlHeadersWriterTests.java
/* * 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. * 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.header.writers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ public class CacheControlHeadersWriterTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private CacheControlHeadersWriter writer; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.writer = new CacheControlHeadersWriter(); } @Test public void writeHeaders() { this.writer.writeHeaders(this.request, this.response); 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"); assertThat(this.response.getHeaderValues("Expires")).containsOnly("0"); } // gh-2953 @Test public void writeHeadersDisabledIfCacheControl() { this.response.setHeader("Cache-Control", "max-age: 123"); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("Cache-Control")).containsOnly("max-age: 123"); assertThat(this.response.getHeaderValue("Pragma")).isNull(); assertThat(this.response.getHeaderValue("Expires")).isNull(); } @Test public void writeHeadersDisabledIfPragma() { this.response.setHeader("Pragma", "mock"); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("Pragma")).containsOnly("mock"); assertThat(this.response.getHeaderValue("Expires")).isNull(); assertThat(this.response.getHeaderValue("Cache-Control")).isNull(); } @Test public void writeHeadersDisabledIfExpires() { this.response.setHeader("Expires", "mock"); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("Expires")).containsOnly("mock"); assertThat(this.response.getHeaderValue("Cache-Control")).isNull(); assertThat(this.response.getHeaderValue("Pragma")).isNull(); } @Test // gh-5534 public void writeHeadersDisabledIfNotModified() { this.response.setStatus(HttpStatus.NOT_MODIFIED.value()); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).isEmpty(); } }
3,395
34.010309
90
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; 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 org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rafiullah Hamedy * @author Josh Cummings * @see ClearSiteDataHeaderWriter */ public class ClearSiteDataHeaderWriterTests { private static final String HEADER_NAME = "Clear-Site-Data"; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.request.setSecure(true); this.response = new MockHttpServletResponse(); } @Test public void createInstanceWhenMissingSourceThenThrowsException() { assertThatExceptionOfType(Exception.class).isThrownBy(() -> new ClearSiteDataHeaderWriter()) .withMessage("directives cannot be empty or null"); } @Test public void writeHeaderWhenRequestNotSecureThenHeaderIsNotPresent() { this.request.setSecure(false); ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE); headerWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HEADER_NAME)).isNull(); } @Test public void writeHeaderWhenRequestIsSecureThenHeaderValueMatchesPassedSource() { ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.STORAGE); headerWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HEADER_NAME)).isEqualTo("\"storage\""); } @Test public void writeHeaderWhenRequestIsSecureThenHeaderValueMatchesPassedSources() { ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE, Directive.COOKIES, Directive.STORAGE, Directive.EXECUTION_CONTEXTS); headerWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HEADER_NAME)) .isEqualTo("\"cache\", \"cookies\", \"storage\", \"executionContexts\""); } }
2,885
35.075
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link FeaturePolicyHeaderWriter}. * * @author Vedran Pavic * @author Ankur Pathak */ public class FeaturePolicyHeaderWriterTests { private static final String DEFAULT_POLICY_DIRECTIVES = "geolocation 'self'"; private MockHttpServletRequest request; private MockHttpServletResponse response; private FeaturePolicyHeaderWriter writer; private static final String FEATURE_POLICY_HEADER = "Feature-Policy"; @BeforeEach public void setUp() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.writer = new FeaturePolicyHeaderWriter(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersFeaturePolicyDefault() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Feature-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES); } @Test public void createWriterWithNullDirectivesShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new FeaturePolicyHeaderWriter(null)) .withMessage("policyDirectives must not be null or empty"); } @Test public void createWriterWithEmptyDirectivesShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new FeaturePolicyHeaderWriter("")) .withMessage("policyDirectives must not be null or empty"); } @Test public void writeHeaderOnlyIfNotPresent() { String value = new String("value"); this.response.setHeader(FEATURE_POLICY_HEADER, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(FEATURE_POLICY_HEADER)).isSameAs(value); } }
2,695
32.283951
93
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriterTests.java
/* * Copyright 2002-2013 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.header.writers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class DelegatingRequestMatcherHeaderWriterTests { @Mock private RequestMatcher matcher; @Mock private HeaderWriter delegate; private MockHttpServletRequest request; private MockHttpServletResponse response; private DelegatingRequestMatcherHeaderWriter headerWriter; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.headerWriter = new DelegatingRequestMatcherHeaderWriter(this.matcher, this.delegate); } @Test public void constructorNullRequestMatcher() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(null, this.delegate)); } @Test public void constructorNullDelegate() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(this.matcher, null)); } @Test public void writeHeadersOnMatch() { given(this.matcher.matches(this.request)).willReturn(true); this.headerWriter.writeHeaders(this.request, this.response); verify(this.delegate).writeHeaders(this.request, this.response); } @Test public void writeHeadersOnNoMatch() { given(this.matcher.matches(this.request)).willReturn(false); this.headerWriter.writeHeaders(this.request, this.response); verify(this.delegate, times(0)).writeHeaders(this.request, this.response); } }
2,784
30.647727
92
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/XXssProtectionHeaderWriterTests.java
/* * 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. * 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.header.writers; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @author Ankur Pathak * @author Daniel Garnier-Moiroux * */ public class XXssProtectionHeaderWriterTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private XXssProtectionHeaderWriter writer; private static final String XSS_PROTECTION_HEADER = "X-XSS-Protection"; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.writer = new XXssProtectionHeaderWriter(); } @Test public void writeHeaders() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("0"); } @Test public void writeHeaderWhenNotPresent() { String value = new String("value"); this.response.setHeader(XSS_PROTECTION_HEADER, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(XSS_PROTECTION_HEADER)).isSameAs(value); } @Test void writeHeaderWhenDisabled() { this.writer.setHeaderValue(XXssProtectionHeaderWriter.HeaderValue.DISABLED); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("0"); } @Test void writeHeaderWhenEnabled() { this.writer.setHeaderValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("1"); } @Test void writeHeaderWhenEnabledModeBlock() { this.writer.setHeaderValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("1; mode=block"); } @Test public void setHeaderValueNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setHeaderValue(null)) .withMessage("headerValue cannot be null"); } }
3,284
32.865979
94
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginEmbedderPolicyHeaderWriterTests.java
/* * Copyright 2002-2021 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.header.writers; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; class CrossOriginEmbedderPolicyHeaderWriterTests { private static final String EMBEDDER_HEADER_NAME = "Cross-Origin-Embedder-Policy"; private CrossOriginEmbedderPolicyHeaderWriter writer; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach void setup() { this.writer = new CrossOriginEmbedderPolicyHeaderWriter(); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test void setEmbedderPolicyWhenNullEmbedderPolicyThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) .withMessage("embedderPolicy cannot be null"); } @Test void writeHeadersWhenDefaultValuesThenDontWriteHeaders() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(0); } @Test void writeHeadersWhenResponseHeaderExistsThenDontOverride() { this.response.addHeader(EMBEDDER_HEADER_NAME, "require-corp"); this.writer.setPolicy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.UNSAFE_NONE); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(EMBEDDER_HEADER_NAME)).isEqualTo("require-corp"); } @Test void writeHeadersWhenSetHeaderValuesThenWrites() { this.writer.setPolicy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(EMBEDDER_HEADER_NAME)).isEqualTo("require-corp"); } @Test void writeHeadersWhenSetEmbedderPolicyThenWritesEmbedderPolicy() { this.writer.setPolicy(CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.UNSAFE_NONE); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader(EMBEDDER_HEADER_NAME)).isEqualTo("unsafe-none"); } }
2,975
35.740741
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginOpenerPolicyHeaderWriterTests.java
/* * Copyright 2002-2021 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.header.writers; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; class CrossOriginOpenerPolicyHeaderWriterTests { private static final String OPENER_HEADER_NAME = "Cross-Origin-Opener-Policy"; private CrossOriginOpenerPolicyHeaderWriter writer; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach void setup() { this.writer = new CrossOriginOpenerPolicyHeaderWriter(); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test void setOpenerPolicyWhenNullOpenerPolicyThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) .withMessage("openerPolicy cannot be null"); } @Test void writeHeadersWhenDefaultValuesThenDontWriteHeaders() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(0); } @Test void writeHeadersWhenResponseHeaderExistsThenDontOverride() { this.response.addHeader(OPENER_HEADER_NAME, "same-origin"); this.writer.setPolicy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(OPENER_HEADER_NAME)).isEqualTo("same-origin"); } @Test void writeHeadersWhenSetHeaderValuesThenWrites() { this.writer.setPolicy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(OPENER_HEADER_NAME)).isEqualTo("same-origin-allow-popups"); } @Test void writeHeadersWhenSetOpenerPolicyThenWritesOpenerPolicy() { this.writer.setPolicy(CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader(OPENER_HEADER_NAME)).isEqualTo("same-origin-allow-popups"); } }
2,996
36
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/XContentTypeOptionsHeaderWriterTests.java
/* * 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. * 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.header.writers; 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 Rob Winch * */ public class XContentTypeOptionsHeaderWriterTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private XContentTypeOptionsHeaderWriter writer; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.writer = new XContentTypeOptionsHeaderWriter(); } @Test public void writeHeaders() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeaderValues("X-Content-Type-Options")).containsExactly("nosniff"); } }
1,606
28.759259
97
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/PermissionsPolicyHeaderWriterTests.java
/* * Copyright 2002-2020 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.header.writers; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link PermissionsPolicyHeaderWriter}. * * @author Christophe Gilles */ public class PermissionsPolicyHeaderWriterTests { private static final String DEFAULT_POLICY_DIRECTIVES = "geolocation=(self)"; private MockHttpServletRequest request; private MockHttpServletResponse response; private PermissionsPolicyHeaderWriter writer; private static final String PERMISSIONS_POLICY_HEADER = "Permissions-Policy"; @BeforeEach public void setUp() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.writer = new PermissionsPolicyHeaderWriter(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersPermissionsPolicyDefault() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Permissions-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES); } @Test public void createWriterWithNullPolicyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PermissionsPolicyHeaderWriter(null)) .withMessage("policy can not be null or empty"); } @Test public void createWriterWithEmptyPolicyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PermissionsPolicyHeaderWriter("")) .withMessage("policy can not be null or empty"); } @Test public void writeHeaderOnlyIfNotPresent() { String value = new String("value"); this.response.setHeader(PERMISSIONS_POLICY_HEADER, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(PERMISSIONS_POLICY_HEADER)).isSameAs(value); } }
2,694
32.6875
97
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/CrossOriginResourcePolicyHeaderWriterTests.java
/* * Copyright 2002-2021 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.header.writers; 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; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; class CrossOriginResourcePolicyHeaderWriterTests { private static final String RESOURCE_HEADER_NAME = "Cross-Origin-Resource-Policy"; private CrossOriginResourcePolicyHeaderWriter writer; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach void setup() { this.writer = new CrossOriginResourcePolicyHeaderWriter(); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test void setResourcePolicyWhenNullThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) .withMessage("resourcePolicy cannot be null"); } @Test void writeHeadersWhenDefaultValuesThenDontWriteHeaders() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(0); } @Test void writeHeadersWhenResponseHeaderExistsThenDontOverride() { this.response.addHeader(RESOURCE_HEADER_NAME, "same-site"); this.writer.setPolicy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.CROSS_ORIGIN); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(RESOURCE_HEADER_NAME)).isEqualTo("same-site"); } @Test void writeHeadersWhenSetHeaderValuesThenWrites() { this.writer.setPolicy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_ORIGIN); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(RESOURCE_HEADER_NAME)).isEqualTo("same-origin"); } @Test void writeHeadersWhenSetResourcePolicyThenWritesResourcePolicy() { this.writer.setPolicy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_SITE); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader(RESOURCE_HEADER_NAME)).isEqualTo("same-site"); } }
2,950
35.432099
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/HstsHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers; 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 org.springframework.security.web.util.matcher.AnyRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @author Ankur Pathak * */ public class HstsHeaderWriterTests { private MockHttpServletRequest request; private MockHttpServletResponse response; private HstsHeaderWriter writer; private static final String HSTS_HEADER_NAME = "Strict-Transport-Security"; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.request.setSecure(true); this.response = new MockHttpServletResponse(); this.writer = new HstsHeaderWriter(); } @Test public void allArgsCustomConstructorWriteHeaders() { this.request.setSecure(false); this.writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000"); } @Test public void maxAgeAndIncludeSubdomainsCustomConstructorWriteHeaders() { this.request.setSecure(false); this.writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000"); } @Test public void maxAgeCustomConstructorWriteHeaders() { this.writer = new HstsHeaderWriter(15768000); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")) .isEqualTo("max-age=15768000 ; includeSubDomains"); } @Test public void includeSubDomainsCustomConstructorWriteHeaders() { this.writer = new HstsHeaderWriter(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000"); } @Test public void writeHeadersDefaultValues() { this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")) .isEqualTo("max-age=31536000 ; includeSubDomains"); } @Test public void writeHeadersIncludeSubDomainsFalse() { this.writer.setIncludeSubDomains(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000"); } @Test public void writeHeadersCustomMaxAgeInSeconds() { this.writer.setMaxAgeInSeconds(1); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=1 ; includeSubDomains"); } @Test public void writeHeadersInsecureRequestDoesNotWriteHeader() { this.request.setSecure(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames().isEmpty()).isTrue(); } @Test public void writeHeadersAnyRequestMatcher() { this.writer.setRequestMatcher(AnyRequestMatcher.INSTANCE); this.request.setSecure(false); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader("Strict-Transport-Security")) .isEqualTo("max-age=31536000 ; includeSubDomains"); } @Test public void setMaxAgeInSecondsToNegative() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setMaxAgeInSeconds(-1)); } @Test public void setRequestMatcherToNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setRequestMatcher(null)); } @Test public void writeHeaderWhenNotPresent() { String value = new String("value"); this.response.setHeader(HSTS_HEADER_NAME, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HSTS_HEADER_NAME)).isSameAs(value); } }
5,203
34.401361
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/StaticAllowFromStrategyTests.java
/* * 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. * 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.header.writers.frameoptions; import java.net.URI; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; /** * Test for the StaticAllowFromStrategy. * * @author Marten Deinum * @since 3.2 */ public class StaticAllowFromStrategyTests { @Test public void shouldReturnUri() { String uri = "https://www.test.com"; StaticAllowFromStrategy strategy = new StaticAllowFromStrategy(URI.create(uri)); assertThat(strategy.getAllowFromValue(new MockHttpServletRequest())).isEqualTo(uri); } }
1,263
28.395349
86
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/RegExpAllowFromStrategyTests.java
/* * 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. * 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.header.writers.frameoptions; import java.util.regex.PatternSyntaxException; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Marten Deinum */ public class RegExpAllowFromStrategyTests { @Test public void invalidRegularExpressionShouldLeadToException() { assertThatExceptionOfType(PatternSyntaxException.class).isThrownBy(() -> new RegExpAllowFromStrategy("[a-z")); } @Test public void nullRegularExpressionShouldLeadToException() { assertThatIllegalArgumentException().isThrownBy(() -> new RegExpAllowFromStrategy(null)); } @Test public void subdomainMatchingRegularExpression() { RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy("^https://([a-z0-9]*?\\.)test\\.com"); strategy.setAllowFromParameterName("from"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("from", "https://www.test.com"); String result1 = strategy.getAllowFromValue(request); assertThat(result1).isEqualTo("https://www.test.com"); request.setParameter("from", "https://www.test.com"); String result2 = strategy.getAllowFromValue(request); assertThat(result2).isEqualTo("https://www.test.com"); request.setParameter("from", "https://test.foobar.com"); String result3 = strategy.getAllowFromValue(request); assertThat(result3).isEqualTo("DENY"); } @Test public void noParameterShouldDeny() { RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy("^https://([a-z0-9]*?\\.)test\\.com"); MockHttpServletRequest request = new MockHttpServletRequest(); String result1 = strategy.getAllowFromValue(request); assertThat(result1).isEqualTo("DENY"); } }
2,571
36.275362
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/WhiteListedAllowFromStrategyTests.java
/* * 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. * 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.header.writers.frameoptions; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Test for the {@code WhiteListedAllowFromStrategy}. * * @author Marten Deinum * @since 3.2 */ public class WhiteListedAllowFromStrategyTests { @Test public void emptyListShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new WhiteListedAllowFromStrategy(new ArrayList<>())); } @Test public void nullListShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new WhiteListedAllowFromStrategy(null)); } @Test public void listWithSingleElementShouldMatch() { List<String> allowed = new ArrayList<>(); allowed.add("https://www.test.com"); WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed); strategy.setAllowFromParameterName("from"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("from", "https://www.test.com"); String result = strategy.getAllowFromValue(request); assertThat(result).isEqualTo("https://www.test.com"); } @Test public void listWithMultipleElementShouldMatch() { List<String> allowed = new ArrayList<>(); allowed.add("https://www.test.com"); allowed.add("https://www.springsource.org"); WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed); strategy.setAllowFromParameterName("from"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("from", "https://www.test.com"); String result = strategy.getAllowFromValue(request); assertThat(result).isEqualTo("https://www.test.com"); } @Test public void listWithSingleElementShouldNotMatch() { List<String> allowed = new ArrayList<>(); allowed.add("https://www.test.com"); WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed); strategy.setAllowFromParameterName("from"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("from", "https://www.test123.com"); String result = strategy.getAllowFromValue(request); assertThat(result).isEqualTo("DENY"); } @Test public void requestWithoutParameterShouldNotMatch() { List<String> allowed = new ArrayList<>(); allowed.add("https://www.test.com"); WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed); strategy.setAllowFromParameterName("from"); MockHttpServletRequest request = new MockHttpServletRequest(); String result = strategy.getAllowFromValue(request); assertThat(result).isEqualTo("DENY"); } }
3,462
35.072917
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/AbstractRequestParameterAllowFromStrategyTests.java
/* * Copyright 2002-2013 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.header.writers.frameoptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * */ public class AbstractRequestParameterAllowFromStrategyTests { private MockHttpServletRequest request; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); } @Test public void nullAllowFromParameterValue() { RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true); assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY"); } @Test public void emptyAllowFromParameterValue() { this.request.setParameter("x-frames-allow-from", ""); RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true); assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY"); } @Test public void emptyAllowFromCustomParameterValue() { String customParam = "custom"; this.request.setParameter(customParam, ""); RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true); strategy.setAllowFromParameterName(customParam); assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY"); } @Test public void allowFromParameterValueAllowed() { String value = "https://example.com"; this.request.setParameter("x-frames-allow-from", value); RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true); assertThat(strategy.getAllowFromValue(this.request)).isEqualTo(value); } @Test public void allowFromParameterValueDenied() { String value = "https://example.com"; this.request.setParameter("x-frames-allow-from", value); RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(false); assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY"); } private static class RequestParameterAllowFromStrategyStub extends AbstractRequestParameterAllowFromStrategy { private boolean match; RequestParameterAllowFromStrategyStub(boolean match) { this.match = match; } @Override protected boolean allowed(String allowFromOrigin) { return this.match; } } }
2,985
31.107527
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/FrameOptionsHeaderWriterTests.java
/* * 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. * 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.header.writers.frameoptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class FrameOptionsHeaderWriterTests { @Mock private AllowFromStrategy strategy; private MockHttpServletResponse response; private MockHttpServletRequest request; private XFrameOptionsHeaderWriter writer; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test public void constructorNullMode() { assertThatIllegalArgumentException().isThrownBy(() -> new XFrameOptionsHeaderWriter((XFrameOptionsMode) null)); } @Test public void constructorAllowFromNoAllowFromStrategy() { assertThatIllegalArgumentException() .isThrownBy(() -> new XFrameOptionsHeaderWriter(XFrameOptionsMode.ALLOW_FROM)); } @Test public void constructorNullAllowFromStrategy() { assertThatIllegalArgumentException().isThrownBy(() -> new XFrameOptionsHeaderWriter((AllowFromStrategy) null)); } @Test public void writeHeadersAllowFromReturnsNull() { this.writer = new XFrameOptionsHeaderWriter(this.strategy); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames().isEmpty()).isTrue(); } @Test public void writeHeadersAllowFrom() { String allowFromValue = "https://example.com/"; given(this.strategy.getAllowFromValue(this.request)).willReturn(allowFromValue); this.writer = new XFrameOptionsHeaderWriter(this.strategy); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)) .isEqualTo("ALLOW-FROM " + allowFromValue); } @Test public void writeHeadersDeny() { this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); } @Test public void writeHeadersSameOrigin() { this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("SAMEORIGIN"); } @Test public void writeHeadersTwiceLastWins() { this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN); this.writer.writeHeaders(this.request, this.response); this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderNames()).hasSize(1); assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); } }
4,181
35.051724
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/XFrameOptionsHeaderWriterTests.java
/* * Copyright 2002-2019 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.header.writers.frameoptions; import java.util.Arrays; import java.util.Collections; 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 Rob Winch * @author Ankur Pathak * @since 5.0 */ public class XFrameOptionsHeaderWriterTests { private MockHttpServletRequest request = new MockHttpServletRequest(); private MockHttpServletResponse response = new MockHttpServletResponse(); private static final String XFRAME_OPTIONS_HEADER = "X-Frame-Options"; @Test public void writeHeadersWhenWhiteList() { WhiteListedAllowFromStrategy whitelist = new WhiteListedAllowFromStrategy(Arrays.asList("example.com")); XFrameOptionsHeaderWriter writer = new XFrameOptionsHeaderWriter(whitelist); writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderValue(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); } @Test public void writeHeaderWhenNotPresent() { WhiteListedAllowFromStrategy whitelist = new WhiteListedAllowFromStrategy( Collections.singletonList("example.com")); XFrameOptionsHeaderWriter writer = new XFrameOptionsHeaderWriter(whitelist); String value = new String("value"); this.response.setHeader(XFRAME_OPTIONS_HEADER, value); writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(XFRAME_OPTIONS_HEADER)).isSameAs(value); } }
2,190
34.33871
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/NoOpAccessDeniedHandlerTests.java
/* * 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); } }
1,469
34
79
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/DelegatingAccessDeniedHandlerTests.java
/* * Copyright 2002-2013 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 java.util.LinkedHashMap; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.csrf.CsrfException; import org.springframework.security.web.csrf.InvalidCsrfTokenException; import org.springframework.security.web.csrf.MissingCsrfTokenException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class DelegatingAccessDeniedHandlerTests { @Mock private AccessDeniedHandler handler1; @Mock private AccessDeniedHandler handler2; @Mock private AccessDeniedHandler handler3; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; private LinkedHashMap<Class<? extends AccessDeniedException>, AccessDeniedHandler> handlers; private DelegatingAccessDeniedHandler handler; @BeforeEach public void setup() { this.handlers = new LinkedHashMap<>(); } @Test public void moreSpecificDoesNotInvokeLessSpecific() throws Exception { this.handlers.put(CsrfException.class, this.handler1); this.handler = new DelegatingAccessDeniedHandler(this.handlers, this.handler3); AccessDeniedException accessDeniedException = new AccessDeniedException(""); this.handler.handle(this.request, this.response, accessDeniedException); verify(this.handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AccessDeniedException.class)); verify(this.handler3).handle(this.request, this.response, accessDeniedException); } @Test public void matchesDoesNotInvokeDefault() throws Exception { this.handlers.put(InvalidCsrfTokenException.class, this.handler1); this.handlers.put(MissingCsrfTokenException.class, this.handler2); this.handler = new DelegatingAccessDeniedHandler(this.handlers, this.handler3); AccessDeniedException accessDeniedException = new MissingCsrfTokenException("123"); this.handler.handle(this.request, this.response, accessDeniedException); verify(this.handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AccessDeniedException.class)); verify(this.handler2).handle(this.request, this.response, accessDeniedException); verify(this.handler3, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AccessDeniedException.class)); } }
3,381
36.164835
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/TestWebInvocationPrivilegeEvaluator.java
/* * Copyright 2002-2021 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 org.springframework.security.core.Authentication; public final class TestWebInvocationPrivilegeEvaluator { private static final AlwaysAllowWebInvocationPrivilegeEvaluator ALWAYS_ALLOW = new AlwaysAllowWebInvocationPrivilegeEvaluator(); private static final AlwaysDenyWebInvocationPrivilegeEvaluator ALWAYS_DENY = new AlwaysDenyWebInvocationPrivilegeEvaluator(); private TestWebInvocationPrivilegeEvaluator() { } public static WebInvocationPrivilegeEvaluator alwaysAllow() { return ALWAYS_ALLOW; } public static WebInvocationPrivilegeEvaluator alwaysDeny() { return ALWAYS_DENY; } private static class AlwaysAllowWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator { @Override public boolean isAllowed(String uri, Authentication authentication) { return true; } @Override public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { return true; } } private static class AlwaysDenyWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator { @Override public boolean isAllowed(String uri, Authentication authentication) { return false; } @Override public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) { return false; } } }
2,002
28.895522
129
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/AuthorizationManagerWebInvocationPrivilegeEvaluatorTests.java
/* * 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. * 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.ServletContext; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockServletContext; import org.springframework.security.authentication.TestAuthentication; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.authorization.AuthorizationManager; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class AuthorizationManagerWebInvocationPrivilegeEvaluatorTests { @InjectMocks private AuthorizationManagerWebInvocationPrivilegeEvaluator privilegeEvaluator; @Mock private AuthorizationManager<HttpServletRequest> authorizationManager; @Test void constructorWhenAuthorizationManagerNullThenIllegalArgument() { assertThatIllegalArgumentException() .isThrownBy(() -> new AuthorizationManagerWebInvocationPrivilegeEvaluator(null)) .withMessage("authorizationManager cannot be null"); } @Test void isAllowedWhenAuthorizationManagerAllowsThenAllowedTrue() { given(this.authorizationManager.check(any(), any())).willReturn(new AuthorizationDecision(true)); boolean allowed = this.privilegeEvaluator.isAllowed("/test", TestAuthentication.authenticatedUser()); assertThat(allowed).isTrue(); verify(this.authorizationManager).check(any(), any()); } @Test void isAllowedWhenAuthorizationManagerDeniesAllowedFalse() { given(this.authorizationManager.check(any(), any())).willReturn(new AuthorizationDecision(false)); boolean allowed = this.privilegeEvaluator.isAllowed("/test", TestAuthentication.authenticatedUser()); assertThat(allowed).isFalse(); } @Test void isAllowedWhenAuthorizationManagerAbstainsThenAllowedTrue() { given(this.authorizationManager.check(any(), any())).willReturn(null); boolean allowed = this.privilegeEvaluator.isAllowed("/test", TestAuthentication.authenticatedUser()); assertThat(allowed).isTrue(); } @Test void isAllowedWhenServletContextExistsThenFilterInvocationHasServletContext() { ServletContext servletContext = new MockServletContext(); this.privilegeEvaluator.setServletContext(servletContext); this.privilegeEvaluator.isAllowed("/test", TestAuthentication.authenticatedUser()); ArgumentCaptor<HttpServletRequest> captor = ArgumentCaptor.forClass(HttpServletRequest.class); verify(this.authorizationManager).check(any(), captor.capture()); assertThat(captor.getValue().getServletContext()).isSameAs(servletContext); } }
3,588
39.784091
103
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluatorTests.java
/* * Copyright 2002-2021 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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.context.ApplicationEventPublisher; import org.springframework.mock.web.MockServletContext; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.intercept.RunAsManager; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests * {@link org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator}. * * @author Ben Alex */ public class DefaultWebInvocationPrivilegeEvaluatorTests { private AccessDecisionManager adm; private FilterInvocationSecurityMetadataSource ods; private RunAsManager ram; private FilterSecurityInterceptor interceptor; @BeforeEach public final void setUp() { this.interceptor = new FilterSecurityInterceptor(); this.ods = mock(FilterInvocationSecurityMetadataSource.class); this.adm = mock(AccessDecisionManager.class); this.ram = mock(RunAsManager.class); this.interceptor.setAuthenticationManager(mock(AuthenticationManager.class)); this.interceptor.setSecurityMetadataSource(this.ods); this.interceptor.setAccessDecisionManager(this.adm); this.interceptor.setRunAsManager(this.ram); this.interceptor.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); SecurityContextHolder.clearContext(); } @Test public void permitsAccessIfNoMatchingAttributesAndPublicInvocationsAllowed() { DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); given(this.ods.getAttributes(any())).willReturn(null); assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isTrue(); } @Test public void deniesAccessIfNoMatchingAttributesAndPublicInvocationsNotAllowed() { DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); given(this.ods.getAttributes(any())).willReturn(null); this.interceptor.setRejectPublicInvocations(true); assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isFalse(); } @Test public void deniesAccessIfAuthenticationIsNull() { DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); assertThat(wipe.isAllowed("/foo/index.jsp", null)).isFalse(); } @Test public void allowsAccessIfAccessDecisionManagerDoes() { Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX"); DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); assertThat(wipe.isAllowed("/foo/index.jsp", token)).isTrue(); } @SuppressWarnings("unchecked") @Test public void deniesAccessIfAccessDecisionManagerDoes() { Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX"); DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); willThrow(new AccessDeniedException("")).given(this.adm).decide(any(Authentication.class), any(), anyList()); assertThat(wipe.isAllowed("/foo/index.jsp", token)).isFalse(); } @Test public void isAllowedWhenServletContextIsSetThenPassedFilterInvocationHasServletContext() { Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX"); MockServletContext servletContext = new MockServletContext(); ArgumentCaptor<FilterInvocation> filterInvocationArgumentCaptor = ArgumentCaptor .forClass(FilterInvocation.class); DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); wipe.setServletContext(servletContext); wipe.isAllowed("/foo/index.jsp", token); verify(this.adm).decide(eq(token), filterInvocationArgumentCaptor.capture(), any()); assertThat(filterInvocationArgumentCaptor.getValue().getRequest().getServletContext()).isNotNull(); } }
5,575
43.253968
111
java