SEC-2179: Add Spring Security Messaging Support

This commit is contained in:
Rob Winch
2014-08-15 16:39:22 -05:00
parent 934937d9c1
commit 3f30529039
28 changed files with 2282 additions and 4 deletions

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2002-2014 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.security.messaging.access.expression;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import java.util.Collection;
import java.util.LinkedHashMap;
@RunWith(MockitoJUnitRunner.class)
public class ExpressionBasedMessageSecurityMetadataSourceFactoryTests {
@Mock
MessageMatcher matcher1;
@Mock
MessageMatcher matcher2;
@Mock
Message message;
@Mock
Authentication authentication;
String expression1;
String expression2;
LinkedHashMap<MessageMatcher<?>,String> matcherToExpression;
MessageSecurityMetadataSource source;
MessageSecurityExpressionRoot rootObject;
@Before
public void setup() {
expression1 = "permitAll";
expression2 = "denyAll";
matcherToExpression = new LinkedHashMap<MessageMatcher<?>, String>();
matcherToExpression.put(matcher1, expression1);
matcherToExpression.put(matcher2, expression2);
source = createExpressionMessageMetadataSource(matcherToExpression);
rootObject = new MessageSecurityExpressionRoot(authentication, message);
}
@Test
public void createExpressionMessageMetadataSourceNoMatch() {
Collection<ConfigAttribute> attrs = source.getAttributes(message);
assertThat(attrs).isNull();
}
@Test
public void createExpressionMessageMetadataSourceMatchFirst() {
when(matcher1.matches(message)).thenReturn(true);
Collection<ConfigAttribute> attrs = source.getAttributes(message);
assertThat(attrs.size()).isEqualTo(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute)attr).getAuthorizeExpression().getValue(rootObject)).isEqualTo(true);
}
@Test
public void createExpressionMessageMetadataSourceMatchSecond() {
when(matcher2.matches(message)).thenReturn(true);
Collection<ConfigAttribute> attrs = source.getAttributes(message);
assertThat(attrs.size()).isEqualTo(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute)attr).getAuthorizeExpression().getValue(rootObject)).isEqualTo(false);
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2014 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.security.messaging.access.expression;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.expression.Expression;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MessageExpressionConfigAttributeTests {
@Mock
Expression expression;
MessageExpressionConfigAttribute attribute;
@Before
public void setup() {
attribute = new MessageExpressionConfigAttribute(expression);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullExpression() {
new MessageExpressionConfigAttribute(null);
}
@Test
public void getAuthorizeExpression() {
assertThat(attribute.getAuthorizeExpression()).isSameAs(expression);
}
@Test
public void getAttribute() {
assertThat(attribute.getAttribute()).isNull();
}
@Test
public void toStringUsesExpressionString() {
when(expression.getExpressionString()).thenReturn("toString");
assertThat(attribute.toString()).isEqualTo(expression.getExpressionString());
}
}

View File

@@ -0,0 +1,114 @@
/*
* Copyright 2002-2014 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.security.messaging.access.expression;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import java.util.Arrays;
import java.util.Collection;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.springframework.security.access.AccessDecisionVoter.*;
@RunWith(MockitoJUnitRunner.class)
public class MessageExpressionVoterTests {
@Mock
Authentication authentication;
@Mock
Message<Object> message;
Collection<ConfigAttribute> attributes;
@Mock
Expression expression;
@Mock
SecurityExpressionHandler<Message> expressionHandler;
@Mock
EvaluationContext evaluationContext;
MessageExpressionVoter voter;
@Before
public void setup() {
attributes = Arrays.<ConfigAttribute>asList(new MessageExpressionConfigAttribute(expression));
voter = new MessageExpressionVoter();
}
@Test
public void voteGranted() {
when(expression.getValue(any(EvaluationContext.class),eq(Boolean.class))).thenReturn(true);
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_GRANTED);
}
@Test
public void voteDenied() {
when(expression.getValue(any(EvaluationContext.class),eq(Boolean.class))).thenReturn(false);
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_DENIED);
}
@Test
public void voteAbstain() {
attributes = Arrays.<ConfigAttribute>asList(new SecurityConfig("ROLE_USER"));
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_ABSTAIN);
}
@Test
public void supportsObjectClassFalse() {
assertThat(voter.supports(Object.class)).isFalse();
}
@Test
public void supportsMessageClassTrue() {
assertThat(voter.supports(Message.class)).isTrue();
}
@Test
public void supportsSecurityConfigFalse() {
assertThat(voter.supports(new SecurityConfig("ROLE_USER"))).isFalse();
}
@Test
public void supportsMessageExpressionConfigAttributeTrue() {
assertThat(voter.supports(new MessageExpressionConfigAttribute(expression))).isTrue();
}
@Test(expected = IllegalArgumentException.class)
public void setExpressionHandlerNull() {
voter.setExpressionHandler(null);
}
@Test
public void customExpressionHandler() {
voter.setExpressionHandler(expressionHandler);
when(expressionHandler.createEvaluationContext(authentication, message)).thenReturn(evaluationContext);
when(expression.getValue(evaluationContext, Boolean.class)).thenReturn(true);
assertThat(voter.vote(authentication, message, attributes)).isEqualTo(ACCESS_GRANTED);
verify(expressionHandler).createEvaluationContext(authentication, message);
}
}

View File

@@ -0,0 +1,158 @@
/*
* Copyright 2002-2014 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.security.messaging.access.intercept;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ChannelSecurityInterceptorTests {
@Mock
Message message;
@Mock
MessageChannel channel;
@Mock
MessageSecurityMetadataSource source;
@Mock
AccessDecisionManager accessDecisionManager;
List<ConfigAttribute> attrs;
ChannelSecurityInterceptor interceptor;
@Before
public void setup() {
attrs = Arrays.<ConfigAttribute>asList(new SecurityConfig("ROLE_USER"));
interceptor = new ChannelSecurityInterceptor(source);
interceptor.setAccessDecisionManager(accessDecisionManager);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
}
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
public void constructorMessageSecurityMetadataSourceNull() {
new ChannelSecurityInterceptor(null);
}
@Test
public void getSecureObjectClass() throws Exception {
assertThat(interceptor.getSecureObjectClass()).isEqualTo(Message.class);
}
@Test
public void obtainSecurityMetadataSource() throws Exception {
assertThat(interceptor.obtainSecurityMetadataSource()).isEqualTo(source);
}
@Test
public void preSendNullAttributes() throws Exception {
assertThat(interceptor.preSend(message, channel)).isSameAs(message);
}
@Test
public void preSendGrant() throws Exception {
when(source.getAttributes(message)).thenReturn(attrs);
Message<?> result = interceptor.preSend(message, channel);
assertThat(result).isInstanceOf(ChannelSecurityInterceptor.TokenMessage.class);
ChannelSecurityInterceptor.TokenMessage tm = (ChannelSecurityInterceptor.TokenMessage) result;
assertThat(tm.getHeaders()).isSameAs(message.getHeaders());
assertThat(tm.getPayload()).isSameAs(message.getPayload());
assertThat(tm.getToken()).isNotNull();
}
@Test(expected = AccessDeniedException.class)
public void preSendDeny() throws Exception {
when(source.getAttributes(message)).thenReturn(attrs);
doThrow(new AccessDeniedException("")).when(accessDecisionManager).decide(any(Authentication.class), eq(message), eq(attrs));
interceptor.preSend(message, channel);
}
@Test
public void postSendNotTokenMessageNoExceptionThrown() throws Exception {
interceptor.postSend(message, channel, true);
}
@Test
public void postSendTokenMessage() throws Exception {
InterceptorStatusToken token = new InterceptorStatusToken(SecurityContextHolder.createEmptyContext(),true,attrs,message);
ChannelSecurityInterceptor.TokenMessage tokenMessage = new ChannelSecurityInterceptor.TokenMessage(message, token);
interceptor.postSend(tokenMessage, channel, true);
assertThat(SecurityContextHolder.getContext()).isSameAs(token.getSecurityContext());
}
@Test
public void afterSendCompletionNotTokenMessageNoExceptionThrown() throws Exception {
interceptor.afterSendCompletion(message, channel, true, null);
}
@Test
public void afterSendCompletionTokenMessage() throws Exception {
InterceptorStatusToken token = new InterceptorStatusToken(SecurityContextHolder.createEmptyContext(),true,attrs,message);
ChannelSecurityInterceptor.TokenMessage tokenMessage = new ChannelSecurityInterceptor.TokenMessage(message, token);
interceptor.afterSendCompletion(tokenMessage, channel, true, null);
assertThat(SecurityContextHolder.getContext()).isSameAs(token.getSecurityContext());
}
@Test
public void preReceive() throws Exception {
assertThat(interceptor.preReceive(channel)).isTrue();;
}
@Test
public void postReceive() throws Exception {
assertThat(interceptor.postReceive(message, channel)).isSameAs(message);
}
@Test
public void afterReceiveCompletionNullExceptionNoExceptionThrown() throws Exception {
interceptor.afterReceiveCompletion(message, channel, null);
}
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright 2002-2014 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.security.messaging.access.intercept;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import static org.fest.assertions.Assertions.assertThat;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DefaultMessageSecurityMetadataSourceTests {
@Mock
MessageMatcher matcher1;
@Mock
MessageMatcher matcher2;
@Mock
Message message;
@Mock
Authentication authentication;
SecurityConfig config1;
SecurityConfig config2;
LinkedHashMap<MessageMatcher<?>,Collection<ConfigAttribute>> messageMap;
MessageSecurityMetadataSource source;
@Before
public void setup() {
messageMap = new LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>>();
messageMap.put(matcher1, Arrays.<ConfigAttribute>asList(config1));
messageMap.put(matcher2, Arrays.<ConfigAttribute>asList(config2));
source = new DefaultMessageSecurityMetadataSource(messageMap);
}
@Test
public void getAttributesNull() {
assertThat(source.getAttributes(message)).isNull();
}
@Test
public void getAttributesFirst() {
when(matcher1.matches(message)).thenReturn(true);
assertThat(source.getAttributes(message)).containsOnly(config1);
}
@Test
public void getAttributesSecond() {
when(matcher1.matches(message)).thenReturn(true);
assertThat(source.getAttributes(message)).containsOnly(config2);
}
@Test
public void getAllConfigAttributes() {
assertThat(source.getAllConfigAttributes()).containsOnly(config1,config2);
}
@Test
public void supportsFalse() {
assertThat(source.supports(Object.class)).isFalse();
}
@Test
public void supportsTrue() {
assertThat(source.supports(Message.class)).isTrue();
}
}

View File

@@ -0,0 +1,149 @@
package org.springframework.security.messaging.context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.messaging.context.SecurityContextChannelInterceptor;
import java.security.Principal;
import static org.fest.assertions.Assertions.assertThat;
import static org.springframework.security.core.context.SecurityContextHolder.*;
@RunWith(MockitoJUnitRunner.class)
public class SecurityContextChannelInterceptorTests {
@Mock
MessageChannel channel;
@Mock
MessageHandler handler;
@Mock
Principal principal;
MessageBuilder messageBuilder;
Authentication authentication;
SecurityContextChannelInterceptor interceptor;
@Before
public void setup() {
authentication = new TestingAuthenticationToken("user","pass", "ROLE_USER");
messageBuilder = MessageBuilder.withPayload("payload");
interceptor = new SecurityContextChannelInterceptor();
}
@After
public void cleanup() {
clearContext();
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullHeader() {
new SecurityContextChannelInterceptor(null);
}
@Test
public void preSendCustomHeader() throws Exception {
String headerName = "header";
interceptor = new SecurityContextChannelInterceptor(headerName);
messageBuilder.setHeader(headerName, authentication);
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(authentication);
}
@Test
public void preSendUserSet() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, authentication);
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(authentication);
}
@Test
public void preSendUserNotAuthentication() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, principal);
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void preSendUserNotSet() throws Exception {
interceptor.preSend(messageBuilder.build(), channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterSendCompletion() throws Exception {
SecurityContextHolder.getContext().setAuthentication(authentication);
interceptor.afterSendCompletion(messageBuilder.build(), channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterSendCompletionNullAuthentication() throws Exception {
interceptor.afterSendCompletion(messageBuilder.build(), channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void beforeHandleUserSet() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, authentication);
interceptor.beforeHandle(messageBuilder.build(), channel, handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(authentication);
}
@Test
public void beforeHandleUserNotAuthentication() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, principal);
interceptor.beforeHandle(messageBuilder.build(), channel, handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void beforeHandleUserNotSet() throws Exception {
interceptor.beforeHandle(messageBuilder.build(), channel, handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterMessageHandledUserNotSet() throws Exception {
interceptor.afterMessageHandled(messageBuilder.build(), channel, handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterMessageHandled() throws Exception {
SecurityContextHolder.getContext().setAuthentication(authentication);
interceptor.afterMessageHandled(messageBuilder.build(), channel, handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2014 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.security.messaging.util.matcher;
import org.junit.Before;
import org.junit.Test;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import static org.fest.assertions.Assertions.assertThat;
public class SimpDestinationMessageMatcherTests {
MessageBuilder<String> messageBuilder;
SimpDestinationMessageMatcher matcher;
@Before
public void setup() {
messageBuilder = MessageBuilder.withPayload("M");
matcher = new SimpDestinationMessageMatcher("/**");
}
@Test(expected = IllegalArgumentException.class)
public void constructorPatternNull() {
new SimpDestinationMessageMatcher(null);
}
@Test
public void matchesDoesNotMatchNullDestination() throws Exception {
assertThat(matcher.matches(messageBuilder.build())).isFalse();
}
@Test
public void matchesAllWithDestination() throws Exception {
messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER,"/destination/1");
assertThat(matcher.matches(messageBuilder.build())).isTrue();
}
@Test
public void matchesSpecificWithDestination() throws Exception {
matcher = new SimpDestinationMessageMatcher("/destination/1");
messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER,"/destination/1");
assertThat(matcher.matches(messageBuilder.build())).isTrue();
}
@Test
public void matchesFalseWithDestination() throws Exception {
matcher = new SimpDestinationMessageMatcher("/nomatch");
messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER,"/destination/1");
assertThat(matcher.matches(messageBuilder.build())).isFalse();
}
}