Repository: ambari Updated Branches: refs/heads/branch-feature-AMBARI-20859 7bb4de144 -> 553e4f9d2
http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/main/resources/webapp/WEB-INF/spring-security.xml ---------------------------------------------------------------------- diff --git a/ambari-server/src/main/resources/webapp/WEB-INF/spring-security.xml b/ambari-server/src/main/resources/webapp/WEB-INF/spring-security.xml index 6650f67..9080866 100644 --- a/ambari-server/src/main/resources/webapp/WEB-INF/spring-security.xml +++ b/ambari-server/src/main/resources/webapp/WEB-INF/spring-security.xml @@ -58,10 +58,10 @@ <beans:constructor-arg ref="ambariAuthenticationEventHandler"/> </beans:bean> - <beans:bean id="ambariJwtAuthenticationFilter" class="org.apache.ambari.server.security.authentication.AmbariJWTAuthenticationFilter"> + <beans:bean id="ambariJwtAuthenticationFilter" class="org.apache.ambari.server.security.authentication.jwt.AmbariJwtAuthenticationFilter"> <beans:constructor-arg ref="ambariEntryPoint"/> <beans:constructor-arg ref="ambariConfiguration"/> - <beans:constructor-arg ref="ambariUsers"/> + <beans:constructor-arg ref="ambariJwtAuthenticationProvider"/> <beans:constructor-arg ref="ambariAuthenticationEventHandler"/> </beans:bean> http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/SecurityHelperImplTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/SecurityHelperImplTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/SecurityHelperImplTest.java index 4d6d5a9..6757b78 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/SecurityHelperImplTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/SecurityHelperImplTest.java @@ -22,7 +22,7 @@ import java.util.Collection; import org.apache.ambari.server.orm.entities.PrincipalEntity; import org.apache.ambari.server.orm.entities.UserEntity; -import org.apache.ambari.server.security.authorization.AmbariUserAuthentication; +import org.apache.ambari.server.security.authentication.AmbariUserAuthentication; import org.apache.ambari.server.security.authorization.User; import org.apache.ambari.server.security.authorization.UserName; import org.junit.Assert; http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AbstractAuthenticationProviderTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AbstractAuthenticationProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AbstractAuthenticationProviderTest.java index 96b4883..49e8a8f 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AbstractAuthenticationProviderTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AbstractAuthenticationProviderTest.java @@ -31,7 +31,6 @@ import org.apache.ambari.server.hooks.HookContextFactory; import org.apache.ambari.server.hooks.HookService; import org.apache.ambari.server.orm.DBAccessor; import org.apache.ambari.server.orm.entities.UserEntity; -import org.apache.ambari.server.security.authorization.AmbariUserAuthentication; import org.apache.ambari.server.security.authorization.Users; import org.apache.ambari.server.state.stack.OsFamily; import org.easymock.EasyMockSupport; http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariJWTAuthenticationFilterTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariJWTAuthenticationFilterTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariJWTAuthenticationFilterTest.java deleted file mode 100644 index 14c1032..0000000 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariJWTAuthenticationFilterTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.apache.ambari.server.security.authentication; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.capture; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.newCapture; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Calendar; -import java.util.Collections; -import java.util.List; - -import javax.servlet.FilterChain; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.ambari.server.configuration.Configuration; -import org.apache.ambari.server.orm.entities.UserAuthenticationEntity; -import org.apache.ambari.server.orm.entities.UserEntity; -import org.apache.ambari.server.security.AmbariEntryPoint; -import org.apache.ambari.server.security.authorization.AmbariGrantedAuthority; -import org.apache.ambari.server.security.authorization.User; -import org.apache.ambari.server.security.authorization.UserAuthenticationType; -import org.apache.ambari.server.security.authorization.Users; -import org.apache.ambari.server.security.authorization.jwt.JwtAuthenticationProperties; -import org.easymock.Capture; -import org.easymock.CaptureType; -import org.easymock.EasyMockSupport; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.SignedJWT; - -public class AmbariJWTAuthenticationFilterTest extends EasyMockSupport { - private static RSAPublicKey publicKey; - private static RSAPrivateKey privateKey; - - private AmbariAuthenticationEventHandler eventHandler; - - private AmbariEntryPoint entryPoint; - - private Configuration configuration; - - private Users users; - - @BeforeClass - public static void generateKeyPair() throws NoSuchAlgorithmException { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(512); - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - publicKey = (RSAPublicKey) keyPair.getPublic(); - privateKey = (RSAPrivateKey) keyPair.getPrivate(); - } - - @Before - public void setUp() { - SecurityContextHolder.getContext().setAuthentication(null); - - JwtAuthenticationProperties properties = createMock(JwtAuthenticationProperties.class); - expect(properties.getAuthenticationProviderUrl()).andReturn("some url").once(); - expect(properties.getPublicKey()).andReturn(publicKey).once(); - expect(properties.getAudiences()).andReturn(Collections.singletonList("foobar")).once(); - expect(properties.getCookieName()).andReturn("chocolate chip").once(); - expect(properties.getOriginalUrlQueryParam()).andReturn("question").once(); - - users = createMock(Users.class); - eventHandler = createMock(AmbariAuthenticationEventHandler.class); - entryPoint = createMock(AmbariEntryPoint.class); - configuration = createMock(Configuration.class); - - expect(configuration.getJwtProperties()).andReturn(properties).once(); - } - - - @Test (expected = IllegalArgumentException.class) - public void ensureNonNullEventHandler() { - new AmbariJWTAuthenticationFilter(entryPoint, configuration, users, null); - } - - @Test - public void testDoFilterSuccessful() throws Exception { - Capture<? extends AmbariAuthenticationFilter> captureFilter = newCapture(CaptureType.ALL); - - SignedJWT token = getSignedToken(); - - HttpServletRequest request = createMock(HttpServletRequest.class); - HttpServletResponse response = createMock(HttpServletResponse.class); - FilterChain filterChain = createMock(FilterChain.class); - - Cookie cookie = createMock(Cookie.class); - expect(cookie.getName()).andReturn("chocolate chip").once(); - expect(cookie.getValue()).andReturn(token.serialize()).once(); - - expect(request.getCookies()).andReturn(new Cookie[]{cookie}).once(); - - UserAuthenticationEntity userAuthenticationEntity = createMock(UserAuthenticationEntity.class); - expect(userAuthenticationEntity.getAuthenticationType()).andReturn(UserAuthenticationType.JWT).anyTimes(); - - UserEntity userEntity = createMock(UserEntity.class); - expect(userEntity.getAuthenticationEntities()).andReturn(Collections.singletonList(userAuthenticationEntity)).once(); - - expect(users.getUserEntity("test-user")).andReturn(userEntity).once(); - expect(users.getUserAuthorities(userEntity)).andReturn(Collections.<AmbariGrantedAuthority>emptyList()).once(); - expect(users.getUser(userEntity)).andReturn(createMock(User.class)).once(); - - eventHandler.beforeAttemptAuthentication(capture(captureFilter), eq(request), eq(response)); - expectLastCall().once(); - eventHandler.onSuccessfulAuthentication(capture(captureFilter), eq(request), eq(response), anyObject(Authentication.class)); - expectLastCall().once(); - - filterChain.doFilter(request, response); - expectLastCall().once(); - - replayAll(); - - // WHEN - AmbariJWTAuthenticationFilter filter = new AmbariJWTAuthenticationFilter(entryPoint, configuration, users, eventHandler); - filter.doFilter(request, response, filterChain); - // THEN - verifyAll(); - - List<? extends AmbariAuthenticationFilter> capturedFilters = captureFilter.getValues(); - for(AmbariAuthenticationFilter capturedFiltered : capturedFilters) { - Assert.assertSame(filter, capturedFiltered); - } - } - - - @Test - public void testDoFilterUnsuccessful() throws Exception { - Capture<? extends AmbariAuthenticationFilter> captureFilter = newCapture(CaptureType.ALL); - - SignedJWT token = getSignedToken(); - // GIVEN - HttpServletRequest request = createMock(HttpServletRequest.class); - HttpServletResponse response = createMock(HttpServletResponse.class); - FilterChain filterChain = createMock(FilterChain.class); - - Cookie cookie = createMock(Cookie.class); - expect(cookie.getName()).andReturn("chocolate chip").once(); - expect(cookie.getValue()).andReturn(token.serialize()).once(); - - expect(request.getCookies()).andReturn(new Cookie[]{cookie}).once(); - - expect(users.getUserEntity("test-user")).andReturn(null).once(); - - eventHandler.beforeAttemptAuthentication(capture(captureFilter), eq(request), eq(response)); - expectLastCall().once(); - eventHandler.onUnsuccessfulAuthentication(capture(captureFilter), eq(request), eq(response), anyObject(AmbariAuthenticationException.class)); - expectLastCall().once(); - - entryPoint.commence(eq(request), eq(response), anyObject(AmbariAuthenticationException.class)); - expectLastCall().once(); - - replayAll(); - // WHEN - AmbariJWTAuthenticationFilter filter = new AmbariJWTAuthenticationFilter(entryPoint, configuration, users, eventHandler); - filter.doFilter(request, response, filterChain); - // THEN - verifyAll(); - - List<? extends AmbariAuthenticationFilter> capturedFilters = captureFilter.getValues(); - for (AmbariAuthenticationFilter capturedFiltered : capturedFilters) { - Assert.assertSame(filter, capturedFiltered); - } - } - - private SignedJWT getSignedToken() throws JOSEException { - RSASSASigner signer = new RSASSASigner(privateKey); - - Calendar expirationTime = Calendar.getInstance(); - expirationTime.setTimeInMillis(System.currentTimeMillis()); - expirationTime.add(Calendar.DATE, 1); //add one day - - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(System.currentTimeMillis()); - JWTClaimsSet claimsSet = new JWTClaimsSet(); - claimsSet.setSubject("test-user"); - claimsSet.setIssuer("unit-test"); - claimsSet.setIssueTime(calendar.getTime()); - - claimsSet.setExpirationTime(expirationTime.getTime()); - - claimsSet.setAudience("foobar"); - - SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); - signedJWT.sign(signer); - - return signedJWT; - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariLocalAuthenticationProviderTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariLocalAuthenticationProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariLocalAuthenticationProviderTest.java index d445c07..b9bfb72 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariLocalAuthenticationProviderTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/AmbariLocalAuthenticationProviderTest.java @@ -24,7 +24,6 @@ import java.util.Collections; import org.apache.ambari.server.orm.entities.PrincipalEntity; import org.apache.ambari.server.orm.entities.UserAuthenticationEntity; import org.apache.ambari.server.orm.entities.UserEntity; -import org.apache.ambari.server.security.authorization.AmbariUserAuthentication; import org.apache.ambari.server.security.authorization.UserAuthenticationType; import org.apache.ambari.server.security.authorization.UserName; import org.springframework.security.authentication.AuthenticationProvider; http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/AmbariJwtAuthenticationFilterTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/AmbariJwtAuthenticationFilterTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/AmbariJwtAuthenticationFilterTest.java new file mode 100644 index 0000000..debfaf6 --- /dev/null +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/AmbariJwtAuthenticationFilterTest.java @@ -0,0 +1,492 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.ambari.server.security.authentication.jwt; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.capture; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.newCapture; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import javax.servlet.FilterChain; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.ambari.server.configuration.Configuration; +import org.apache.ambari.server.orm.entities.PrincipalEntity; +import org.apache.ambari.server.orm.entities.UserAuthenticationEntity; +import org.apache.ambari.server.orm.entities.UserEntity; +import org.apache.ambari.server.security.AmbariEntryPoint; +import org.apache.ambari.server.security.authentication.AmbariAuthenticationEventHandler; +import org.apache.ambari.server.security.authentication.AmbariAuthenticationException; +import org.apache.ambari.server.security.authentication.AmbariAuthenticationFilter; +import org.apache.ambari.server.security.authorization.UserAuthenticationType; +import org.apache.ambari.server.security.authorization.Users; +import org.easymock.Capture; +import org.easymock.CaptureType; +import org.easymock.EasyMockSupport; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.AuthenticationEntryPoint; + +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; + +public class AmbariJwtAuthenticationFilterTest extends EasyMockSupport { + private static RSAPublicKey publicKey; + private static RSAPrivateKey privateKey; + private static RSAPrivateKey invalidPrivateKey; + + + @BeforeClass + public static void generateKeyPair() throws NoSuchAlgorithmException { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(512); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + publicKey = (RSAPublicKey) keyPair.getPublic(); + privateKey = (RSAPrivateKey) keyPair.getPrivate(); + + keyPair = keyPairGenerator.generateKeyPair(); + invalidPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); + } + + @Before + public void setup() { + SecurityContextHolder.clearContext(); + } + + private JwtAuthenticationProperties createTestProperties() { + return createTestProperties(Collections.singletonList("test-audience")); + } + + private JwtAuthenticationProperties createTestProperties(List<String> audiences) { + JwtAuthenticationProperties properties = new JwtAuthenticationProperties(); + properties.setCookieName("non-default"); + properties.setPublicKey(publicKey); + properties.setAudiences(audiences); + + return properties; + } + + private SignedJWT getSignedToken() throws JOSEException { + return getSignedToken("test-audience"); + } + + private SignedJWT getSignedToken(String audience) throws JOSEException { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + calendar.add(Calendar.DATE, 1); //add one day + return getSignedToken(calendar.getTime(), audience); + } + + private SignedJWT getSignedToken(Date expirationTime, String audience) throws JOSEException { + RSASSASigner signer = new RSASSASigner(privateKey); + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + JWTClaimsSet claimsSet = new JWTClaimsSet(); + claimsSet.setSubject("test-user"); + claimsSet.setIssuer("unit-test"); + claimsSet.setIssueTime(calendar.getTime()); + + claimsSet.setExpirationTime(expirationTime); + + claimsSet.setAudience(audience); + + SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); + signedJWT.sign(signer); + + return signedJWT; + } + + private SignedJWT getInvalidToken() throws JOSEException { + RSASSASigner signer = new RSASSASigner(invalidPrivateKey); + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + calendar.add(Calendar.DATE, -2); + + JWTClaimsSet claimsSet = new JWTClaimsSet(); + claimsSet.setSubject("test-user"); + claimsSet.setIssuer("unit-test"); + claimsSet.setIssueTime(calendar.getTime()); + + calendar.add(Calendar.DATE, 1); //add one day + claimsSet.setExpirationTime(calendar.getTime()); + + claimsSet.setAudience("test-audience-invalid"); + + SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); + signedJWT.sign(signer); + + return signedJWT; + } + + @Test + public void testGetJWTFromCookie() throws Exception { + HttpServletRequest request = createNiceMock(HttpServletRequest.class); + Cookie cookie = createNiceMock(Cookie.class); + + expect(cookie.getName()).andReturn("non-default"); + expect(cookie.getValue()).andReturn("stubtokenstring"); + + expect(request.getCookies()).andReturn(new Cookie[]{cookie}); + + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + String jwtFromCookie = filter.getJWTFromCookie(request); + + verifyAll(); + + assertEquals("stubtokenstring", jwtFromCookie); + } + + @Test + public void testValidateSignature() throws Exception { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertTrue(filter.validateSignature(getSignedToken())); + assertFalse(filter.validateSignature(getInvalidToken())); + + verifyAll(); + } + + @Test + public void testValidateAudiences() throws Exception { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + + assertTrue(filter.validateAudiences(getSignedToken())); + assertFalse(filter.validateAudiences(getInvalidToken())); + + verifyAll(); + } + + @Test + public void testValidateNullAudiences() throws Exception { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties(null)).anyTimes(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertTrue(filter.validateAudiences(getSignedToken())); + assertTrue(filter.validateAudiences(getInvalidToken())); + + verifyAll(); + } + + @Test + public void testValidateTokenWithoutAudiences() throws Exception { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertFalse(filter.validateAudiences(getSignedToken(null))); + + verifyAll(); + } + + @Test + public void testValidateExpiration() throws Exception { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertTrue(filter.validateExpiration(getSignedToken())); + assertFalse(filter.validateExpiration(getInvalidToken())); + + verifyAll(); + } + + @Test + public void testValidateNoExpiration() throws Exception { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + + assertTrue(filter.validateExpiration(getSignedToken(null, "test-audience"))); + assertFalse(filter.validateExpiration(getInvalidToken())); + + verifyAll(); + } + + @Test + public void testShouldApplyTrue() throws JOSEException { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + SignedJWT token = getInvalidToken(); + + Cookie cookie = createMock(Cookie.class); + expect(cookie.getName()).andReturn("non-default").atLeastOnce(); + expect(cookie.getValue()).andReturn(token.serialize()).atLeastOnce(); + + HttpServletRequest request = createMock(HttpServletRequest.class); + expect(request.getCookies()).andReturn(new Cookie[]{cookie}); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertTrue(filter.shouldApply(request)); + + verifyAll(); + } + + @Test + public void testShouldApplyTrueBadToken() throws JOSEException { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + Cookie cookie = createMock(Cookie.class); + expect(cookie.getName()).andReturn("non-default").atLeastOnce(); + expect(cookie.getValue()).andReturn("bad token").atLeastOnce(); + + HttpServletRequest request = createMock(HttpServletRequest.class); + expect(request.getCookies()).andReturn(new Cookie[]{cookie}); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertTrue(filter.shouldApply(request)); + + verifyAll(); + } + + @Test + public void testShouldApplyFalseMissingCookie() throws JOSEException { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + Cookie cookie = createMock(Cookie.class); + expect(cookie.getName()).andReturn("some-other-cookie").atLeastOnce(); + + HttpServletRequest request = createMock(HttpServletRequest.class); + expect(request.getCookies()).andReturn(new Cookie[]{cookie}); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertFalse(filter.shouldApply(request)); + + verifyAll(); + } + + @Test + public void testShouldApplyFalseNotEnabled() throws JOSEException { + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(null).anyTimes(); + + HttpServletRequest request = createMock(HttpServletRequest.class); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + + replayAll(); + + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, configuration, null, eventHandler); + assertFalse(filter.shouldApply(request)); + + verify(request); + } + + @Test(expected = IllegalArgumentException.class) + public void ensureNonNullEventHandler() { + new AmbariJwtAuthenticationFilter(createNiceMock(AmbariEntryPoint.class), createNiceMock(Configuration.class), createNiceMock(AuthenticationProvider.class), null); + } + + @Test + public void testDoFilterSuccessful() throws Exception { + Capture<? extends AmbariAuthenticationFilter> captureFilter = newCapture(CaptureType.ALL); + + SignedJWT token = getSignedToken(); + + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + expect(configuration.getMaxAuthenticationFailures()).andReturn(10).anyTimes(); + + HttpServletRequest request = createMock(HttpServletRequest.class); + HttpServletResponse response = createMock(HttpServletResponse.class); + FilterChain filterChain = createMock(FilterChain.class); + + Cookie cookie = createMock(Cookie.class); + expect(cookie.getName()).andReturn("non-default").once(); + expect(cookie.getValue()).andReturn(token.serialize()).once(); + + expect(request.getCookies()).andReturn(new Cookie[]{cookie}).once(); + + UserAuthenticationEntity userAuthenticationEntity = createMock(UserAuthenticationEntity.class); + expect(userAuthenticationEntity.getAuthenticationType()).andReturn(UserAuthenticationType.JWT).anyTimes(); + expect(userAuthenticationEntity.getAuthenticationKey()).andReturn("").anyTimes(); + + PrincipalEntity principal = createMock(PrincipalEntity.class); + expect(principal.getPrivileges()).andReturn(Collections.emptySet()).atLeastOnce(); + + UserEntity userEntity = createMock(UserEntity.class); + expect(userEntity.getAuthenticationEntities()).andReturn(Collections.singletonList(userAuthenticationEntity)).once(); + expect(userEntity.getActive()).andReturn(true).atLeastOnce(); + expect(userEntity.getConsecutiveFailures()).andReturn(1).atLeastOnce(); + expect(userEntity.getUserId()).andReturn(1).atLeastOnce(); + expect(userEntity.getUserName()).andReturn("username").atLeastOnce(); + expect(userEntity.getCreateTime()).andReturn(new Date()).atLeastOnce(); + expect(userEntity.getMemberEntities()).andReturn(Collections.emptySet()).atLeastOnce(); + expect(userEntity.getAuthenticationEntities()).andReturn(Collections.singletonList(userAuthenticationEntity)).atLeastOnce(); + expect(userEntity.getPrincipal()).andReturn(principal).atLeastOnce(); + + Users users = createMock(Users.class); + expect(users.getUserEntity("test-user")).andReturn(userEntity).once(); + expect(users.getUserAuthorities(userEntity)).andReturn(Collections.emptyList()).once(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + eventHandler.beforeAttemptAuthentication(capture(captureFilter), eq(request), eq(response)); + expectLastCall().once(); + eventHandler.onSuccessfulAuthentication(capture(captureFilter), eq(request), eq(response), anyObject(Authentication.class)); + expectLastCall().once(); + + filterChain.doFilter(request, response); + expectLastCall().once(); + + AuthenticationEntryPoint entryPoint = createNiceMock(AmbariEntryPoint.class); + + replayAll(); + + AmbariJwtAuthenticationProvider provider = new AmbariJwtAuthenticationProvider(users, configuration); + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(entryPoint, configuration, provider, eventHandler); + filter.doFilter(request, response, filterChain); + + verifyAll(); + + List<? extends AmbariAuthenticationFilter> capturedFilters = captureFilter.getValues(); + for (AmbariAuthenticationFilter capturedFiltered : capturedFilters) { + assertSame(filter, capturedFiltered); + } + } + + + @Test + public void testDoFilterUnsuccessful() throws Exception { + Capture<? extends AmbariAuthenticationFilter> captureFilter = newCapture(CaptureType.ALL); + + SignedJWT token = getSignedToken(); + + Configuration configuration = createNiceMock(Configuration.class); + expect(configuration.getJwtProperties()).andReturn(createTestProperties()).anyTimes(); + + HttpServletRequest request = createMock(HttpServletRequest.class); + HttpServletResponse response = createMock(HttpServletResponse.class); + + FilterChain filterChain = createMock(FilterChain.class); + + Cookie cookie = createMock(Cookie.class); + expect(cookie.getName()).andReturn("non-default").once(); + expect(cookie.getValue()).andReturn(token.serialize()).once(); + + expect(request.getCookies()).andReturn(new Cookie[]{cookie}).once(); + + Users users = createMock(Users.class); + expect(users.getUserEntity("test-user")).andReturn(null).once(); + + AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class); + eventHandler.beforeAttemptAuthentication(capture(captureFilter), eq(request), eq(response)); + expectLastCall().once(); + eventHandler.onUnsuccessfulAuthentication(capture(captureFilter), eq(request), eq(response), anyObject(AmbariAuthenticationException.class)); + expectLastCall().once(); + + AuthenticationEntryPoint entryPoint = createNiceMock(AmbariEntryPoint.class); + entryPoint.commence(eq(request), eq(response), anyObject(AmbariAuthenticationException.class)); + expectLastCall().once(); + + replayAll(); + + AmbariJwtAuthenticationProvider provider = new AmbariJwtAuthenticationProvider(users, configuration); + AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(entryPoint, configuration, provider, eventHandler); + filter.doFilter(request, response, filterChain); + + verifyAll(); + + List<? extends AmbariAuthenticationFilter> capturedFilters = captureFilter.getValues(); + for (AmbariAuthenticationFilter capturedFiltered : capturedFilters) { + assertSame(filter, capturedFiltered); + } + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/JwtAuthenticationPropertiesTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/JwtAuthenticationPropertiesTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/JwtAuthenticationPropertiesTest.java new file mode 100644 index 0000000..9b7e482 --- /dev/null +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/jwt/JwtAuthenticationPropertiesTest.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.ambari.server.security.authentication.jwt; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class JwtAuthenticationPropertiesTest { + + @Test + public void testSetNullAudiences() { + JwtAuthenticationProperties jwtAuthenticationProperties = new JwtAuthenticationProperties(); + jwtAuthenticationProperties.setAudiencesString(null); + assertNull(jwtAuthenticationProperties.getAudiences()); + } + + @Test + public void testSetEmptyAudiences() { + JwtAuthenticationProperties jwtAuthenticationProperties = new JwtAuthenticationProperties(); + jwtAuthenticationProperties.setAudiencesString(""); + assertNull(jwtAuthenticationProperties.getAudiences()); + } + + @Test + public void testSetValidAudiences() { + String[] expectedAudiences = {"first", "second", "third"}; + JwtAuthenticationProperties jwtAuthenticationProperties = new JwtAuthenticationProperties(); + jwtAuthenticationProperties.setAudiencesString("first,second,third"); + assertNotNull(jwtAuthenticationProperties.getAudiences()); + assertArrayEquals(expectedAudiences, jwtAuthenticationProperties.getAudiences().toArray(new String[]{})); + } +} http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariPamAuthenticationProviderTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariPamAuthenticationProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariPamAuthenticationProviderTest.java index 4e080b1..38f9a9e 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariPamAuthenticationProviderTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariPamAuthenticationProviderTest.java @@ -37,6 +37,7 @@ import org.apache.ambari.server.orm.entities.PrincipalEntity; import org.apache.ambari.server.orm.entities.UserAuthenticationEntity; import org.apache.ambari.server.orm.entities.UserEntity; import org.apache.ambari.server.security.ClientSecurityType; +import org.apache.ambari.server.security.authentication.AmbariUserAuthentication; import org.apache.ambari.server.security.authentication.pam.PamAuthenticationFactory; import org.apache.ambari.server.state.stack.OsFamily; import org.easymock.EasyMockSupport; http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AuthorizationHelperTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AuthorizationHelperTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AuthorizationHelperTest.java index 41816aa..cad734c 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AuthorizationHelperTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AuthorizationHelperTest.java @@ -45,6 +45,7 @@ import org.apache.ambari.server.orm.entities.ResourceEntity; import org.apache.ambari.server.orm.entities.ResourceTypeEntity; import org.apache.ambari.server.orm.entities.RoleAuthorizationEntity; import org.apache.ambari.server.orm.entities.UserEntity; +import org.apache.ambari.server.security.authentication.AmbariUserAuthentication; import org.easymock.EasyMockRule; import org.easymock.EasyMockSupport; import org.easymock.Mock; http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationFilterTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationFilterTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationFilterTest.java deleted file mode 100644 index 47df030..0000000 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationFilterTest.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.apache.ambari.server.security.authorization.jwt; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.createMockBuilder; -import static org.easymock.EasyMock.createNiceMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.servlet.FilterChain; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.ambari.server.security.authorization.AmbariGrantedAuthority; -import org.apache.ambari.server.security.authorization.AuthorizationHelper; -import org.apache.ambari.server.security.authorization.User; -import org.apache.ambari.server.security.authorization.Users; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.AuthenticationEntryPoint; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.SignedJWT; - -import junit.framework.Assert; - -public class JwtAuthenticationFilterTest { - private static RSAPublicKey publicKey; - private static RSAPrivateKey privateKey; - private static RSAPrivateKey invalidPrivateKey; - - - @BeforeClass - public static void generateKeyPair() throws NoSuchAlgorithmException { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(512); - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - publicKey = (RSAPublicKey) keyPair.getPublic(); - privateKey = (RSAPrivateKey) keyPair.getPrivate(); - - keyPair = keyPairGenerator.generateKeyPair(); - invalidPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); - } - - private JwtAuthenticationProperties createTestProperties() { - return createTestProperties(Collections.singletonList("test-audience")); - } - - private JwtAuthenticationProperties createTestProperties(List<String> audiences) { - JwtAuthenticationProperties properties = new JwtAuthenticationProperties(); - properties.setCookieName("non-default"); - properties.setPublicKey(publicKey); - properties.setAudiences(audiences); - - return properties; - } - - private SignedJWT getSignedToken() throws JOSEException { - return getSignedToken("test-audience"); - } - - private SignedJWT getSignedToken(String audience) throws JOSEException { - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(System.currentTimeMillis()); - calendar.add(Calendar.DATE, 1); //add one day - return getSignedToken(calendar.getTime(), audience); - } - - private SignedJWT getSignedToken(Date expirationTime, String audience) throws JOSEException { - RSASSASigner signer = new RSASSASigner(privateKey); - - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(System.currentTimeMillis()); - JWTClaimsSet claimsSet = new JWTClaimsSet(); - claimsSet.setSubject("test-user"); - claimsSet.setIssuer("unit-test"); - claimsSet.setIssueTime(calendar.getTime()); - - claimsSet.setExpirationTime(expirationTime); - - claimsSet.setAudience(audience); - - SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); - signedJWT.sign(signer); - - return signedJWT; - } - - private SignedJWT getInvalidToken() throws JOSEException { - RSASSASigner signer = new RSASSASigner(invalidPrivateKey); - - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(System.currentTimeMillis()); - calendar.add(Calendar.DATE, -2); - - JWTClaimsSet claimsSet = new JWTClaimsSet(); - claimsSet.setSubject("test-user"); - claimsSet.setIssuer("unit-test"); - claimsSet.setIssueTime(calendar.getTime()); - - calendar.add(Calendar.DATE, 1); //add one day - claimsSet.setExpirationTime(calendar.getTime()); - - claimsSet.setAudience("test-audience-invalid"); - - SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet); - signedJWT.sign(signer); - - return signedJWT; - } - - - @Test - @Ignore - public void testDoFilter() throws Exception { - Users users = createNiceMock(Users.class); - AuthenticationEntryPoint entryPoint = createNiceMock(AuthenticationEntryPoint.class); - HttpServletRequest request = createNiceMock(HttpServletRequest.class); - HttpServletResponse response = createNiceMock(HttpServletResponse.class); - FilterChain chain = createNiceMock(FilterChain.class); - AmbariGrantedAuthority authority = createNiceMock(AmbariGrantedAuthority.class); - User user = createNiceMock(User.class); - - SignedJWT signedJWT = getSignedToken(); - - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = createMockBuilder(JwtAuthenticationFilter.class). - addMockedMethod("getJWTFromCookie"). - withConstructor(properties, entryPoint, users).createNiceMock(); - - expect(filter.getJWTFromCookie(anyObject(HttpServletRequest.class))).andReturn(signedJWT.serialize()); - expect(users.getUser(eq("test-user"))).andReturn(null).once(); - expect(users.getUser(eq("test-user"))).andReturn(user).anyTimes(); - - users.createUser(eq("test-user"), eq("test-user"), eq("test-user")); - expectLastCall(); - - expect(users.getUserAuthorities(eq("test-user"))).andReturn(Collections.singletonList(authority)); - - expect(user.getUserName()).andReturn("test-user"); - - expect(user.getUserId()).andReturn(1); - - replay(users, request, response, chain, filter, entryPoint, user, authority); - - filter.doFilter(request, response, chain); - - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - assertEquals(1L, AuthorizationHelper.getAuthenticatedId()); - - verify(users, request, response, chain, filter, entryPoint, user, authority); - - assertEquals(true, authentication.isAuthenticated()); - } - - @Test - public void testGetJWTFromCookie() throws Exception { - HttpServletRequest request = createNiceMock(HttpServletRequest.class); - Cookie cookie = createNiceMock(Cookie.class); - - expect(cookie.getName()).andReturn("non-default"); - expect(cookie.getValue()).andReturn("stubtokenstring"); - - expect(request.getCookies()).andReturn(new Cookie[]{cookie}); - - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - replay(request, cookie); - - String jwtFromCookie = filter.getJWTFromCookie(request); - - verify(request, cookie); - - assertEquals("stubtokenstring", jwtFromCookie); - } - - @Test - public void testValidateSignature() throws Exception { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - boolean isValid = filter.validateSignature(getSignedToken()); - - assertEquals(true, isValid); - - isValid = filter.validateSignature(getInvalidToken()); - - assertEquals(false, isValid); - - } - - @Test - public void testValidateAudiences() throws Exception { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - boolean isValid = filter.validateAudiences(getSignedToken()); - - assertEquals(true, isValid); - - isValid = filter.validateAudiences(getInvalidToken()); - - assertEquals(false, isValid); - } - - @Test - public void testValidateNullAudiences() throws Exception { - JwtAuthenticationProperties properties = createTestProperties(null); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - boolean isValid = filter.validateAudiences(getSignedToken()); - - assertEquals(true, isValid); - - isValid = filter.validateAudiences(getInvalidToken()); - - assertEquals(true, isValid); - } - - @Test - public void testValidateTokenWithoutAudiences() throws Exception { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - boolean isValid = filter.validateAudiences(getSignedToken(null)); - - assertEquals(false, isValid); - } - - @Test - public void testValidateExpiration() throws Exception { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - boolean isValid = filter.validateExpiration(getSignedToken()); - - assertEquals(true, isValid); - - isValid = filter.validateExpiration(getInvalidToken()); - - assertEquals(false, isValid); - - } - - @Test - public void testValidateNoExpiration() throws Exception { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - boolean isValid = filter.validateExpiration(getSignedToken(null, "test-audience")); - - assertEquals(true, isValid); - - isValid = filter.validateExpiration(getInvalidToken()); - - assertEquals(false, isValid); - - } - - @Test - public void testShouldApplyTrue() throws JOSEException { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - SignedJWT token = getInvalidToken(); - - Cookie cookie = createMock(Cookie.class); - expect(cookie.getName()).andReturn("non-default").atLeastOnce(); - expect(cookie.getValue()).andReturn(token.serialize()).atLeastOnce(); - - HttpServletRequest request = createMock(HttpServletRequest.class); - expect(request.getCookies()).andReturn(new Cookie[]{cookie}); - - replay(request, cookie); - - Assert.assertTrue(filter.shouldApply(request)); - - verify(request, cookie); - } - - @Test - public void testShouldApplyTrueBadToken() throws JOSEException { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - Cookie cookie = createMock(Cookie.class); - expect(cookie.getName()).andReturn("non-default").atLeastOnce(); - expect(cookie.getValue()).andReturn("bad token").atLeastOnce(); - - HttpServletRequest request = createMock(HttpServletRequest.class); - expect(request.getCookies()).andReturn(new Cookie[]{cookie}); - - replay(request, cookie); - - Assert.assertTrue(filter.shouldApply(request)); - - verify(request, cookie); - } - - @Test - public void testShouldApplyFalseMissingCookie() throws JOSEException { - JwtAuthenticationProperties properties = createTestProperties(); - JwtAuthenticationFilter filter = new JwtAuthenticationFilter(properties, null, null); - - Cookie cookie = createMock(Cookie.class); - expect(cookie.getName()).andReturn("some-other-cookie").atLeastOnce(); - - HttpServletRequest request = createMock(HttpServletRequest.class); - expect(request.getCookies()).andReturn(new Cookie[]{cookie}); - - replay(request, cookie); - - Assert.assertFalse(filter.shouldApply(request)); - - verify(request, cookie); - } - - @Test - public void testShouldApplyFalseNotEnabled() throws JOSEException { - JwtAuthenticationFilter filter = new JwtAuthenticationFilter((JwtAuthenticationProperties) null, null, null); - - HttpServletRequest request = createMock(HttpServletRequest.class); - - replay(request); - - Assert.assertFalse(filter.shouldApply(request)); - - verify(request); - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/553e4f9d/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationPropertiesTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationPropertiesTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationPropertiesTest.java deleted file mode 100644 index 144d90a..0000000 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/jwt/JwtAuthenticationPropertiesTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.apache.ambari.server.security.authorization.jwt; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -public class JwtAuthenticationPropertiesTest { - - @Test - public void testSetNullAudiences() { - JwtAuthenticationProperties jwtAuthenticationProperties = new JwtAuthenticationProperties(); - jwtAuthenticationProperties.setAudiencesString(null); - assertNull(jwtAuthenticationProperties.getAudiences()); - } - - @Test - public void testSetEmptyAudiences() { - JwtAuthenticationProperties jwtAuthenticationProperties = new JwtAuthenticationProperties(); - jwtAuthenticationProperties.setAudiencesString(""); - assertNull(jwtAuthenticationProperties.getAudiences()); - } - - @Test - public void testSetValidAudiences() { - String[] expectedAudiences = {"first", "second", "third"}; - JwtAuthenticationProperties jwtAuthenticationProperties = new JwtAuthenticationProperties(); - jwtAuthenticationProperties.setAudiencesString("first,second,third"); - assertNotNull(jwtAuthenticationProperties.getAudiences()); - assertArrayEquals(expectedAudiences, jwtAuthenticationProperties.getAudiences().toArray(new String[]{})); - } -}
