HADOOP-9866. convert hadoop-auth testcases requiring kerberos to use minikdc. (ywskycn via tucu)

git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1515658 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Alejandro Abdelnur 2013-08-19 23:04:23 +00:00
parent 540896b39e
commit 32bdd011ef
16 changed files with 356 additions and 328 deletions

View File

@ -33,7 +33,6 @@
<properties> <properties>
<maven.build.timestamp.format>yyyyMMdd</maven.build.timestamp.format> <maven.build.timestamp.format>yyyyMMdd</maven.build.timestamp.format>
<kerberos.realm>LOCALHOST</kerberos.realm>
</properties> </properties>
<dependencies> <dependencies>
@ -83,38 +82,15 @@
<artifactId>slf4j-log4j12</artifactId> <artifactId>slf4j-log4j12</artifactId>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-minikdc</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<testResources>
<testResource>
<directory>${basedir}/src/test/resources</directory>
<filtering>true</filtering>
<includes>
<include>krb5.conf</include>
</includes>
</testResource>
</testResources>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>always</forkMode>
<forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
<systemPropertyVariables>
<java.security.krb5.conf>${project.build.directory}/test-classes/krb5.conf</java.security.krb5.conf>
<kerberos.realm>${kerberos.realm}</kerberos.realm>
</systemPropertyVariables>
<excludes>
<exclude>**/${test.exclude}.java</exclude>
<exclude>${test.exclude.pattern}</exclude>
<exclude>**/TestKerberosAuth*.java</exclude>
<exclude>**/TestAltKerberosAuth*.java</exclude>
<exclude>**/Test*$*.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
@ -134,33 +110,6 @@
</build> </build>
<profiles> <profiles>
<profile>
<id>testKerberos</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>always</forkMode>
<forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
<systemPropertyVariables>
<java.security.krb5.conf>${project.build.directory}/test-classes/krb5.conf</java.security.krb5.conf>
<kerberos.realm>${kerberos.realm}</kerberos.realm>
</systemPropertyVariables>
<excludes>
<exclude>**/${test.exclude}.java</exclude>
<exclude>${test.exclude.pattern}</exclude>
<exclude>**/Test*$*.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile> <profile>
<id>docs</id> <id>docs</id>
<activation> <activation>

View File

@ -13,7 +13,6 @@
*/ */
package org.apache.hadoop.security.authentication; package org.apache.hadoop.security.authentication;
import javax.security.auth.Subject; import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal; import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry;
@ -26,6 +25,7 @@ import java.io.File;
import java.security.Principal; import java.security.Principal;
import java.security.PrivilegedActionException; import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction; import java.security.PrivilegedExceptionAction;
import java.util.UUID;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
@ -36,32 +36,23 @@ import java.util.concurrent.Callable;
* Test helper class for Java Kerberos setup. * Test helper class for Java Kerberos setup.
*/ */
public class KerberosTestUtils { public class KerberosTestUtils {
private static final String PREFIX = "hadoop-auth.test."; private static String keytabFile = new File(System.getProperty("test.dir", "target"),
UUID.randomUUID().toString()).toString();
public static final String REALM = PREFIX + "kerberos.realm";
public static final String CLIENT_PRINCIPAL = PREFIX + "kerberos.client.principal";
public static final String SERVER_PRINCIPAL = PREFIX + "kerberos.server.principal";
public static final String KEYTAB_FILE = PREFIX + "kerberos.keytab.file";
public static String getRealm() { public static String getRealm() {
return System.getProperty(REALM, "LOCALHOST"); return "EXAMPLE.COM";
} }
public static String getClientPrincipal() { public static String getClientPrincipal() {
return System.getProperty(CLIENT_PRINCIPAL, "client") + "@" + getRealm(); return "client@EXAMPLE.COM";
} }
public static String getServerPrincipal() { public static String getServerPrincipal() {
return System.getProperty(SERVER_PRINCIPAL, "HTTP/localhost") + "@" + getRealm(); return "HTTP/localhost@EXAMPLE.COM";
} }
public static String getKeytabFile() { public static String getKeytabFile() {
String keytabFile = return keytabFile;
new File(System.getProperty("user.home"), System.getProperty("user.name") + ".keytab").toString();
return System.getProperty(KEYTAB_FILE, keytabFile);
} }
private static class KerberosConfiguration extends Configuration { private static class KerberosConfiguration extends Configuration {

View File

@ -13,10 +13,7 @@
*/ */
package org.apache.hadoop.security.authentication.client; package org.apache.hadoop.security.authentication.client;
import junit.framework.Assert;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter; import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import junit.framework.TestCase;
import org.mockito.Mockito;
import org.mortbay.jetty.Server; import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.FilterHolder; import org.mortbay.jetty.servlet.FilterHolder;
@ -27,19 +24,20 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Writer; import java.io.Writer;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.URL; import java.net.URL;
import java.util.Properties; import java.util.Properties;
import org.junit.Assert;
public abstract class AuthenticatorTestCase extends TestCase { public class AuthenticatorTestCase {
private Server server; private Server server;
private String host = null; private String host = null;
private int port = -1; private int port = -1;
@ -151,18 +149,18 @@ public abstract class AuthenticatorTestCase extends TestCase {
writer.write(POST); writer.write(POST);
writer.close(); writer.close();
} }
assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
if (doPost) { if (doPost) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String echo = reader.readLine(); String echo = reader.readLine();
assertEquals(POST, echo); Assert.assertEquals(POST, echo);
assertNull(reader.readLine()); Assert.assertNull(reader.readLine());
} }
aUrl = new AuthenticatedURL(); aUrl = new AuthenticatedURL();
conn = aUrl.openConnection(url, token); conn = aUrl.openConnection(url, token);
conn.connect(); conn.connect();
assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
assertEquals(tokenStr, token.toString()); Assert.assertEquals(tokenStr, token.toString());
} finally { } finally {
stop(); stop();
} }

View File

@ -13,8 +13,8 @@
*/ */
package org.apache.hadoop.security.authentication.client; package org.apache.hadoop.security.authentication.client;
import junit.framework.Assert; import org.junit.Assert;
import junit.framework.TestCase; import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
@ -24,46 +24,48 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class TestAuthenticatedURL extends TestCase { public class TestAuthenticatedURL {
@Test
public void testToken() throws Exception { public void testToken() throws Exception {
AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.Token token = new AuthenticatedURL.Token();
assertFalse(token.isSet()); Assert.assertFalse(token.isSet());
token = new AuthenticatedURL.Token("foo"); token = new AuthenticatedURL.Token("foo");
assertTrue(token.isSet()); Assert.assertTrue(token.isSet());
assertEquals("foo", token.toString()); Assert.assertEquals("foo", token.toString());
AuthenticatedURL.Token token1 = new AuthenticatedURL.Token(); AuthenticatedURL.Token token1 = new AuthenticatedURL.Token();
AuthenticatedURL.Token token2 = new AuthenticatedURL.Token(); AuthenticatedURL.Token token2 = new AuthenticatedURL.Token();
assertEquals(token1.hashCode(), token2.hashCode()); Assert.assertEquals(token1.hashCode(), token2.hashCode());
assertTrue(token1.equals(token2)); Assert.assertTrue(token1.equals(token2));
token1 = new AuthenticatedURL.Token(); token1 = new AuthenticatedURL.Token();
token2 = new AuthenticatedURL.Token("foo"); token2 = new AuthenticatedURL.Token("foo");
assertNotSame(token1.hashCode(), token2.hashCode()); Assert.assertNotSame(token1.hashCode(), token2.hashCode());
assertFalse(token1.equals(token2)); Assert.assertFalse(token1.equals(token2));
token1 = new AuthenticatedURL.Token("foo"); token1 = new AuthenticatedURL.Token("foo");
token2 = new AuthenticatedURL.Token(); token2 = new AuthenticatedURL.Token();
assertNotSame(token1.hashCode(), token2.hashCode()); Assert.assertNotSame(token1.hashCode(), token2.hashCode());
assertFalse(token1.equals(token2)); Assert.assertFalse(token1.equals(token2));
token1 = new AuthenticatedURL.Token("foo"); token1 = new AuthenticatedURL.Token("foo");
token2 = new AuthenticatedURL.Token("foo"); token2 = new AuthenticatedURL.Token("foo");
assertEquals(token1.hashCode(), token2.hashCode()); Assert.assertEquals(token1.hashCode(), token2.hashCode());
assertTrue(token1.equals(token2)); Assert.assertTrue(token1.equals(token2));
token1 = new AuthenticatedURL.Token("bar"); token1 = new AuthenticatedURL.Token("bar");
token2 = new AuthenticatedURL.Token("foo"); token2 = new AuthenticatedURL.Token("foo");
assertNotSame(token1.hashCode(), token2.hashCode()); Assert.assertNotSame(token1.hashCode(), token2.hashCode());
assertFalse(token1.equals(token2)); Assert.assertFalse(token1.equals(token2));
token1 = new AuthenticatedURL.Token("foo"); token1 = new AuthenticatedURL.Token("foo");
token2 = new AuthenticatedURL.Token("bar"); token2 = new AuthenticatedURL.Token("bar");
assertNotSame(token1.hashCode(), token2.hashCode()); Assert.assertNotSame(token1.hashCode(), token2.hashCode());
assertFalse(token1.equals(token2)); Assert.assertFalse(token1.equals(token2));
} }
@Test
public void testInjectToken() throws Exception { public void testInjectToken() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.Token token = new AuthenticatedURL.Token();
@ -72,6 +74,7 @@ public class TestAuthenticatedURL extends TestCase {
Mockito.verify(conn).addRequestProperty(Mockito.eq("Cookie"), Mockito.anyString()); Mockito.verify(conn).addRequestProperty(Mockito.eq("Cookie"), Mockito.anyString());
} }
@Test
public void testExtractTokenOK() throws Exception { public void testExtractTokenOK() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
@ -87,9 +90,10 @@ public class TestAuthenticatedURL extends TestCase {
AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.Token token = new AuthenticatedURL.Token();
AuthenticatedURL.extractToken(conn, token); AuthenticatedURL.extractToken(conn, token);
assertEquals(tokenStr, token.toString()); Assert.assertEquals(tokenStr, token.toString());
} }
@Test
public void testExtractTokenFail() throws Exception { public void testExtractTokenFail() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
@ -106,15 +110,16 @@ public class TestAuthenticatedURL extends TestCase {
token.set("bar"); token.set("bar");
try { try {
AuthenticatedURL.extractToken(conn, token); AuthenticatedURL.extractToken(conn, token);
fail(); Assert.fail();
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
// Expected // Expected
Assert.assertFalse(token.isSet()); Assert.assertFalse(token.isSet());
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} }
} }
@Test
public void testConnectionConfigurator() throws Exception { public void testConnectionConfigurator() throws Exception {
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
Mockito.when(conn.getResponseCode()). Mockito.when(conn.getResponseCode()).

View File

@ -13,17 +13,33 @@
*/ */
package org.apache.hadoop.security.authentication.client; package org.apache.hadoop.security.authentication.client;
import org.apache.hadoop.minikdc.KerberosSecurityTestcase;
import org.apache.hadoop.security.authentication.KerberosTestUtils; import org.apache.hadoop.security.authentication.KerberosTestUtils;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter; import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler; import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler;
import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler; import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
public class TestKerberosAuthenticator extends AuthenticatorTestCase { public class TestKerberosAuthenticator extends KerberosSecurityTestcase {
@Before
public void setup() throws Exception {
// create keytab
File keytabFile = new File(KerberosTestUtils.getKeytabFile());
String clientPrincipal = KerberosTestUtils.getClientPrincipal();
String serverPrincipal = KerberosTestUtils.getServerPrincipal();
clientPrincipal = clientPrincipal.substring(0, clientPrincipal.lastIndexOf("@"));
serverPrincipal = serverPrincipal.substring(0, serverPrincipal.lastIndexOf("@"));
getKdc().createPrincipal(keytabFile, clientPrincipal, serverPrincipal);
}
private Properties getAuthenticationHandlerConfiguration() { private Properties getAuthenticationHandlerConfiguration() {
Properties props = new Properties(); Properties props = new Properties();
@ -35,57 +51,67 @@ public class TestKerberosAuthenticator extends AuthenticatorTestCase {
return props; return props;
} }
@Test(timeout=60000)
public void testFallbacktoPseudoAuthenticator() throws Exception { public void testFallbacktoPseudoAuthenticator() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
Properties props = new Properties(); Properties props = new Properties();
props.setProperty(AuthenticationFilter.AUTH_TYPE, "simple"); props.setProperty(AuthenticationFilter.AUTH_TYPE, "simple");
props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false"); props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false");
setAuthenticationHandlerConfig(props); auth.setAuthenticationHandlerConfig(props);
_testAuthentication(new KerberosAuthenticator(), false); auth._testAuthentication(new KerberosAuthenticator(), false);
} }
@Test(timeout=60000)
public void testFallbacktoPseudoAuthenticatorAnonymous() throws Exception { public void testFallbacktoPseudoAuthenticatorAnonymous() throws Exception {
AuthenticatorTestCase auth = new AuthenticatorTestCase();
Properties props = new Properties(); Properties props = new Properties();
props.setProperty(AuthenticationFilter.AUTH_TYPE, "simple"); props.setProperty(AuthenticationFilter.AUTH_TYPE, "simple");
props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "true"); props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "true");
setAuthenticationHandlerConfig(props); auth.setAuthenticationHandlerConfig(props);
_testAuthentication(new KerberosAuthenticator(), false); auth._testAuthentication(new KerberosAuthenticator(), false);
} }
@Test(timeout=60000)
public void testNotAuthenticated() throws Exception { public void testNotAuthenticated() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration()); AuthenticatorTestCase auth = new AuthenticatorTestCase();
start(); auth.setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration());
auth.start();
try { try {
URL url = new URL(getBaseURL()); URL url = new URL(auth.getBaseURL());
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect(); conn.connect();
assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
assertTrue(conn.getHeaderField(KerberosAuthenticator.WWW_AUTHENTICATE) != null); Assert.assertTrue(conn.getHeaderField(KerberosAuthenticator.WWW_AUTHENTICATE) != null);
} finally { } finally {
stop(); auth.stop();
} }
} }
@Test(timeout=60000)
public void testAuthentication() throws Exception { public void testAuthentication() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration()); final AuthenticatorTestCase auth = new AuthenticatorTestCase();
auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration());
KerberosTestUtils.doAsClient(new Callable<Void>() { KerberosTestUtils.doAsClient(new Callable<Void>() {
@Override @Override
public Void call() throws Exception { public Void call() throws Exception {
_testAuthentication(new KerberosAuthenticator(), false); auth._testAuthentication(new KerberosAuthenticator(), false);
return null; return null;
} }
}); });
} }
@Test(timeout=60000)
public void testAuthenticationPost() throws Exception { public void testAuthenticationPost() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration()); final AuthenticatorTestCase auth = new AuthenticatorTestCase();
auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration());
KerberosTestUtils.doAsClient(new Callable<Void>() { KerberosTestUtils.doAsClient(new Callable<Void>() {
@Override @Override
public Void call() throws Exception { public Void call() throws Exception {
_testAuthentication(new KerberosAuthenticator(), true); auth._testAuthentication(new KerberosAuthenticator(), true);
return null; return null;
} }
}); });
} }
} }

View File

@ -15,12 +15,14 @@ package org.apache.hadoop.security.authentication.client;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter; import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler; import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler;
import org.junit.Assert;
import org.junit.Test;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Properties; import java.util.Properties;
public class TestPseudoAuthenticator extends AuthenticatorTestCase { public class TestPseudoAuthenticator {
private Properties getAuthenticationHandlerConfiguration(boolean anonymousAllowed) { private Properties getAuthenticationHandlerConfiguration(boolean anonymousAllowed) {
Properties props = new Properties(); Properties props = new Properties();
@ -29,55 +31,74 @@ public class TestPseudoAuthenticator extends AuthenticatorTestCase {
return props; return props;
} }
@Test
public void testGetUserName() throws Exception { public void testGetUserName() throws Exception {
PseudoAuthenticator authenticator = new PseudoAuthenticator(); PseudoAuthenticator authenticator = new PseudoAuthenticator();
assertEquals(System.getProperty("user.name"), authenticator.getUserName()); Assert.assertEquals(System.getProperty("user.name"), authenticator.getUserName());
} }
@Test
public void testAnonymousAllowed() throws Exception { public void testAnonymousAllowed() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration(true)); AuthenticatorTestCase auth = new AuthenticatorTestCase();
start(); auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(true));
auth.start();
try { try {
URL url = new URL(getBaseURL()); URL url = new URL(auth.getBaseURL());
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect(); conn.connect();
assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
} finally { } finally {
stop(); auth.stop();
} }
} }
@Test
public void testAnonymousDisallowed() throws Exception { public void testAnonymousDisallowed() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration(false)); AuthenticatorTestCase auth = new AuthenticatorTestCase();
start(); auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(false));
auth.start();
try { try {
URL url = new URL(getBaseURL()); URL url = new URL(auth.getBaseURL());
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect(); conn.connect();
assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
} finally { } finally {
stop(); auth.stop();
} }
} }
@Test
public void testAuthenticationAnonymousAllowed() throws Exception { public void testAuthenticationAnonymousAllowed() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration(true)); AuthenticatorTestCase auth = new AuthenticatorTestCase();
_testAuthentication(new PseudoAuthenticator(), false); auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(true));
auth._testAuthentication(new PseudoAuthenticator(), false);
} }
@Test
public void testAuthenticationAnonymousDisallowed() throws Exception { public void testAuthenticationAnonymousDisallowed() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration(false)); AuthenticatorTestCase auth = new AuthenticatorTestCase();
_testAuthentication(new PseudoAuthenticator(), false); auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(false));
auth._testAuthentication(new PseudoAuthenticator(), false);
} }
@Test
public void testAuthenticationAnonymousAllowedWithPost() throws Exception { public void testAuthenticationAnonymousAllowedWithPost() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration(true)); AuthenticatorTestCase auth = new AuthenticatorTestCase();
_testAuthentication(new PseudoAuthenticator(), true); auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(true));
auth._testAuthentication(new PseudoAuthenticator(), true);
} }
@Test
public void testAuthenticationAnonymousDisallowedWithPost() throws Exception { public void testAuthenticationAnonymousDisallowedWithPost() throws Exception {
setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration(false)); AuthenticatorTestCase auth = new AuthenticatorTestCase();
_testAuthentication(new PseudoAuthenticator(), true); auth.setAuthenticationHandlerConfig(
getAuthenticationHandlerConfiguration(false));
auth._testAuthentication(new PseudoAuthenticator(), true);
} }
} }

View File

@ -18,6 +18,8 @@ import java.util.Properties;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
public class TestAltKerberosAuthenticationHandler public class TestAltKerberosAuthenticationHandler
@ -45,6 +47,7 @@ public class TestAltKerberosAuthenticationHandler
return AltKerberosAuthenticationHandler.TYPE; return AltKerberosAuthenticationHandler.TYPE;
} }
@Test(timeout=60000)
public void testAlternateAuthenticationAsBrowser() throws Exception { public void testAlternateAuthenticationAsBrowser() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
@ -54,11 +57,12 @@ public class TestAltKerberosAuthenticationHandler
Mockito.when(request.getHeader("User-Agent")).thenReturn("Some Browser"); Mockito.when(request.getHeader("User-Agent")).thenReturn("Some Browser");
AuthenticationToken token = handler.authenticate(request, response); AuthenticationToken token = handler.authenticate(request, response);
assertEquals("A", token.getUserName()); Assert.assertEquals("A", token.getUserName());
assertEquals("B", token.getName()); Assert.assertEquals("B", token.getName());
assertEquals(getExpectedType(), token.getType()); Assert.assertEquals(getExpectedType(), token.getType());
} }
@Test(timeout=60000)
public void testNonDefaultNonBrowserUserAgentAsBrowser() throws Exception { public void testNonDefaultNonBrowserUserAgentAsBrowser() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
@ -81,11 +85,12 @@ public class TestAltKerberosAuthenticationHandler
Mockito.when(request.getHeader("User-Agent")).thenReturn("blah"); Mockito.when(request.getHeader("User-Agent")).thenReturn("blah");
// Should use alt authentication // Should use alt authentication
AuthenticationToken token = handler.authenticate(request, response); AuthenticationToken token = handler.authenticate(request, response);
assertEquals("A", token.getUserName()); Assert.assertEquals("A", token.getUserName());
assertEquals("B", token.getName()); Assert.assertEquals("B", token.getName());
assertEquals(getExpectedType(), token.getType()); Assert.assertEquals(getExpectedType(), token.getType());
} }
@Test(timeout=60000)
public void testNonDefaultNonBrowserUserAgentAsNonBrowser() throws Exception { public void testNonDefaultNonBrowserUserAgentAsNonBrowser() throws Exception {
if (handler != null) { if (handler != null) {
handler.destroy(); handler.destroy();

View File

@ -16,7 +16,8 @@ package org.apache.hadoop.security.authentication.server;
import org.apache.hadoop.security.authentication.client.AuthenticatedURL; import org.apache.hadoop.security.authentication.client.AuthenticatedURL;
import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.hadoop.security.authentication.util.Signer; import org.apache.hadoop.security.authentication.util.Signer;
import junit.framework.TestCase; import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
@ -34,8 +35,9 @@ import java.util.Arrays;
import java.util.Properties; import java.util.Properties;
import java.util.Vector; import java.util.Vector;
public class TestAuthenticationFilter extends TestCase { public class TestAuthenticationFilter {
@Test
public void testGetConfiguration() throws Exception { public void testGetConfiguration() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
FilterConfig config = Mockito.mock(FilterConfig.class); FilterConfig config = Mockito.mock(FilterConfig.class);
@ -43,27 +45,28 @@ public class TestAuthenticationFilter extends TestCase {
Mockito.when(config.getInitParameter("a")).thenReturn("A"); Mockito.when(config.getInitParameter("a")).thenReturn("A");
Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList("a")).elements()); Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList("a")).elements());
Properties props = filter.getConfiguration("", config); Properties props = filter.getConfiguration("", config);
assertEquals("A", props.getProperty("a")); Assert.assertEquals("A", props.getProperty("a"));
config = Mockito.mock(FilterConfig.class); config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("foo"); Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("foo");
Mockito.when(config.getInitParameter("foo.a")).thenReturn("A"); Mockito.when(config.getInitParameter("foo.a")).thenReturn("A");
Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList("foo.a")).elements()); Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList("foo.a")).elements());
props = filter.getConfiguration("foo.", config); props = filter.getConfiguration("foo.", config);
assertEquals("A", props.getProperty("a")); Assert.assertEquals("A", props.getProperty("a"));
} }
@Test
public void testInitEmpty() throws Exception { public void testInitEmpty() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
FilterConfig config = Mockito.mock(FilterConfig.class); FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>().elements()); Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>().elements());
filter.init(config); filter.init(config);
fail(); Assert.fail();
} catch (ServletException ex) { } catch (ServletException ex) {
// Expected // Expected
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} finally { } finally {
filter.destroy(); filter.destroy();
} }
@ -126,6 +129,7 @@ public class TestAuthenticationFilter extends TestCase {
} }
} }
@Test
public void testInit() throws Exception { public void testInit() throws Exception {
// minimal configuration & simple auth handler (Pseudo) // minimal configuration & simple auth handler (Pseudo)
@ -138,11 +142,11 @@ public class TestAuthenticationFilter extends TestCase {
new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE, new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.AUTH_TOKEN_VALIDITY)).elements()); AuthenticationFilter.AUTH_TOKEN_VALIDITY)).elements());
filter.init(config); filter.init(config);
assertEquals(PseudoAuthenticationHandler.class, filter.getAuthenticationHandler().getClass()); Assert.assertEquals(PseudoAuthenticationHandler.class, filter.getAuthenticationHandler().getClass());
assertTrue(filter.isRandomSecret()); Assert.assertTrue(filter.isRandomSecret());
assertNull(filter.getCookieDomain()); Assert.assertNull(filter.getCookieDomain());
assertNull(filter.getCookiePath()); Assert.assertNull(filter.getCookiePath());
assertEquals(1000, filter.getValidity()); Assert.assertEquals(1000, filter.getValidity());
} finally { } finally {
filter.destroy(); filter.destroy();
} }
@ -157,7 +161,7 @@ public class TestAuthenticationFilter extends TestCase {
new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE, new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET)).elements()); AuthenticationFilter.SIGNATURE_SECRET)).elements());
filter.init(config); filter.init(config);
assertFalse(filter.isRandomSecret()); Assert.assertFalse(filter.isRandomSecret());
} finally { } finally {
filter.destroy(); filter.destroy();
} }
@ -174,13 +178,12 @@ public class TestAuthenticationFilter extends TestCase {
AuthenticationFilter.COOKIE_DOMAIN, AuthenticationFilter.COOKIE_DOMAIN,
AuthenticationFilter.COOKIE_PATH)).elements()); AuthenticationFilter.COOKIE_PATH)).elements());
filter.init(config); filter.init(config);
assertEquals(".foo.com", filter.getCookieDomain()); Assert.assertEquals(".foo.com", filter.getCookieDomain());
assertEquals("/bar", filter.getCookiePath()); Assert.assertEquals("/bar", filter.getCookiePath());
} finally { } finally {
filter.destroy(); filter.destroy();
} }
// authentication handler lifecycle, and custom impl // authentication handler lifecycle, and custom impl
DummyAuthenticationHandler.reset(); DummyAuthenticationHandler.reset();
filter = new AuthenticationFilter(); filter = new AuthenticationFilter();
@ -195,10 +198,10 @@ public class TestAuthenticationFilter extends TestCase {
Arrays.asList(AuthenticationFilter.AUTH_TYPE, Arrays.asList(AuthenticationFilter.AUTH_TYPE,
"management.operation.return")).elements()); "management.operation.return")).elements());
filter.init(config); filter.init(config);
assertTrue(DummyAuthenticationHandler.init); Assert.assertTrue(DummyAuthenticationHandler.init);
} finally { } finally {
filter.destroy(); filter.destroy();
assertTrue(DummyAuthenticationHandler.destroy); Assert.assertTrue(DummyAuthenticationHandler.destroy);
} }
// kerberos auth handler // kerberos auth handler
@ -212,11 +215,12 @@ public class TestAuthenticationFilter extends TestCase {
} catch (ServletException ex) { } catch (ServletException ex) {
// Expected // Expected
} finally { } finally {
assertEquals(KerberosAuthenticationHandler.class, filter.getAuthenticationHandler().getClass()); Assert.assertEquals(KerberosAuthenticationHandler.class, filter.getAuthenticationHandler().getClass());
filter.destroy(); filter.destroy();
} }
} }
@Test
public void testGetRequestURL() throws Exception { public void testGetRequestURL() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -235,12 +239,13 @@ public class TestAuthenticationFilter extends TestCase {
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
Mockito.when(request.getQueryString()).thenReturn("a=A&b=B"); Mockito.when(request.getQueryString()).thenReturn("a=A&b=B");
assertEquals("http://foo:8080/bar?a=A&b=B", filter.getRequestURL(request)); Assert.assertEquals("http://foo:8080/bar?a=A&b=B", filter.getRequestURL(request));
} finally { } finally {
filter.destroy(); filter.destroy();
} }
} }
@Test
public void testGetToken() throws Exception { public void testGetToken() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -268,12 +273,13 @@ public class TestAuthenticationFilter extends TestCase {
AuthenticationToken newToken = filter.getToken(request); AuthenticationToken newToken = filter.getToken(request);
assertEquals(token.toString(), newToken.toString()); Assert.assertEquals(token.toString(), newToken.toString());
} finally { } finally {
filter.destroy(); filter.destroy();
} }
} }
@Test
public void testGetTokenExpired() throws Exception { public void testGetTokenExpired() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -300,17 +306,18 @@ public class TestAuthenticationFilter extends TestCase {
try { try {
filter.getToken(request); filter.getToken(request);
fail(); Assert.fail();
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
// Expected // Expected
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} }
} finally { } finally {
filter.destroy(); filter.destroy();
} }
} }
@Test
public void testGetTokenInvalidType() throws Exception { public void testGetTokenInvalidType() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -338,17 +345,18 @@ public class TestAuthenticationFilter extends TestCase {
try { try {
filter.getToken(request); filter.getToken(request);
fail(); Assert.fail();
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
// Expected // Expected
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} }
} finally { } finally {
filter.destroy(); filter.destroy();
} }
} }
@Test
public void testDoFilterNotAuthenticated() throws Exception { public void testDoFilterNotAuthenticated() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -374,7 +382,7 @@ public class TestAuthenticationFilter extends TestCase {
new Answer<Object>() { new Answer<Object>() {
@Override @Override
public Object answer(InvocationOnMock invocation) throws Throwable { public Object answer(InvocationOnMock invocation) throws Throwable {
fail(); Assert.fail();
return null; return null;
} }
} }
@ -468,27 +476,27 @@ public class TestAuthenticationFilter extends TestCase {
Mockito.verify(response, Mockito.never()). Mockito.verify(response, Mockito.never()).
addCookie(Mockito.any(Cookie.class)); addCookie(Mockito.any(Cookie.class));
} else { } else {
assertNotNull(setCookie[0]); Assert.assertNotNull(setCookie[0]);
assertEquals(AuthenticatedURL.AUTH_COOKIE, setCookie[0].getName()); Assert.assertEquals(AuthenticatedURL.AUTH_COOKIE, setCookie[0].getName());
assertTrue(setCookie[0].getValue().contains("u=")); Assert.assertTrue(setCookie[0].getValue().contains("u="));
assertTrue(setCookie[0].getValue().contains("p=")); Assert.assertTrue(setCookie[0].getValue().contains("p="));
assertTrue(setCookie[0].getValue().contains("t=")); Assert.assertTrue(setCookie[0].getValue().contains("t="));
assertTrue(setCookie[0].getValue().contains("e=")); Assert.assertTrue(setCookie[0].getValue().contains("e="));
assertTrue(setCookie[0].getValue().contains("s=")); Assert.assertTrue(setCookie[0].getValue().contains("s="));
assertTrue(calledDoFilter[0]); Assert.assertTrue(calledDoFilter[0]);
Signer signer = new Signer("secret".getBytes()); Signer signer = new Signer("secret".getBytes());
String value = signer.verifyAndExtract(setCookie[0].getValue()); String value = signer.verifyAndExtract(setCookie[0].getValue());
AuthenticationToken token = AuthenticationToken.parse(value); AuthenticationToken token = AuthenticationToken.parse(value);
assertEquals(System.currentTimeMillis() + 1000 * 1000, Assert.assertEquals(System.currentTimeMillis() + 1000 * 1000,
token.getExpires(), 100); token.getExpires(), 100);
if (withDomainPath) { if (withDomainPath) {
assertEquals(".foo.com", setCookie[0].getDomain()); Assert.assertEquals(".foo.com", setCookie[0].getDomain());
assertEquals("/bar", setCookie[0].getPath()); Assert.assertEquals("/bar", setCookie[0].getPath());
} else { } else {
assertNull(setCookie[0].getDomain()); Assert.assertNull(setCookie[0].getDomain());
assertNull(setCookie[0].getPath()); Assert.assertNull(setCookie[0].getPath());
} }
} }
} finally { } finally {
@ -496,22 +504,27 @@ public class TestAuthenticationFilter extends TestCase {
} }
} }
@Test
public void testDoFilterAuthentication() throws Exception { public void testDoFilterAuthentication() throws Exception {
_testDoFilterAuthentication(false, false, false); _testDoFilterAuthentication(false, false, false);
} }
@Test
public void testDoFilterAuthenticationImmediateExpiration() throws Exception { public void testDoFilterAuthenticationImmediateExpiration() throws Exception {
_testDoFilterAuthentication(false, false, true); _testDoFilterAuthentication(false, false, true);
} }
@Test
public void testDoFilterAuthenticationWithInvalidToken() throws Exception { public void testDoFilterAuthenticationWithInvalidToken() throws Exception {
_testDoFilterAuthentication(false, true, false); _testDoFilterAuthentication(false, true, false);
} }
@Test
public void testDoFilterAuthenticationWithDomainPath() throws Exception { public void testDoFilterAuthenticationWithDomainPath() throws Exception {
_testDoFilterAuthentication(true, false, false); _testDoFilterAuthentication(true, false, false);
} }
@Test
public void testDoFilterAuthenticated() throws Exception { public void testDoFilterAuthenticated() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -547,8 +560,8 @@ public class TestAuthenticationFilter extends TestCase {
public Object answer(InvocationOnMock invocation) throws Throwable { public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments(); Object[] args = invocation.getArguments();
HttpServletRequest request = (HttpServletRequest) args[0]; HttpServletRequest request = (HttpServletRequest) args[0];
assertEquals("u", request.getRemoteUser()); Assert.assertEquals("u", request.getRemoteUser());
assertEquals("p", request.getUserPrincipal().getName()); Assert.assertEquals("p", request.getUserPrincipal().getName());
return null; return null;
} }
} }
@ -561,6 +574,7 @@ public class TestAuthenticationFilter extends TestCase {
} }
} }
@Test
public void testDoFilterAuthenticatedExpired() throws Exception { public void testDoFilterAuthenticatedExpired() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -594,7 +608,7 @@ public class TestAuthenticationFilter extends TestCase {
new Answer<Object>() { new Answer<Object>() {
@Override @Override
public Object answer(InvocationOnMock invocation) throws Throwable { public Object answer(InvocationOnMock invocation) throws Throwable {
fail(); Assert.fail();
return null; return null;
} }
} }
@ -616,15 +630,15 @@ public class TestAuthenticationFilter extends TestCase {
Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString()); Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString());
assertNotNull(setCookie[0]); Assert.assertNotNull(setCookie[0]);
assertEquals(AuthenticatedURL.AUTH_COOKIE, setCookie[0].getName()); Assert.assertEquals(AuthenticatedURL.AUTH_COOKIE, setCookie[0].getName());
assertEquals("", setCookie[0].getValue()); Assert.assertEquals("", setCookie[0].getValue());
} finally { } finally {
filter.destroy(); filter.destroy();
} }
} }
@Test
public void testDoFilterAuthenticatedInvalidType() throws Exception { public void testDoFilterAuthenticatedInvalidType() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {
@ -658,7 +672,7 @@ public class TestAuthenticationFilter extends TestCase {
new Answer<Object>() { new Answer<Object>() {
@Override @Override
public Object answer(InvocationOnMock invocation) throws Throwable { public Object answer(InvocationOnMock invocation) throws Throwable {
fail(); Assert.fail();
return null; return null;
} }
} }
@ -680,14 +694,15 @@ public class TestAuthenticationFilter extends TestCase {
Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString()); Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.anyString());
assertNotNull(setCookie[0]); Assert.assertNotNull(setCookie[0]);
assertEquals(AuthenticatedURL.AUTH_COOKIE, setCookie[0].getName()); Assert.assertEquals(AuthenticatedURL.AUTH_COOKIE, setCookie[0].getName());
assertEquals("", setCookie[0].getValue()); Assert.assertEquals("", setCookie[0].getValue());
} finally { } finally {
filter.destroy(); filter.destroy();
} }
} }
@Test
public void testManagementOperation() throws Exception { public void testManagementOperation() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(); AuthenticationFilter filter = new AuthenticationFilter();
try { try {

View File

@ -14,98 +14,104 @@
package org.apache.hadoop.security.authentication.server; package org.apache.hadoop.security.authentication.server;
import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.apache.hadoop.security.authentication.client.AuthenticationException;
import junit.framework.TestCase; import org.junit.Assert;
import org.junit.Test;
public class TestAuthenticationToken extends TestCase { public class TestAuthenticationToken {
@Test
public void testAnonymous() { public void testAnonymous() {
assertNotNull(AuthenticationToken.ANONYMOUS); Assert.assertNotNull(AuthenticationToken.ANONYMOUS);
assertEquals(null, AuthenticationToken.ANONYMOUS.getUserName()); Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getUserName());
assertEquals(null, AuthenticationToken.ANONYMOUS.getName()); Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getName());
assertEquals(null, AuthenticationToken.ANONYMOUS.getType()); Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getType());
assertEquals(-1, AuthenticationToken.ANONYMOUS.getExpires()); Assert.assertEquals(-1, AuthenticationToken.ANONYMOUS.getExpires());
assertFalse(AuthenticationToken.ANONYMOUS.isExpired()); Assert.assertFalse(AuthenticationToken.ANONYMOUS.isExpired());
} }
@Test
public void testConstructor() throws Exception { public void testConstructor() throws Exception {
try { try {
new AuthenticationToken(null, "p", "t"); new AuthenticationToken(null, "p", "t");
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
try { try {
new AuthenticationToken("", "p", "t"); new AuthenticationToken("", "p", "t");
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
try { try {
new AuthenticationToken("u", null, "t"); new AuthenticationToken("u", null, "t");
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
try { try {
new AuthenticationToken("u", "", "t"); new AuthenticationToken("u", "", "t");
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
try { try {
new AuthenticationToken("u", "p", null); new AuthenticationToken("u", "p", null);
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
try { try {
new AuthenticationToken("u", "p", ""); new AuthenticationToken("u", "p", "");
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
new AuthenticationToken("u", "p", "t"); new AuthenticationToken("u", "p", "t");
} }
@Test
public void testGetters() throws Exception { public void testGetters() throws Exception {
long expires = System.currentTimeMillis() + 50; long expires = System.currentTimeMillis() + 50;
AuthenticationToken token = new AuthenticationToken("u", "p", "t"); AuthenticationToken token = new AuthenticationToken("u", "p", "t");
token.setExpires(expires); token.setExpires(expires);
assertEquals("u", token.getUserName()); Assert.assertEquals("u", token.getUserName());
assertEquals("p", token.getName()); Assert.assertEquals("p", token.getName());
assertEquals("t", token.getType()); Assert.assertEquals("t", token.getType());
assertEquals(expires, token.getExpires()); Assert.assertEquals(expires, token.getExpires());
assertFalse(token.isExpired()); Assert.assertFalse(token.isExpired());
Thread.sleep(51); Thread.sleep(51);
assertTrue(token.isExpired()); Assert.assertTrue(token.isExpired());
} }
@Test
public void testToStringAndParse() throws Exception { public void testToStringAndParse() throws Exception {
long expires = System.currentTimeMillis() + 50; long expires = System.currentTimeMillis() + 50;
AuthenticationToken token = new AuthenticationToken("u", "p", "t"); AuthenticationToken token = new AuthenticationToken("u", "p", "t");
token.setExpires(expires); token.setExpires(expires);
String str = token.toString(); String str = token.toString();
token = AuthenticationToken.parse(str); token = AuthenticationToken.parse(str);
assertEquals("p", token.getName()); Assert.assertEquals("p", token.getName());
assertEquals("t", token.getType()); Assert.assertEquals("t", token.getType());
assertEquals(expires, token.getExpires()); Assert.assertEquals(expires, token.getExpires());
assertFalse(token.isExpired()); Assert.assertFalse(token.isExpired());
Thread.sleep(51); Thread.sleep(51);
assertTrue(token.isExpired()); Assert.assertTrue(token.isExpired());
} }
@Test
public void testParseInvalid() throws Exception { public void testParseInvalid() throws Exception {
long expires = System.currentTimeMillis() + 50; long expires = System.currentTimeMillis() + 50;
AuthenticationToken token = new AuthenticationToken("u", "p", "t"); AuthenticationToken token = new AuthenticationToken("u", "p", "t");
@ -114,11 +120,11 @@ public class TestAuthenticationToken extends TestCase {
str = str.substring(0, str.indexOf("e=")); str = str.substring(0, str.indexOf("e="));
try { try {
AuthenticationToken.parse(str); AuthenticationToken.parse(str);
fail(); Assert.fail();
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
// Expected // Expected
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} }
} }
} }

View File

@ -13,25 +13,31 @@
*/ */
package org.apache.hadoop.security.authentication.server; package org.apache.hadoop.security.authentication.server;
import org.apache.hadoop.minikdc.KerberosSecurityTestcase;
import org.apache.hadoop.security.authentication.KerberosTestUtils; import org.apache.hadoop.security.authentication.KerberosTestUtils;
import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.hadoop.security.authentication.client.KerberosAuthenticator; import org.apache.hadoop.security.authentication.client.KerberosAuthenticator;
import junit.framework.TestCase;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.security.authentication.util.KerberosName; import org.apache.hadoop.security.authentication.util.KerberosName;
import org.apache.hadoop.security.authentication.util.KerberosUtil; import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName; import org.ietf.jgss.GSSName;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.ietf.jgss.Oid; import org.ietf.jgss.Oid;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
public class TestKerberosAuthenticationHandler extends TestCase { public class TestKerberosAuthenticationHandler
extends KerberosSecurityTestcase {
protected KerberosAuthenticationHandler handler; protected KerberosAuthenticationHandler handler;
@ -54,9 +60,16 @@ public class TestKerberosAuthenticationHandler extends TestCase {
return props; return props;
} }
@Override @Before
protected void setUp() throws Exception { public void setup() throws Exception {
super.setUp(); // create keytab
File keytabFile = new File(KerberosTestUtils.getKeytabFile());
String clientPrincipal = KerberosTestUtils.getClientPrincipal();
String serverPrincipal = KerberosTestUtils.getServerPrincipal();
clientPrincipal = clientPrincipal.substring(0, clientPrincipal.lastIndexOf("@"));
serverPrincipal = serverPrincipal.substring(0, serverPrincipal.lastIndexOf("@"));
getKdc().createPrincipal(keytabFile, clientPrincipal, serverPrincipal);
// handler
handler = getNewAuthenticationHandler(); handler = getNewAuthenticationHandler();
Properties props = getDefaultProperties(); Properties props = getDefaultProperties();
try { try {
@ -67,18 +80,10 @@ public class TestKerberosAuthenticationHandler extends TestCase {
} }
} }
@Override @Test(timeout=60000)
protected void tearDown() throws Exception {
if (handler != null) {
handler.destroy();
handler = null;
}
super.tearDown();
}
public void testNameRules() throws Exception { public void testNameRules() throws Exception {
KerberosName kn = new KerberosName(KerberosTestUtils.getServerPrincipal()); KerberosName kn = new KerberosName(KerberosTestUtils.getServerPrincipal());
assertEquals(KerberosTestUtils.getRealm(), kn.getRealm()); Assert.assertEquals(KerberosTestUtils.getRealm(), kn.getRealm());
//destroy handler created in setUp() //destroy handler created in setUp()
handler.destroy(); handler.destroy();
@ -93,30 +98,32 @@ public class TestKerberosAuthenticationHandler extends TestCase {
} catch (Exception ex) { } catch (Exception ex) {
} }
kn = new KerberosName("bar@BAR"); kn = new KerberosName("bar@BAR");
assertEquals("bar", kn.getShortName()); Assert.assertEquals("bar", kn.getShortName());
kn = new KerberosName("bar@FOO"); kn = new KerberosName("bar@FOO");
try { try {
kn.getShortName(); kn.getShortName();
fail(); Assert.fail();
} }
catch (Exception ex) { catch (Exception ex) {
} }
} }
@Test(timeout=60000)
public void testInit() throws Exception { public void testInit() throws Exception {
assertEquals(KerberosTestUtils.getServerPrincipal(), handler.getPrincipal()); Assert.assertEquals(KerberosTestUtils.getServerPrincipal(), handler.getPrincipal());
assertEquals(KerberosTestUtils.getKeytabFile(), handler.getKeytab()); Assert.assertEquals(KerberosTestUtils.getKeytabFile(), handler.getKeytab());
} }
@Test(timeout=60000)
public void testType() throws Exception { public void testType() throws Exception {
assertEquals(getExpectedType(), handler.getType()); Assert.assertEquals(getExpectedType(), handler.getType());
} }
public void testRequestWithoutAuthorization() throws Exception { public void testRequestWithoutAuthorization() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
assertNull(handler.authenticate(request, response)); Assert.assertNull(handler.authenticate(request, response));
Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} }
@ -126,11 +133,12 @@ public class TestKerberosAuthenticationHandler extends TestCase {
HttpServletResponse response = Mockito.mock(HttpServletResponse.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)).thenReturn("invalid"); Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)).thenReturn("invalid");
assertNull(handler.authenticate(request, response)); Assert.assertNull(handler.authenticate(request, response));
Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} }
@Test(timeout=60000)
public void testRequestWithIncompleteAuthorization() throws Exception { public void testRequestWithIncompleteAuthorization() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
@ -139,15 +147,14 @@ public class TestKerberosAuthenticationHandler extends TestCase {
.thenReturn(KerberosAuthenticator.NEGOTIATE); .thenReturn(KerberosAuthenticator.NEGOTIATE);
try { try {
handler.authenticate(request, response); handler.authenticate(request, response);
fail(); Assert.fail();
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
// Expected // Expected
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} }
} }
public void testRequestWithAuthorization() throws Exception { public void testRequestWithAuthorization() throws Exception {
String token = KerberosTestUtils.doAsClient(new Callable<String>() { String token = KerberosTestUtils.doAsClient(new Callable<String>() {
@Override @Override
@ -191,9 +198,9 @@ public class TestKerberosAuthenticationHandler extends TestCase {
Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName()); Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName())); Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
assertEquals(getExpectedType(), authToken.getType()); Assert.assertEquals(getExpectedType(), authToken.getType());
} else { } else {
Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE), Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*")); Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
@ -213,12 +220,19 @@ public class TestKerberosAuthenticationHandler extends TestCase {
try { try {
handler.authenticate(request, response); handler.authenticate(request, response);
fail(); Assert.fail();
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
// Expected // Expected
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} }
} }
@After
public void tearDown() throws Exception {
if (handler != null) {
handler.destroy();
handler = null;
}
}
} }

View File

@ -14,33 +14,37 @@
package org.apache.hadoop.security.authentication.server; package org.apache.hadoop.security.authentication.server;
import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.apache.hadoop.security.authentication.client.AuthenticationException;
import junit.framework.TestCase;
import org.apache.hadoop.security.authentication.client.PseudoAuthenticator; import org.apache.hadoop.security.authentication.client.PseudoAuthenticator;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.util.Properties; import java.util.Properties;
public class TestPseudoAuthenticationHandler extends TestCase { public class TestPseudoAuthenticationHandler {
@Test
public void testInit() throws Exception { public void testInit() throws Exception {
PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler(); PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler();
try { try {
Properties props = new Properties(); Properties props = new Properties();
props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false"); props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false");
handler.init(props); handler.init(props);
assertEquals(false, handler.getAcceptAnonymous()); Assert.assertEquals(false, handler.getAcceptAnonymous());
} finally { } finally {
handler.destroy(); handler.destroy();
} }
} }
@Test
public void testType() throws Exception { public void testType() throws Exception {
PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler(); PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler();
assertEquals(PseudoAuthenticationHandler.TYPE, handler.getType()); Assert.assertEquals(PseudoAuthenticationHandler.TYPE, handler.getType());
} }
@Test
public void testAnonymousOn() throws Exception { public void testAnonymousOn() throws Exception {
PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler(); PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler();
try { try {
@ -53,12 +57,13 @@ public class TestPseudoAuthenticationHandler extends TestCase {
AuthenticationToken token = handler.authenticate(request, response); AuthenticationToken token = handler.authenticate(request, response);
assertEquals(AuthenticationToken.ANONYMOUS, token); Assert.assertEquals(AuthenticationToken.ANONYMOUS, token);
} finally { } finally {
handler.destroy(); handler.destroy();
} }
} }
@Test
public void testAnonymousOff() throws Exception { public void testAnonymousOff() throws Exception {
PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler(); PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler();
try { try {
@ -70,11 +75,11 @@ public class TestPseudoAuthenticationHandler extends TestCase {
HttpServletResponse response = Mockito.mock(HttpServletResponse.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
handler.authenticate(request, response); handler.authenticate(request, response);
fail(); Assert.fail();
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
// Expected // Expected
} catch (Exception ex) { } catch (Exception ex) {
fail(); Assert.fail();
} finally { } finally {
handler.destroy(); handler.destroy();
} }
@ -93,19 +98,21 @@ public class TestPseudoAuthenticationHandler extends TestCase {
AuthenticationToken token = handler.authenticate(request, response); AuthenticationToken token = handler.authenticate(request, response);
assertNotNull(token); Assert.assertNotNull(token);
assertEquals("user", token.getUserName()); Assert.assertEquals("user", token.getUserName());
assertEquals("user", token.getName()); Assert.assertEquals("user", token.getName());
assertEquals(PseudoAuthenticationHandler.TYPE, token.getType()); Assert.assertEquals(PseudoAuthenticationHandler.TYPE, token.getType());
} finally { } finally {
handler.destroy(); handler.destroy();
} }
} }
@Test
public void testUserNameAnonymousOff() throws Exception { public void testUserNameAnonymousOff() throws Exception {
_testUserName(false); _testUserName(false);
} }
@Test
public void testUserNameAnonymousOn() throws Exception { public void testUserNameAnonymousOn() throws Exception {
_testUserName(true); _testUserName(true);
} }

View File

@ -21,14 +21,19 @@ package org.apache.hadoop.security.authentication.util;
import java.io.IOException; import java.io.IOException;
import org.apache.hadoop.security.authentication.KerberosTestUtils; import org.apache.hadoop.security.authentication.KerberosTestUtils;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Assert;
public class TestKerberosName { public class TestKerberosName {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
System.setProperty("java.security.krb5.realm", KerberosTestUtils.getRealm());
System.setProperty("java.security.krb5.kdc", "localhost:88");
String rules = String rules =
"RULE:[1:$1@$0](.*@YAHOO\\.COM)s/@.*//\n" + "RULE:[1:$1@$0](.*@YAHOO\\.COM)s/@.*//\n" +
"RULE:[2:$1](johndoe)s/^.*$/guest/\n" + "RULE:[2:$1](johndoe)s/^.*$/guest/\n" +
@ -44,7 +49,7 @@ public class TestKerberosName {
KerberosName nm = new KerberosName(from); KerberosName nm = new KerberosName(from);
String simple = nm.getShortName(); String simple = nm.getShortName();
System.out.println("to " + simple); System.out.println("to " + simple);
assertEquals("short name incorrect", to, simple); Assert.assertEquals("short name incorrect", to, simple);
} }
@Test @Test
@ -61,7 +66,7 @@ public class TestKerberosName {
System.out.println("Checking " + name + " to ensure it is bad."); System.out.println("Checking " + name + " to ensure it is bad.");
try { try {
new KerberosName(name); new KerberosName(name);
fail("didn't get exception for " + name); Assert.fail("didn't get exception for " + name);
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
// PASS // PASS
} }
@ -72,7 +77,7 @@ public class TestKerberosName {
KerberosName nm = new KerberosName(from); KerberosName nm = new KerberosName(from);
try { try {
nm.getShortName(); nm.getShortName();
fail("didn't get exception for " + from); Assert.fail("didn't get exception for " + from);
} catch (IOException ie) { } catch (IOException ie) {
// PASS // PASS
} }
@ -85,4 +90,10 @@ public class TestKerberosName {
checkBadTranslation("foo@ACME.COM"); checkBadTranslation("foo@ACME.COM");
checkBadTranslation("root/joe@FOO.COM"); checkBadTranslation("root/joe@FOO.COM");
} }
@After
public void clear() {
System.clearProperty("java.security.krb5.realm");
System.clearProperty("java.security.krb5.kdc");
}
} }

View File

@ -16,11 +16,10 @@
*/ */
package org.apache.hadoop.security.authentication.util; package org.apache.hadoop.security.authentication.util;
import static org.junit.Assert.*; import org.junit.Assert;
import java.io.IOException; import java.io.IOException;
import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.junit.Test; import org.junit.Test;
public class TestKerberosUtil { public class TestKerberosUtil {
@ -32,23 +31,23 @@ public class TestKerberosUtil {
String testHost = "FooBar"; String testHost = "FooBar";
// send null hostname // send null hostname
assertEquals("When no hostname is sent", Assert.assertEquals("When no hostname is sent",
service + "/" + localHostname.toLowerCase(), service + "/" + localHostname.toLowerCase(),
KerberosUtil.getServicePrincipal(service, null)); KerberosUtil.getServicePrincipal(service, null));
// send empty hostname // send empty hostname
assertEquals("When empty hostname is sent", Assert.assertEquals("When empty hostname is sent",
service + "/" + localHostname.toLowerCase(), service + "/" + localHostname.toLowerCase(),
KerberosUtil.getServicePrincipal(service, "")); KerberosUtil.getServicePrincipal(service, ""));
// send 0.0.0.0 hostname // send 0.0.0.0 hostname
assertEquals("When 0.0.0.0 hostname is sent", Assert.assertEquals("When 0.0.0.0 hostname is sent",
service + "/" + localHostname.toLowerCase(), service + "/" + localHostname.toLowerCase(),
KerberosUtil.getServicePrincipal(service, "0.0.0.0")); KerberosUtil.getServicePrincipal(service, "0.0.0.0"));
// send uppercase hostname // send uppercase hostname
assertEquals("When uppercase hostname is sent", Assert.assertEquals("When uppercase hostname is sent",
service + "/" + testHost.toLowerCase(), service + "/" + testHost.toLowerCase(),
KerberosUtil.getServicePrincipal(service, testHost)); KerberosUtil.getServicePrincipal(service, testHost));
// send lowercase hostname // send lowercase hostname
assertEquals("When lowercase hostname is sent", Assert.assertEquals("When lowercase hostname is sent",
service + "/" + testHost.toLowerCase(), service + "/" + testHost.toLowerCase(),
KerberosUtil.getServicePrincipal(service, testHost.toLowerCase())); KerberosUtil.getServicePrincipal(service, testHost.toLowerCase()));
} }

View File

@ -13,68 +13,75 @@
*/ */
package org.apache.hadoop.security.authentication.util; package org.apache.hadoop.security.authentication.util;
import junit.framework.TestCase; import org.junit.Assert;
import org.junit.Test;
public class TestSigner extends TestCase { public class TestSigner {
@Test
public void testNoSecret() throws Exception { public void testNoSecret() throws Exception {
try { try {
new Signer(null); new Signer(null);
fail(); Assert.fail();
} }
catch (IllegalArgumentException ex) { catch (IllegalArgumentException ex) {
} }
} }
@Test
public void testNullAndEmptyString() throws Exception { public void testNullAndEmptyString() throws Exception {
Signer signer = new Signer("secret".getBytes()); Signer signer = new Signer("secret".getBytes());
try { try {
signer.sign(null); signer.sign(null);
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
try { try {
signer.sign(""); signer.sign("");
fail(); Assert.fail();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
} }
@Test
public void testSignature() throws Exception { public void testSignature() throws Exception {
Signer signer = new Signer("secret".getBytes()); Signer signer = new Signer("secret".getBytes());
String s1 = signer.sign("ok"); String s1 = signer.sign("ok");
String s2 = signer.sign("ok"); String s2 = signer.sign("ok");
String s3 = signer.sign("wrong"); String s3 = signer.sign("wrong");
assertEquals(s1, s2); Assert.assertEquals(s1, s2);
assertNotSame(s1, s3); Assert.assertNotSame(s1, s3);
} }
@Test
public void testVerify() throws Exception { public void testVerify() throws Exception {
Signer signer = new Signer("secret".getBytes()); Signer signer = new Signer("secret".getBytes());
String t = "test"; String t = "test";
String s = signer.sign(t); String s = signer.sign(t);
String e = signer.verifyAndExtract(s); String e = signer.verifyAndExtract(s);
assertEquals(t, e); Assert.assertEquals(t, e);
} }
@Test
public void testInvalidSignedText() throws Exception { public void testInvalidSignedText() throws Exception {
Signer signer = new Signer("secret".getBytes()); Signer signer = new Signer("secret".getBytes());
try { try {
signer.verifyAndExtract("test"); signer.verifyAndExtract("test");
fail(); Assert.fail();
} catch (SignerException ex) { } catch (SignerException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
} }
@Test
public void testTampering() throws Exception { public void testTampering() throws Exception {
Signer signer = new Signer("secret".getBytes()); Signer signer = new Signer("secret".getBytes());
String t = "test"; String t = "test";
@ -82,12 +89,11 @@ public class TestSigner extends TestCase {
s += "x"; s += "x";
try { try {
signer.verifyAndExtract(s); signer.verifyAndExtract(s);
fail(); Assert.fail();
} catch (SignerException ex) { } catch (SignerException ex) {
// Expected // Expected
} catch (Throwable ex) { } catch (Throwable ex) {
fail(); Assert.fail();
} }
} }
} }

View File

@ -1,28 +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.
#
[libdefaults]
default_realm = ${kerberos.realm}
udp_preference_limit = 1
extra_addresses = 127.0.0.1
[realms]
${kerberos.realm} = {
admin_server = localhost:88
kdc = localhost:88
}
[domain_realm]
localhost = ${kerberos.realm}

View File

@ -35,6 +35,9 @@ Release 2.3.0 - UNRELEASED
HADOOP-9860. Remove class HackedKeytab and HackedKeytabEncoder from HADOOP-9860. Remove class HackedKeytab and HackedKeytabEncoder from
hadoop-minikdc once jira DIRSERVER-1882 solved. (ywskycn via tucu) hadoop-minikdc once jira DIRSERVER-1882 solved. (ywskycn via tucu)
HADOOP-9866. convert hadoop-auth testcases requiring kerberos to
use minikdc. (ywskycn via tucu)
OPTIMIZATIONS OPTIMIZATIONS
HADOOP-9748. Reduce blocking on UGI.ensureInitialized (daryn) HADOOP-9748. Reduce blocking on UGI.ensureInitialized (daryn)