INT-2166: Add SecurityContext Propagation

JIRA: https://jira.spring.io/browse/INT-2166

* Introduce `ThreadStatePropagationChannelInterceptor` based on the `ExecutorChannelInterceptor`
* Add `SecurityContextPropagationChannelInterceptor`,`SecurityContextCleanupChannelInterceptor`
* Introduce `AbstractExecutorChannel` to utilize `ExecutorChannelInterceptor` logic
* Introduce `MessageHandlingTaskDecorator` to avoid package tangle from `dispatcher` and `channel`
* Introduce `SecurityContextCleanupAdvice` for those cases when we don't get deal with `MessageChannel`s already, but want to have proper way to cleanup `SecurityContext`
* Make `GlobalChannelInterceptorProcessor` as `SmartInitializingSingleton` to avoid `phase` conflicts.
* Fix `MessagingAnnotationPostProcessor` to use `beanFactory.initializeBean(endpoint, endpointBeanName);` instead of manual `start()` invocation bypassing the `phase` logic, hence having a bug, when endpoints have been started very early
* Optimise `AbstractPollableChannel` to use `size` field from `ChannelInterceptorList` instead of `size()` from `Collection<?>`
* Fix `AnnotatedEndpointActivationTests` extracting separate component for annotation configuration instead of using test class directly. This caused very late Messaging Annotations process on that class
* Fix typo in the `spring-integration-jdbc-4.2.xsd`
* Remove some `SOUT`s throughout the project

TODO Docs

PR Comments:

* Remove redundant `AbstractExecutorChannel#executorInterceptors` and make logic based on the `super.interceptors`
 * Fix wrong imports order
 * JavaDocs for `ThreadStatePropagationChannelInterceptor`
 * Docs for `SecurityContext` propagation

INT-3593: Fix FTP PartialSuccess Tests

JIRA: https://jira.spring.io/browse/INT-3593

Sort the files for the MPUT tests.

INT-2166: Add SecurityContext Propagation

JIRA: https://jira.spring.io/browse/INT-2166

* Introduce `ThreadStatePropagationChannelInterceptor` based on the `ExecutorChannelInterceptor`
* Add `SecurityContextPropagationChannelInterceptor`,`SecurityContextCleanupChannelInterceptor`
* Introduce `AbstractExecutorChannel` to utilize `ExecutorChannelInterceptor` logic
* Introduce `MessageHandlingTaskDecorator` to avoid package tangle from `dispatcher` and `channel`
* Introduce `SecurityContextCleanupAdvice` for those cases when we don't get deal with `MessageChannel`s already, but want to have proper way to cleanup `SecurityContext`
* Make `GlobalChannelInterceptorProcessor` as `SmartInitializingSingleton` to avoid `phase` conflicts.
* Fix `MessagingAnnotationPostProcessor` to use `beanFactory.initializeBean(endpoint, endpointBeanName);` instead of manual `start()` invocation bypassing the `phase` logic, hence having a bug, when endpoints have been started very early
* Optimise `AbstractPollableChannel` to use `size` field from `ChannelInterceptorList` instead of `size()` from `Collection<?>`
* Fix `AnnotatedEndpointActivationTests` extracting separate component for annotation configuration instead of using test class directly. This caused very late Messaging Annotations process on that class
* Fix typo in the `spring-integration-jdbc-4.2.xsd`
* Remove some `SOUT`s throughout the project

TODO Docs

PR Comments:

* Remove redundant `AbstractExecutorChannel#executorInterceptors` and make logic based on the `super.interceptors`
 * Fix wrong imports order
 * JavaDocs for `ThreadStatePropagationChannelInterceptor`
 * Docs for `SecurityContext` propagation

Doc Polishing

Address PR comments

Address PR comments

* Extract `ExecutorChannelInterceptor` logic in the `PollingConsumer`
to have an ability to invoke `afterMessageHandled()` on the TaskScheduler's Thread
for example for the `SecurityContext` clean up
* Get rid of all that redundant "clean up" stuff
* Docs polishing

Fix `NPE` in the `PollingConsumer`

Introduce `ExecutorChannelInterceptorAware` to avoid iterators on each message

Polishing; Docs, Sonar
This commit is contained in:
Artem Bilan
2015-07-05 12:58:33 -04:00
committed by Gary Russell
parent fd35d43aba
commit 09fb4f78c9
37 changed files with 1459 additions and 288 deletions

View File

@@ -23,7 +23,7 @@ import org.springframework.security.access.ConfigAttribute;
/**
* Interface to encapsulate {@link ConfigAttribute}s for secured channel
* send and receive operations.
*
*
* @author Oleg Zhurakousky
* @since 2.0
*/

View File

@@ -20,6 +20,7 @@ import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;

View File

@@ -0,0 +1,95 @@
/*
* Copyright 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
*
* http://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.integration.security.channel;
import org.springframework.aop.support.AopUtils;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.interceptor.ThreadStatePropagationChannelInterceptor;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.support.ExecutorChannelInterceptor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* The {@link ExecutorChannelInterceptor} implementation responsible for
* the {@link SecurityContext} propagation from one message flow's thread to another
* through the {@link MessageChannel}s involved in the flow.
* <p>
* In addition this interceptor cleans up (restores) the {@link SecurityContext}
* in the containers Threads for channels like
* {@link org.springframework.integration.channel.ExecutorChannel}
* and {@link org.springframework.integration.channel.QueueChannel}.
*
* @author Artem Bilan
* @see ThreadStatePropagationChannelInterceptor
* @since 4.2
*/
public class SecurityContextPropagationChannelInterceptor
extends ThreadStatePropagationChannelInterceptor<Authentication> {
private final static SecurityContext EMPTY_CONTEXT = SecurityContextHolder.createEmptyContext();
private static final ThreadLocal<SecurityContext> ORIGINAL_CONTEXT = new ThreadLocal<SecurityContext>();
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
cleanup();
}
@Override
protected Authentication obtainPropagatingContext(Message<?> message, MessageChannel channel) {
if (!DirectChannel.class.isAssignableFrom(AopUtils.getTargetClass(channel))) {
return SecurityContextHolder.getContext().getAuthentication();
}
return null;
}
@Override
protected void populatePropagatedContext(Authentication authentication, Message<?> message,
MessageChannel channel) {
if (authentication != null) {
SecurityContext currentContext = SecurityContextHolder.getContext();
ORIGINAL_CONTEXT.set(currentContext);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
}
}
public static void cleanup() {
SecurityContext originalContext = ORIGINAL_CONTEXT.get();
try {
if (originalContext == null || EMPTY_CONTEXT.equals(originalContext)) {
SecurityContextHolder.clearContext();
ORIGINAL_CONTEXT.remove();
}
else {
SecurityContextHolder.setContext(originalContext);
}
}
catch (Throwable t) {
SecurityContextHolder.clearContext();
}
}
}

View File

@@ -1,14 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:si-security="http://www.springframework.org/schema/integration/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
xmlns:si-security="http://www.springframework.org/schema/integration/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/security
http://www.springframework.org/schema/integration/security/spring-integration-security.xsd">
http://www.springframework.org/schema/integration/security/spring-integration-security.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<beans:import resource="classpath:org/springframework/integration/security/config/commonSecurityConfiguration.xml"/>
@@ -24,4 +26,27 @@
<outbound-channel-adapter id="unsecuredChannelAdapter" ref="testHandler"/>
<channel id="queueChannel">
<queue/>
<interceptors>
<beans:bean
class="org.springframework.integration.security.channel.SecurityContextPropagationChannelInterceptor"/>
</interceptors>
</channel>
<!--The single taskScheduler Thread is need to check that SecurityContext cleanup works well-->
<task:scheduler id="taskScheduler"/>
<bridge input-channel="queueChannel" output-channel="securedChannelQueue">
<poller fixed-delay="100"/>
</bridge>
<channel id="securedChannelQueue">
<queue/>
</channel>
<channel id="errorChannel">
<queue/>
</channel>
</beans:beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* 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.
@@ -16,24 +16,32 @@
package org.springframework.integration.security.channel;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.security.TestHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.integration.security.SecurityTestUtils;
import org.springframework.integration.security.TestHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Mark Fisher
@@ -41,7 +49,9 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
* @author Artem Bilan
*/
@ContextConfiguration
public class ChannelAdapterSecurityIntegrationTests extends AbstractJUnit4SpringContextTests {
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class ChannelAdapterSecurityIntegrationTests {
@Autowired
@Qualifier("securedChannelAdapter")
@@ -55,6 +65,18 @@ public class ChannelAdapterSecurityIntegrationTests extends AbstractJUnit4Spring
@Qualifier("unsecuredChannelAdapter")
MessageChannel unsecuredChannelAdapter;
@Autowired
@Qualifier("queueChannel")
MessageChannel queueChannel;
@Autowired
@Qualifier("securedChannelQueue")
PollableChannel securedChannelQueue;
@Autowired
@Qualifier("errorChannel")
PollableChannel errorChannel;
@Autowired
TestHandler testConsumer;
@@ -66,14 +88,12 @@ public class ChannelAdapterSecurityIntegrationTests extends AbstractJUnit4Spring
@Test(expected = AccessDeniedException.class)
@DirtiesContext
public void testSecuredWithNotEnoughPermission() {
login("bob", "bobspassword", "ROLE_ADMINA");
securedChannelAdapter.send(new GenericMessage<String>("test"));
}
@Test
@DirtiesContext
public void testSecuredWithPermission() {
login("bob", "bobspassword", "ROLE_ADMIN", "ROLE_PRESIDENT");
securedChannelAdapter.send(new GenericMessage<String>("test"));
@@ -81,28 +101,42 @@ public class ChannelAdapterSecurityIntegrationTests extends AbstractJUnit4Spring
assertEquals("Wrong size of message list in target", 2, testConsumer.sentMessages.size());
}
@Test
public void testSecurityContextPropagation() {
login("bob", "bobspassword", "ROLE_ADMIN", "ROLE_PRESIDENT");
this.queueChannel.send(new GenericMessage<String>("test"));
Message<?> receive = this.securedChannelQueue.receive(10000);
assertNotNull(receive);
SecurityContextHolder.clearContext();
this.queueChannel.send(new GenericMessage<String>("test"));
Message<?> errorMessage = this.errorChannel.receive(1000);
assertNotNull(errorMessage);
Object payload = errorMessage.getPayload();
assertThat(payload, instanceOf(MessageHandlingException.class));
assertThat(((MessageHandlingException) payload).getCause(),
instanceOf(AuthenticationCredentialsNotFoundException.class));
}
@Test(expected = AccessDeniedException.class)
@DirtiesContext
public void testSecuredWithoutPermision() {
public void testSecuredWithoutPermission() {
login("bob", "bobspassword", "ROLE_USER");
securedChannelAdapter.send(new GenericMessage<String>("test"));
}
@Test(expected = AccessDeniedException.class)
@DirtiesContext
public void testSecured2WithoutPermision() {
public void testSecured2WithoutPermission() {
login("bob", "bobspassword", "ROLE_USER");
securedChannelAdapter2.send(new GenericMessage<String>("test"));
}
@Test(expected = AuthenticationException.class)
@DirtiesContext
public void testSecuredWithoutAuthenticating() {
securedChannelAdapter.send(new GenericMessage<String>("test"));
}
@Test
@DirtiesContext
public void testUnsecuredAsAdmin() {
login("bob", "bobspassword", "ROLE_ADMIN");
unsecuredChannelAdapter.send(new GenericMessage<String>("test"));
@@ -110,7 +144,6 @@ public class ChannelAdapterSecurityIntegrationTests extends AbstractJUnit4Spring
}
@Test
@DirtiesContext
public void testUnsecuredAsUser() {
login("bob", "bobspassword", "ROLE_USER");
unsecuredChannelAdapter.send(new GenericMessage<String>("test"));
@@ -118,7 +151,6 @@ public class ChannelAdapterSecurityIntegrationTests extends AbstractJUnit4Spring
}
@Test
@DirtiesContext
public void testUnsecuredWithoutAuthenticating() {
unsecuredChannelAdapter.send(new GenericMessage<String>("test"));
assertEquals("Wrong size of message list in target", 1, testConsumer.sentMessages.size());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2011 the original author or authors.
* 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.

View File

@@ -16,27 +16,56 @@
package org.springframework.integration.security.config;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.integration.annotation.BridgeTo;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.ChannelInterceptorAware;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.ExecutorChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.config.GlobalChannelInterceptor;
import org.springframework.integration.router.RecipientListRouter;
import org.springframework.integration.security.SecurityTestUtils;
import org.springframework.integration.security.TestHandler;
import org.springframework.integration.security.channel.ChannelSecurityInterceptor;
import org.springframework.integration.security.channel.SecuredChannel;
import org.springframework.integration.security.channel.SecurityContextPropagationChannelInterceptor;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
@@ -63,6 +92,22 @@ public class ChannelSecurityInterceptorSecuredChannelAnnotationTests {
@Autowired
MessageChannel unsecuredChannel;
@Autowired
@Qualifier("queueChannel")
MessageChannel queueChannel;
@Autowired
@Qualifier("securedChannelQueue")
PollableChannel securedChannelQueue;
@Autowired
@Qualifier("executorChannel")
MessageChannel executorChannel;
@Autowired
@Qualifier("errorChannel")
PollableChannel errorChannel;
@Autowired
TestHandler testConsumer;
@@ -124,6 +169,42 @@ public class ChannelSecurityInterceptorSecuredChannelAnnotationTests {
assertEquals("Wrong size of message list in target", 1, testConsumer.sentMessages.size());
}
@Test
public void testSecurityContextPropagationQueueChannel() {
login("bob", "bobspassword", "ROLE_ADMIN", "ROLE_PRESIDENT");
this.queueChannel.send(new GenericMessage<String>("test"));
Message<?> receive = this.securedChannelQueue.receive(10000);
assertNotNull(receive);
SecurityContextHolder.clearContext();
this.queueChannel.send(new GenericMessage<String>("test"));
Message<?> errorMessage = this.errorChannel.receive(1000);
assertNotNull(errorMessage);
Object payload = errorMessage.getPayload();
assertThat(payload, instanceOf(MessageHandlingException.class));
assertThat(((MessageHandlingException) payload).getCause(),
instanceOf(AuthenticationCredentialsNotFoundException.class));
}
@Test
public void testSecurityContextPropagationExecutorChannel() {
login("bob", "bobspassword", "ROLE_ADMIN", "ROLE_PRESIDENT");
this.executorChannel.send(new GenericMessage<String>("test"));
Message<?> receive = this.securedChannelQueue.receive(10000);
assertNotNull(receive);
SecurityContextHolder.clearContext();
this.queueChannel.send(new GenericMessage<String>("test"));
Message<?> errorMessage = this.errorChannel.receive(1000);
assertNotNull(errorMessage);
Object payload = errorMessage.getPayload();
assertThat(payload, instanceOf(MessageHandlingException.class));
assertThat(((MessageHandlingException) payload).getCause(),
instanceOf(AuthenticationCredentialsNotFoundException.class));
}
private void login(String username, String password, String... roles) {
SecurityContext context = SecurityTestUtils.createContext(username, password, roles);
@@ -153,6 +234,41 @@ public class ChannelSecurityInterceptorSecuredChannelAnnotationTests {
return new DirectChannel();
}
@Bean
@GlobalChannelInterceptor(patterns = {"queueChannel", "executorChannel"})
public ChannelInterceptor securityContextPropagationInterceptor() {
return new SecurityContextPropagationChannelInterceptor();
}
@Bean
@BridgeTo(value = "securedChannelQueue", poller = @Poller(fixedDelay = "1000"))
public PollableChannel queueChannel() {
return new QueueChannel();
}
@Bean
@SecuredChannel(interceptor = "channelSecurityInterceptor", sendAccess = {"ROLE_ADMIN", "ROLE_PRESIDENT"})
public PollableChannel securedChannelQueue() {
return new QueueChannel();
}
@Bean
@BridgeTo("securedChannelQueue")
public SubscribableChannel executorChannel() {
return new ExecutorChannel(Executors.newSingleThreadExecutor());
}
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Bean
public PollableChannel errorChannel() {
return new QueueChannel();
}
@Bean
public TestHandler testHandler() {
TestHandler testHandler = new TestHandler();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.

View File

@@ -2,7 +2,7 @@ log4j.rootCategory=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1}: %m%n
log4j.appender.stdout.layout.ConversionPattern=%d %5p %c{1} [%t] : %m%n
log4j.category.org.springframework.integration.security=WARN
log4j.category.org.springframework.integration=WARN