Revert unnecessary merges on 6.0.x

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

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

View File

@@ -1,102 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author Steve Riesenberg
*/
public final class DelegatingSecurityContextTestUtils {
private DelegatingSecurityContextTestUtils() {
}
public static <T extends Executor> SecurityContext runAndReturn(ThreadFactory threadFactory,
Function<ScheduledExecutorService, T> factory, BiConsumer<T, Runnable> fn) throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(1);
AtomicReference<SecurityContext> result = new AtomicReference<>();
ScheduledExecutorService delegate = Executors.newSingleThreadScheduledExecutor(threadFactory);
try {
T executor = factory.apply(delegate);
Runnable task = () -> {
result.set(SecurityContextHolder.getContext());
countDownLatch.countDown();
};
fn.accept(executor, task);
countDownLatch.await();
return result.get();
}
finally {
delegate.shutdown();
}
}
public static <T extends TaskScheduler> SecurityContext runAndReturn(ThreadFactory threadFactory,
Function<ScheduledExecutorService, T> factory, BiFunction<T, Runnable, ScheduledFuture<?>> fn)
throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(1);
AtomicReference<SecurityContext> result = new AtomicReference<>();
ScheduledExecutorService delegate = Executors.newSingleThreadScheduledExecutor(threadFactory);
try {
T taskScheduler = factory.apply(delegate);
Runnable task = () -> {
result.set(SecurityContextHolder.getContext());
countDownLatch.countDown();
};
ScheduledFuture<?> future = fn.apply(taskScheduler, task);
countDownLatch.await();
future.cancel(false);
return result.get();
}
finally {
delegate.shutdown();
}
}
public static <T extends Executor> SecurityContext callAndReturn(ThreadFactory threadFactory,
Function<ScheduledExecutorService, T> factory,
BiFunction<T, Callable<SecurityContext>, Future<SecurityContext>> fn) throws Exception {
ScheduledExecutorService delegate = Executors.newSingleThreadScheduledExecutor(threadFactory);
try {
T executor = factory.apply(delegate);
Callable<SecurityContext> task = SecurityContextHolder::getContext;
return fn.apply(executor, task).get();
}
finally {
delegate.shutdown();
}
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.security.access.intercept;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.BadCredentialsException;
@@ -49,7 +50,7 @@ public class RunAsImplAuthenticationProviderTests {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("my_password");
Authentication result = provider.authenticate(token);
assertThat(result instanceof RunAsUserToken).as("Should have returned RunAsUserToken").isTrue();
Assertions.assertTrue(result instanceof RunAsUserToken, "Should have returned RunAsUserToken");
RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}

View File

@@ -66,9 +66,9 @@ public class RunAsManagerImplTests {
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(authorities).contains("FOOBAR_RUN_AS_SOMETHING");
assertThat(authorities).contains("ONE");
assertThat(authorities).contains("TWO");
assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue();
assertThat(authorities.contains("ONE")).isTrue();
assertThat(authorities.contains("TWO")).isTrue();
RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
@@ -87,9 +87,9 @@ public class RunAsManagerImplTests {
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(authorities).contains("ROLE_RUN_AS_SOMETHING");
assertThat(authorities).contains("ROLE_ONE");
assertThat(authorities).contains("ROLE_TWO");
assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue();
assertThat(authorities.contains("ROLE_ONE")).isTrue();
assertThat(authorities.contains("ROLE_TWO")).isTrue();
RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}

View File

@@ -50,7 +50,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(this.mds.getAllConfigAttributes()).isEmpty();
assertThat(this.mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation(null, String.class.getMethod("toString"));
assertThat(this.mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
// Exercise the cached case
@@ -68,7 +68,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(this.mds.getAllConfigAttributes()).isEmpty();
assertThat(this.mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation("", toString);
assertThat(this.mds.getAttributes(mi)).isSameAs(attributes);
// Exercise the cached case

View File

@@ -17,6 +17,7 @@
package org.springframework.security.access.vote;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
@@ -46,7 +47,9 @@ public class DenyAgainVoter implements AccessDecisionVoter<Object> {
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
for (ConfigAttribute attribute : attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator();
while (iter.hasNext()) {
ConfigAttribute attribute = iter.next();
if (this.supports(attribute)) {
return ACCESS_DENIED;
}

View File

@@ -17,6 +17,7 @@
package org.springframework.security.access.vote;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
@@ -48,7 +49,9 @@ public class DenyVoter implements AccessDecisionVoter<Object> {
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
for (ConfigAttribute attribute : attributes) {
Iterator<ConfigAttribute> iter = attributes.iterator();
while (iter.hasNext()) {
ConfigAttribute attribute = iter.next();
if (this.supports(attribute)) {
return ACCESS_DENIED;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -93,10 +93,4 @@ public class ObservationAuthenticationManagerTests {
assertThat(context.getAuthenticationResult()).isNull();
}
@Test
void setObservationConventionWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tested.setObservationConvention(null));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -96,10 +96,4 @@ public class ObservationReactiveAuthenticationManagerTests {
assertThat(context.getAuthenticationResult()).isNull();
}
@Test
void setObservationConventionWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tested.setObservationConvention(null));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,23 +17,15 @@
package org.springframework.security.authentication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetails;
/**
* @author Rob Winch
* @author Evgeniy Cheban
* @since 5.0
*/
public class TestAuthentication extends PasswordEncodedUser {
private static final Authentication ANONYMOUS = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
private static final RememberMeAuthenticationToken REMEMBER_ME = new RememberMeAuthenticationToken("key", "user",
AuthorityUtils.createAuthorityList("ROLE_USER"));
public static Authentication authenticatedAdmin() {
return autheticated(admin());
}
@@ -46,12 +38,4 @@ public class TestAuthentication extends PasswordEncodedUser {
return UsernamePasswordAuthenticationToken.authenticated(user, null, user.getAuthorities());
}
public static Authentication anonymousUser() {
return ANONYMOUS;
}
public static Authentication rememberMeUser() {
return REMEMBER_ME;
}
}

View File

@@ -222,13 +222,16 @@ public class DefaultJaasAuthenticationProviderTests {
public void javadocExample() {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(resName);
try (context) {
context.registerShutdownHook();
context.registerShutdownHook();
try {
this.provider = context.getBean(DefaultJaasAuthenticationProvider.class);
Authentication auth = this.provider.authenticate(this.token);
assertThat(auth.isAuthenticated()).isEqualTo(true);
assertThat(auth.getPrincipal()).isEqualTo(this.token.getPrincipal());
}
finally {
context.close();
}
}
private void verifyFailedLogin() {

View File

@@ -174,7 +174,8 @@ public class JaasAuthenticationProviderTests {
assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue();
boolean foundit = false;
for (GrantedAuthority a : list) {
if (a instanceof JaasGrantedAuthority grant) {
if (a instanceof JaasGrantedAuthority) {
JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority")
.isNotNull();
foundit = true;

View File

@@ -30,7 +30,8 @@ public class TestCallbackHandler implements JaasAuthenticationCallbackHandler {
@Override
public void handle(Callback callback, Authentication auth) {
if (callback instanceof TextInputCallback tic) {
if (callback instanceof TextInputCallback) {
TextInputCallback tic = (TextInputCallback) callback;
tic.setText(auth.getPrincipal().toString());
}
}

View File

@@ -89,7 +89,7 @@ public class InMemoryConfigurationTests {
public void mappedNonnullDefault() {
InMemoryConfiguration configuration = new InMemoryConfiguration(this.mappedEntries, this.defaultEntries);
assertThat(this.defaultEntries).isEqualTo(configuration.getAppConfigurationEntry("missing"));
assertThat(this.mappedEntries).containsEntry("name", configuration.getAppConfigurationEntry("name"));
assertThat(this.mappedEntries.get("name")).isEqualTo(configuration.getAppConfigurationEntry("name"));
}
@Test

View File

@@ -1,87 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authorization;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.hierarchicalroles.NullRoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link AuthoritiesAuthorizationManager}.
*
* @author Evgeniy Cheban
*/
class AuthoritiesAuthorizationManagerTests {
@Test
void setRoleHierarchyWhenNullThenIllegalArgumentException() {
AuthoritiesAuthorizationManager manager = new AuthoritiesAuthorizationManager();
assertThatIllegalArgumentException().isThrownBy(() -> manager.setRoleHierarchy(null))
.withMessage("roleHierarchy cannot be null");
}
@Test
void setRoleHierarchyWhenNotNullThenVerifyRoleHierarchy() {
AuthoritiesAuthorizationManager manager = new AuthoritiesAuthorizationManager();
RoleHierarchy roleHierarchy = new RoleHierarchyImpl();
manager.setRoleHierarchy(roleHierarchy);
assertThat(manager).extracting("roleHierarchy").isEqualTo(roleHierarchy);
}
@Test
void getRoleHierarchyWhenNotSetThenDefaultsToNullRoleHierarchy() {
AuthoritiesAuthorizationManager manager = new AuthoritiesAuthorizationManager();
assertThat(manager).extracting("roleHierarchy").isInstanceOf(NullRoleHierarchy.class);
}
@Test
void checkWhenUserHasAnyAuthorityThenGrantedDecision() {
AuthoritiesAuthorizationManager manager = new AuthoritiesAuthorizationManager();
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "USER");
assertThat(manager.check(authentication, Arrays.asList("ADMIN", "USER")).isGranted()).isTrue();
}
@Test
void checkWhenUserHasNotAnyAuthorityThenDeniedDecision() {
AuthoritiesAuthorizationManager manager = new AuthoritiesAuthorizationManager();
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ANONYMOUS");
assertThat(manager.check(authentication, Arrays.asList("ADMIN", "USER")).isGranted()).isFalse();
}
@Test
void checkWhenRoleHierarchySetThenGreaterRoleTakesPrecedence() {
AuthoritiesAuthorizationManager manager = new AuthoritiesAuthorizationManager();
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
manager.setRoleHierarchy(roleHierarchy);
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password",
"ROLE_ADMIN");
assertThat(manager.check(authentication, Collections.singleton("ROLE_USER")).isGranted()).isTrue();
}
}

View File

@@ -245,13 +245,13 @@ public class AuthorityAuthorizationManagerTests {
AuthorityAuthorizationManager<Object> manager = AuthorityAuthorizationManager.hasRole("USER");
RoleHierarchy roleHierarchy = new RoleHierarchyImpl();
manager.setRoleHierarchy(roleHierarchy);
assertThat(manager).extracting("delegate").extracting("roleHierarchy").isEqualTo(roleHierarchy);
assertThat(manager).extracting("roleHierarchy").isEqualTo(roleHierarchy);
}
@Test
public void getRoleHierarchyWhenNotSetThenDefaultsToNullRoleHierarchy() {
AuthorityAuthorizationManager<Object> manager = AuthorityAuthorizationManager.hasRole("USER");
assertThat(manager).extracting("delegate").extracting("roleHierarchy").isInstanceOf(NullRoleHierarchy.class);
assertThat(manager).extracting("roleHierarchy").isInstanceOf(NullRoleHierarchy.class);
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.security.authorization;
import java.util.Optional;
import java.util.function.Supplier;
import io.micrometer.observation.Observation;
@@ -26,7 +25,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.context.MessageSource;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
@@ -34,7 +32,6 @@ import org.springframework.security.core.Authentication;
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.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -88,20 +85,14 @@ public class ObservationAuthorizationManagerTests {
@Test
void verifyWhenErrorsThenObserves() {
MessageSource source = mock(MessageSource.class);
this.tested.setMessageSource(source);
given(this.handler.supportsContext(any())).willReturn(true);
given(this.authorizationManager.check(any(), any())).willReturn(this.deny);
given(source.getMessage(eq("AbstractAccessDecisionManager.accessDenied"), any(), any(), any()))
.willReturn("accessDenied");
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.tested.verify(this.token, this.object));
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(this.handler).onStart(captor.capture());
assertThat(captor.getValue().getName()).isEqualTo(AuthorizationObservationConvention.OBSERVATION_NAME);
assertThat(captor.getValue().getError()).isInstanceOf(AccessDeniedException.class);
assertThat(Optional.ofNullable(captor.getValue().getError()).map(Throwable::getMessage).orElse(""))
.isEqualTo("accessDenied");
assertThat(captor.getValue()).isInstanceOf(AuthorizationObservationContext.class);
AuthorizationObservationContext<?> context = (AuthorizationObservationContext<?>) captor.getValue();
assertThat(context.getAuthentication()).isNull();
@@ -127,10 +118,4 @@ public class ObservationAuthorizationManagerTests {
assertThat(context.getDecision()).isEqualTo(this.grant);
}
@Test
void setObservationConventionWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tested.setObservationConvention(null));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -117,10 +117,4 @@ public class ObservationReactiveAuthorizationManagerTests {
assertThat(context.getDecision()).isEqualTo(this.grant);
}
@Test
void setObservationConventionWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tested.setObservationConvention(null));
}
}

View File

@@ -38,7 +38,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
*/
public class SpringAuthorizationEventPublisherTests {
Supplier<Authentication> authentication = TestAuthentication::authenticatedUser;
Supplier<Authentication> authentication = () -> TestAuthentication.authenticatedUser();
ApplicationEventPublisher applicationEventPublisher;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* 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.
@@ -18,8 +18,6 @@ package org.springframework.security.authorization.method;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.annotation.security.DenyAll;
@@ -32,14 +30,11 @@ import org.springframework.security.access.intercept.method.MockMethodInvocation
import org.springframework.security.authentication.TestAuthentication;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link Jsr250AuthorizationManager}.
@@ -68,27 +63,6 @@ public class Jsr250AuthorizationManagerTests {
assertThat(manager).extracting("rolePrefix").isEqualTo("CUSTOM_");
}
@Test
public void setAuthoritiesAuthorizationManagerWhenNullThenException() {
Jsr250AuthorizationManager manager = new Jsr250AuthorizationManager();
assertThatIllegalArgumentException().isThrownBy(() -> manager.setAuthoritiesAuthorizationManager(null))
.withMessage("authoritiesAuthorizationManager cannot be null");
}
@Test
public void setAuthoritiesAuthorizationManagerWhenNotNullThenVerifyUsage() throws Exception {
AuthorizationManager<Collection<String>> authoritiesAuthorizationManager = mock(AuthorizationManager.class);
Jsr250AuthorizationManager manager = new Jsr250AuthorizationManager();
manager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new ClassLevelAnnotations(),
ClassLevelAnnotations.class, "rolesAllowedAdmin");
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password",
"ROLE_ADMIN");
AuthorizationDecision decision = manager.check(authentication, methodInvocation);
assertThat(decision).isNull();
verify(authoritiesAuthorizationManager).check(authentication, Set.of("ROLE_ADMIN"));
}
@Test
public void checkDoSomethingWhenNoJsr250AnnotationsThenNullDecision() throws Exception {
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
@@ -149,7 +123,7 @@ public class Jsr250AuthorizationManagerTests {
}
@Test
public void checkMultipleMethodAnnotationsWhenInvokedThenAnnotationConfigurationException() throws Exception {
public void checkMultipleAnnotationsWhenInvokedThenAnnotationConfigurationException() throws Exception {
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password",
"ROLE_ANONYMOUS");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
@@ -159,16 +133,6 @@ public class Jsr250AuthorizationManagerTests {
.isThrownBy(() -> manager.check(authentication, methodInvocation));
}
@Test
public void checkMultipleClassAnnotationsWhenInvokedThenAnnotationConfigurationException() throws Exception {
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new ClassLevelIllegalAnnotations(),
ClassLevelIllegalAnnotations.class, "inheritedAnnotations");
Jsr250AuthorizationManager manager = new Jsr250AuthorizationManager();
assertThatExceptionOfType(AnnotationConfigurationException.class)
.isThrownBy(() -> manager.check(authentication, methodInvocation));
}
@Test
public void checkRequiresAdminWhenClassAnnotationsThenMethodAnnotationsTakePrecedence() throws Exception {
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER");
@@ -283,15 +247,6 @@ public class Jsr250AuthorizationManagerTests {
}
@MyIllegalRolesAllowed
public static class ClassLevelIllegalAnnotations {
public void inheritedAnnotations() {
}
}
public interface InterfaceAnnotationsOne {
@RolesAllowed("ADMIN")
@@ -319,11 +274,4 @@ public class Jsr250AuthorizationManagerTests {
}
@DenyAll
@RolesAllowed("USER")
@Retention(RetentionPolicy.RUNTIME)
public @interface MyIllegalRolesAllowed {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* 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.
@@ -18,8 +18,6 @@ package org.springframework.security.authorization.method;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Set;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
@@ -31,14 +29,10 @@ import org.springframework.security.access.intercept.method.MockMethodInvocation
import org.springframework.security.authentication.TestAuthentication;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link SecuredAuthorizationManager}.
@@ -47,26 +41,6 @@ import static org.mockito.Mockito.verify;
*/
public class SecuredAuthorizationManagerTests {
@Test
public void setAuthoritiesAuthorizationManagerWhenNullThenException() {
SecuredAuthorizationManager manager = new SecuredAuthorizationManager();
assertThatIllegalArgumentException().isThrownBy(() -> manager.setAuthoritiesAuthorizationManager(null))
.withMessage("authoritiesAuthorizationManager cannot be null");
}
@Test
public void setAuthoritiesAuthorizationManagerWhenNotNullThenVerifyUsage() throws Exception {
AuthorizationManager<Collection<String>> authoritiesAuthorizationManager = mock(AuthorizationManager.class);
SecuredAuthorizationManager manager = new SecuredAuthorizationManager();
manager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"securedUserOrAdmin");
Supplier<Authentication> authentication = TestAuthentication::authenticatedUser;
AuthorizationDecision decision = manager.check(authentication, methodInvocation);
assertThat(decision).isNull();
verify(authoritiesAuthorizationManager).check(authentication, Set.of("ROLE_USER", "ROLE_ADMIN"));
}
@Test
public void checkDoSomethingWhenNoSecuredAnnotationThenNullDecision() throws Exception {
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,

View File

@@ -1,75 +0,0 @@
/*
* Copyright 2020-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.concurrent;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.security.DelegatingSecurityContextTestUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Steve Riesenberg
*/
public class DelegatingSecurityContextExecutorIntegrationTests {
@Test
public void executeWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createExecutor,
Executor::execute
);
// @formatter:on
}
private DelegatingSecurityContextExecutor createExecutor(ScheduledExecutorService delegate) {
return new DelegatingSecurityContextExecutor(delegate, securityContext());
}
private static SecurityContext securityContext() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
return securityContext;
}
}

View File

@@ -1,98 +0,0 @@
/*
* Copyright 2020-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.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.security.DelegatingSecurityContextTestUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Steve Riesenberg
*/
public class DelegatingSecurityContextExecutorServiceIntegrationTests {
@Test
public void executeWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createExecutor,
ExecutorService::execute
);
// @formatter:on
}
@Test
public void submitWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void submitWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext submitAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.callAndReturn(
threadFactory,
this::createExecutor,
ExecutorService::submit
);
// @formatter:on
}
private DelegatingSecurityContextExecutorService createExecutor(ScheduledExecutorService delegate) {
return new DelegatingSecurityContextExecutorService(delegate, securityContext());
}
private static SecurityContext securityContext() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
return securityContext;
}
}

View File

@@ -1,121 +0,0 @@
/*
* Copyright 2020-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.concurrent;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.security.DelegatingSecurityContextTestUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Steve Riesenberg
*/
public class DelegatingSecurityContextScheduledExecutorServiceIntegrationTests {
@Test
public void executeWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createExecutor,
ScheduledExecutorService::execute
);
// @formatter:on
}
@Test
public void submitWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void submitWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext submitAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.callAndReturn(
threadFactory,
this::createExecutor,
ScheduledExecutorService::submit
);
// @formatter:on
}
@Test
public void scheduleWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void scheduleWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext scheduleAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.callAndReturn(
threadFactory,
this::createExecutor,
(executor, task) -> executor.schedule(task, 50, TimeUnit.MILLISECONDS)
);
// @formatter:on
}
private DelegatingSecurityContextScheduledExecutorService createExecutor(ScheduledExecutorService delegate) {
return new DelegatingSecurityContextScheduledExecutorService(delegate, securityContext());
}
private static SecurityContext securityContext() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
return securityContext;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* 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.
@@ -32,11 +32,11 @@ public class JavaVersionTests {
private static final int JDK17_CLASS_VERSION = 61;
@Test
public void authenticationWhenJdk17ThenCorrectJdkCompatibility() throws Exception {
assertClassVersion(Authentication.class, JDK17_CLASS_VERSION);
public void authenticationCorrectJdkCompatibility() throws Exception {
assertClassVersion(Authentication.class);
}
private void assertClassVersion(Class<?> clazz, int classVersion) throws Exception {
private void assertClassVersion(Class<?> clazz) throws Exception {
String classResourceName = clazz.getName().replaceAll("\\.", "/") + ".class";
try (InputStream input = Thread.currentThread()
.getContextClassLoader()
@@ -45,7 +45,7 @@ public class JavaVersionTests {
data.readInt();
data.readShort(); // minor
int major = data.readShort();
assertThat(major).isEqualTo(classVersion);
assertThat(major).isEqualTo(JDK17_CLASS_VERSION);
}
}

View File

@@ -68,7 +68,13 @@ final class StaticFinalReflectionUtils {
field.set(null, newValue);
}
}
catch (SecurityException | IllegalAccessException | IllegalArgumentException ex) {
catch (SecurityException ex) {
throw new RuntimeException(ex);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.security.core.authority;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
@@ -28,7 +27,6 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Luke Taylor
* @author Evgeniy Cheban
*/
public class AuthorityUtilsTests {
@@ -37,21 +35,11 @@ public class AuthorityUtilsTests {
List<GrantedAuthority> authorityArray = AuthorityUtils
.commaSeparatedStringToAuthorityList(" ROLE_A, B, C, ROLE_D\n,\n E ");
Set<String> authorities = AuthorityUtils.authorityListToSet(authorityArray);
assertThat(authorities).contains("B");
assertThat(authorities).contains("C");
assertThat(authorities).contains("E");
assertThat(authorities).contains("ROLE_A");
assertThat(authorities).contains("ROLE_D");
}
@Test
public void createAuthorityList() {
List<GrantedAuthority> authorities = AuthorityUtils
.createAuthorityList(Arrays.asList("ROLE_A", "ROLE_B", "ROLE_C"));
assertThat(authorities).hasSize(3);
assertThat(authorities).element(0).extracting(GrantedAuthority::getAuthority).isEqualTo("ROLE_A");
assertThat(authorities).element(1).extracting(GrantedAuthority::getAuthority).isEqualTo("ROLE_B");
assertThat(authorities).element(2).extracting(GrantedAuthority::getAuthority).isEqualTo("ROLE_C");
assertThat(authorities.contains("B")).isTrue();
assertThat(authorities.contains("C")).isTrue();
assertThat(authorities.contains("E")).isTrue();
assertThat(authorities.contains("ROLE_A")).isTrue();
assertThat(authorities.contains("ROLE_D")).isTrue();
}
}

View File

@@ -45,8 +45,8 @@ public class SimpleAuthoritiesMapperTests {
SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
Set<String> mapped = AuthorityUtils
.authorityListToSet(mapper.mapAuthorities(AuthorityUtils.createAuthorityList("AaA", "ROLE_bbb")));
assertThat(mapped).contains("ROLE_AaA");
assertThat(mapped).contains("ROLE_bbb");
assertThat(mapped.contains("ROLE_AaA")).isTrue();
assertThat(mapped.contains("ROLE_bbb")).isTrue();
}
@Test
@@ -56,19 +56,19 @@ public class SimpleAuthoritiesMapperTests {
List<GrantedAuthority> toMap = AuthorityUtils.createAuthorityList("AaA", "Bbb");
Set<String> mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
assertThat(mapped).hasSize(2);
assertThat(mapped).contains("AaA");
assertThat(mapped).contains("Bbb");
assertThat(mapped.contains("AaA")).isTrue();
assertThat(mapped.contains("Bbb")).isTrue();
mapper.setConvertToLowerCase(true);
mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
assertThat(mapped).hasSize(2);
assertThat(mapped).contains("aaa");
assertThat(mapped).contains("bbb");
assertThat(mapped.contains("aaa")).isTrue();
assertThat(mapped.contains("bbb")).isTrue();
mapper.setConvertToLowerCase(false);
mapper.setConvertToUpperCase(true);
mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
assertThat(mapped).hasSize(2);
assertThat(mapped).contains("AAA");
assertThat(mapped).contains("BBB");
assertThat(mapped.contains("AAA")).isTrue();
assertThat(mapped.contains("BBB")).isTrue();
}
@Test
@@ -86,7 +86,7 @@ public class SimpleAuthoritiesMapperTests {
mapper.setDefaultAuthority("ROLE_USER");
Set<String> mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(AuthorityUtils.NO_AUTHORITIES));
assertThat(mapped).hasSize(1);
assertThat(mapped).contains("ROLE_USER");
assertThat(mapped.contains("ROLE_USER")).isTrue();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,17 +16,10 @@
package org.springframework.security.core.context;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
@@ -106,53 +99,4 @@ public class ReactiveSecurityContextHolderTests {
// @formatter:on
}
@Test
public void getContextWhenThreadFactoryIsPlatformThenPropagated() {
verifySecurityContextIsPropagated(Executors.defaultThreadFactory());
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void getContextWhenThreadFactoryIsVirtualThenPropagated() {
verifySecurityContextIsPropagated(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
}
private static void verifySecurityContextIsPropagated(ThreadFactory threadFactory) {
Authentication authentication = new TestingAuthenticationToken("user", null);
// @formatter:off
Mono<Authentication> publisher = ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.contextWrite((context) -> ReactiveSecurityContextHolder.withAuthentication(authentication))
.subscribeOn(Schedulers.newSingle(threadFactory));
// @formatter:on
StepVerifier.create(publisher).expectNext(authentication).verifyComplete();
}
@Test
public void clearContextWhenThreadFactoryIsPlatformThenCleared() {
verifySecurityContextIsCleared(Executors.defaultThreadFactory());
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void clearContextWhenThreadFactoryIsVirtualThenCleared() {
verifySecurityContextIsCleared(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
}
private static void verifySecurityContextIsCleared(ThreadFactory threadFactory) {
Authentication authentication = new TestingAuthenticationToken("user", null);
// @formatter:off
Mono<Authentication> publisher = ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.contextWrite(ReactiveSecurityContextHolder.clearContext())
.contextWrite((context) -> ReactiveSecurityContextHolder.withAuthentication(authentication))
.subscribeOn(Schedulers.newSingle(threadFactory));
// @formatter:on
StepVerifier.create(publisher).verifyComplete();
}
}

View File

@@ -57,7 +57,7 @@ class ThreadLocalSecurityContextHolderStrategyTests {
void deferredContextValidates() {
this.strategy.setDeferredContext(() -> null);
Supplier<SecurityContext> deferredContext = this.strategy.getDeferredContext();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(deferredContext::get);
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> deferredContext.get());
}
@Test

View File

@@ -24,8 +24,8 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
@@ -60,11 +60,11 @@ public class DefaultSecurityParameterNameDiscovererTests {
@Test
public void constructorDiscoverers() {
this.discoverer = new DefaultSecurityParameterNameDiscoverer(
Arrays.asList(new StandardReflectionParameterNameDiscoverer()));
Arrays.asList(new LocalVariableTableParameterNameDiscoverer()));
List<ParameterNameDiscoverer> discoverers = (List<ParameterNameDiscoverer>) ReflectionTestUtils
.getField(this.discoverer, "parameterNameDiscoverers");
assertThat(discoverers).hasSize(3);
assertThat(discoverers.get(0)).isInstanceOf(StandardReflectionParameterNameDiscoverer.class);
assertThat(discoverers.get(0)).isInstanceOf(LocalVariableTableParameterNameDiscoverer.class);
ParameterNameDiscoverer annotationDisc = discoverers.get(1);
assertThat(annotationDisc).isInstanceOf(AnnotationParameterNameDiscoverer.class);
Set<String> annotationsToUse = (Set<String>) ReflectionTestUtils.getField(annotationDisc,

View File

@@ -97,8 +97,8 @@ public class SessionRegistryImplTests {
this.sessionRegistry.registerNewSession(sessionId2, principal1);
this.sessionRegistry.registerNewSession(sessionId3, principal2);
assertThat(this.sessionRegistry.getAllPrincipals()).hasSize(2);
assertThat(this.sessionRegistry.getAllPrincipals()).contains(principal1);
assertThat(this.sessionRegistry.getAllPrincipals()).contains(principal2);
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal1)).isTrue();
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal2)).isTrue();
}
@Test

View File

@@ -18,17 +18,12 @@ package org.springframework.security.core.userdetails;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
@@ -42,7 +37,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* Tests {@link User}.
*
* @author Ben Alex
* @author Ilya Starchenko
*/
public class UserTests {
@@ -74,70 +68,6 @@ public class UserTests {
.isThrownBy(() -> User.class.getDeclaredConstructor((Class[]) null));
}
@Test
public void testBuildUserWithNoAuthorities() {
UserDetails user = User.builder().username("user").password("password").build();
assertThat(user.getAuthorities()).isEmpty();
}
@Test
public void testNullWithinUserAuthoritiesIsRejected() {
assertThatIllegalArgumentException().isThrownBy(() -> User.builder()
.username("user")
.password("password")
.authorities((Collection<? extends GrantedAuthority>) null)
.build());
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(null);
authorities.add(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> User.builder().username("user").password("password").authorities(authorities).build());
assertThatIllegalArgumentException().isThrownBy(() -> User.builder()
.username("user")
.password("password")
.authorities((GrantedAuthority[]) null)
.build());
assertThatIllegalArgumentException().isThrownBy(() -> User.builder()
.username("user")
.password("password")
.authorities(new GrantedAuthority[] { null, null })
.build());
assertThatIllegalArgumentException().isThrownBy(
() -> User.builder().username("user").password("password").authorities((String[]) null).build());
assertThatIllegalArgumentException().isThrownBy(() -> User.builder()
.username("user")
.password("password")
.authorities(new String[] { null, null })
.build());
}
// gh-12533
@ParameterizedTest
@NullSource
@ValueSource(strings = { "ROLE_USER,ROLE_ADMIN,read", "read" })
public void withUserDetailsWhenAuthoritiesThenOverridesPreviousAuthorities(String arg) {
// @formatter:off
UserDetails parent = User.builder()
.username("user")
.password("password")
.authorities("one", "two", "three")
.build();
// @formatter:on
String[] authorities = (arg != null) ? arg.split(",") : new String[0];
User.UserBuilder builder = User.withUserDetails(parent);
UserDetails user = builder.build();
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).containsOnly("one", "two", "three");
user = builder.authorities(authorities).build();
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).containsOnly(authorities);
user = builder.authorities(AuthorityUtils.createAuthorityList(authorities)).build();
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).containsOnly(authorities);
user = builder.authorities(AuthorityUtils.createAuthorityList(authorities).toArray(GrantedAuthority[]::new))
.build();
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).containsOnly(authorities);
}
@Test
public void testNullValuesRejected() {
assertThatIllegalArgumentException().isThrownBy(() -> new User(null, "koala", true, true, true, true, ROLE_12));

View File

@@ -145,7 +145,7 @@ public class JdbcUserDetailsManagerTests {
AuthorityUtils.createAuthorityList("A", "B"));
this.manager.createUser(user);
UserDetails user2 = this.manager.loadUserByUsername(user.getUsername());
assertThat(user2).usingRecursiveComparison().isEqualTo(user);
assertThat(user2).isEqualToComparingFieldByField(user);
}
@Test
@@ -176,7 +176,7 @@ public class JdbcUserDetailsManagerTests {
AuthorityUtils.createAuthorityList("D", "F", "E"));
this.manager.updateUser(newJoe);
UserDetails joe = this.manager.loadUserByUsername(newJoe.getUsername());
assertThat(joe).usingRecursiveComparison().isEqualTo(newJoe);
assertThat(joe).isEqualToComparingFieldByField(newJoe);
assertThat(this.cache.getUserMap().containsKey(newJoe.getUsername())).isFalse();
}
@@ -189,7 +189,7 @@ public class JdbcUserDetailsManagerTests {
public void userExistsReturnsTrueForExistingUsername() {
insertJoe();
assertThat(this.manager.userExists("joe")).isTrue();
assertThat(this.cache.getUserMap()).containsKey("joe");
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue();
}
@Test
@@ -251,7 +251,7 @@ public class JdbcUserDetailsManagerTests {
UserDetails newJoe = this.manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("password");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("password");
assertThat(this.cache.getUserMap()).containsKey("joe");
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue();
}
@Test

View File

@@ -1,148 +0,0 @@
/*
* Copyright 2020-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.scheduling;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.scheduling.SchedulingTaskExecutor;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.security.DelegatingSecurityContextTestUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Steve Riesenberg
*/
public class DelegatingSecurityContextSchedulingTaskExecutorIntegrationTests {
@Test
public void executeWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createExecutor,
SchedulingTaskExecutor::execute
);
// @formatter:on
}
@Test
public void executeCompletableWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeCompletableAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeCompletableWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeCompletableAndReturn(
new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeCompletableAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createExecutor,
SchedulingTaskExecutor::submitCompletable
);
// @formatter:on
}
@Test
public void submitWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void submitWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext submitAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.callAndReturn(
threadFactory,
this::createExecutor,
SchedulingTaskExecutor::submit
);
// @formatter:on
}
@Test
public void submitCompletableWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitCompletableAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void submitCompletableWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitCompletableAndReturn(
new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext submitCompletableAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.callAndReturn(
threadFactory,
this::createExecutor,
SchedulingTaskExecutor::submitCompletable
);
// @formatter:on
}
private DelegatingSecurityContextSchedulingTaskExecutor createExecutor(ScheduledExecutorService delegate) {
return new DelegatingSecurityContextSchedulingTaskExecutor(new ConcurrentTaskExecutor(delegate),
securityContext());
}
private static SecurityContext securityContext() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
return securityContext;
}
}

View File

@@ -1,125 +0,0 @@
/*
* Copyright 2020-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.scheduling;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.security.DelegatingSecurityContextTestUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Steve Riesenberg
*/
public class DelegatingSecurityContextTaskSchedulerIntegrationTests {
@Test
public void scheduleWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void scheduleWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext scheduleAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createTaskScheduler,
(taskScheduler, task) -> taskScheduler.schedule(task, new PeriodicTrigger(Duration.ofMillis(50)))
);
// @formatter:on
}
@Test
public void scheduleAtFixedRateWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleAtFixedRateAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void scheduleAtFixedRateWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleAtFixedRateAndReturn(
new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext scheduleAtFixedRateAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createTaskScheduler,
(taskScheduler, task) -> taskScheduler.scheduleAtFixedRate(task, Duration.ofMillis(50))
);
// @formatter:on
}
@Test
public void scheduleWithFixedDelayWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleWithFixedDelayAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void scheduleWithFixedDelayWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = scheduleWithFixedDelayAndReturn(
new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext scheduleWithFixedDelayAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(
threadFactory,
this::createTaskScheduler,
(taskScheduler, task) -> taskScheduler.scheduleWithFixedDelay(task, Duration.ofMillis(50))
);
// @formatter:on
}
private DelegatingSecurityContextTaskScheduler createTaskScheduler(ScheduledExecutorService delegate) {
return new DelegatingSecurityContextTaskScheduler(new ConcurrentTaskScheduler(delegate), securityContext());
}
private static SecurityContext securityContext() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
return securityContext;
}
}

View File

@@ -1,143 +0,0 @@
/*
* Copyright 2020-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.task;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.security.DelegatingSecurityContextTestUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Steve Riesenberg
*/
public class DelegatingSecurityContextAsyncTaskExecutorIntegrationTests {
@Test
public void executeWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(threadFactory,
this::createExecutor,
AsyncTaskExecutor::execute
);
// @formatter:on
}
@Test
public void executeCompletableWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeCompletableAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeCompletableWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeCompletableAndReturn(
new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeCompletableAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(threadFactory,
this::createExecutor,
AsyncTaskExecutor::submitCompletable
);
// @formatter:on
}
@Test
public void submitWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void submitWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext submitAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.callAndReturn(threadFactory,
this::createExecutor,
AsyncTaskExecutor::submit
);
// @formatter:on
}
@Test
public void submitCompletableWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitCompletableAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void submitCompletableWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = submitCompletableAndReturn(
new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext submitCompletableAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.callAndReturn(threadFactory,
this::createExecutor,
AsyncTaskExecutor::submitCompletable
);
// @formatter:on
}
private DelegatingSecurityContextAsyncTaskExecutor createExecutor(ScheduledExecutorService delegate) {
return new DelegatingSecurityContextAsyncTaskExecutor(new TaskExecutorAdapter(delegate), securityContext());
}
private static SecurityContext securityContext() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
return securityContext;
}
}

View File

@@ -1,75 +0,0 @@
/*
* Copyright 2020-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.task;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.core.task.TaskExecutor;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.security.DelegatingSecurityContextTestUtils;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Steve Riesenberg
*/
public class DelegatingSecurityContextTaskExecutorIntegrationTests {
@Test
public void executeWhenThreadFactoryIsPlatformThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(Executors.defaultThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
@Test
@DisabledOnJre(JRE.JAVA_17)
public void executeWhenThreadFactoryIsVirtualThenSecurityContextPropagated() throws Exception {
SecurityContext securityContext = executeAndReturn(new VirtualThreadTaskExecutor().getVirtualThreadFactory());
assertThat(securityContext.getAuthentication()).isNotNull();
}
private SecurityContext executeAndReturn(ThreadFactory threadFactory) throws Exception {
// @formatter:off
return DelegatingSecurityContextTestUtils.runAndReturn(threadFactory,
this::createExecutor,
TaskExecutor::execute
);
// @formatter:on
}
private DelegatingSecurityContextTaskExecutor createExecutor(ScheduledExecutorService delegate) {
return new DelegatingSecurityContextTaskExecutor(new TaskExecutorAdapter(delegate), securityContext());
}
private static SecurityContext securityContext() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
return securityContext;
}
}