You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@taverna.apache.org by re...@apache.org on 2015/03/20 16:47:28 UTC
[3/8] incubator-taverna-engine git commit: package names changed to
org.apache.taverna.*
http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorIT.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorIT.java b/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorIT.java
deleted file mode 100644
index 18068db..0000000
--- a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorIT.java
+++ /dev/null
@@ -1,535 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2008-2010 The University of Manchester
- *
- * Modifications to the initial code base are copyright of their
- * respective authors, or their employers as appropriate.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.Authenticator;
-import java.net.PasswordAuthentication;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-import net.sf.taverna.t2.security.credentialmanager.CMException;
-import net.sf.taverna.t2.security.credentialmanager.CredentialManager;
-import net.sf.taverna.t2.security.credentialmanager.JavaTruststorePasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.MasterPasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.ServiceUsernameAndPasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.TrustConfirmationProvider;
-import net.sf.taverna.t2.security.credentialmanager.UsernamePassword;
-
-import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mortbay.jetty.Connector;
-import org.mortbay.jetty.Handler;
-import org.mortbay.jetty.Server;
-import org.mortbay.jetty.handler.DefaultHandler;
-import org.mortbay.jetty.handler.HandlerCollection;
-import org.mortbay.jetty.nio.SelectChannelConnector;
-import org.mortbay.jetty.security.Constraint;
-import org.mortbay.jetty.security.ConstraintMapping;
-import org.mortbay.jetty.security.HashUserRealm;
-import org.mortbay.jetty.security.SecurityHandler;
-import org.mortbay.jetty.webapp.WebAppContext;
-
-/**
- *
- * Based on net.sf.tavenra.security.credentialmanager.FixedPasswordProvider from the
- * Taverna 2 codebase.
- *
- * @author Stian Soiland-Reyes
- * @author Alex Nenadic
- *
- */
-public class HTTPAuthenticatorIT {
-
- protected static final String WRONG_PASSWORD = "wrongOne";
- protected final static String PASSWORD = "basicPassword";
- protected static final String PASSWORD2 = "password2";
- protected static final String PASSWORD3 = "password3";
- protected static final String PASSWORD4 = "password4";
- protected static final String REALM = "realm1";
- protected static final String REALM2 = "realm2";
- protected final static String USERNAME = "basicUser";
-
- protected static final int PORT = 9638;
-
- private final class CountingAuthenticator extends
- CredentialManagerAuthenticator {
-
- public CountingAuthenticator(CredentialManager credManager) {
- super(credManager);
- }
-
- private int calls;
-
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- calls++;
- return super.getPasswordAuthentication();
- }
- }
-
- public class NullAuthenticator extends Authenticator {
- }
-
- protected static final String ROLE_NAME = "user";
- protected static final String HTML = "/html/";
- protected static Server server;
- protected static HashUserRealm userRealm;
- private static SecurityHandler sh;
-
- private static CredentialManagerImpl credentialManager;
- private static File credentialManagerDirectory;
- private static DummyMasterPasswordProvider masterPasswordProvider;
- private static HTTPAuthenticatorServiceUsernameAndPasswordProvider httpAuthProvider;
-
- @BeforeClass
- public static void startCredentialManager() throws CMException, IOException {
-
- try {
- credentialManager = new CredentialManagerImpl();
- } catch (CMException e) {
- System.out.println(e.getStackTrace());
- }
- Random randomGenerator = new Random();
- String credentialManagerDirectoryPath = System
- .getProperty("java.io.tmpdir")
- + System.getProperty("file.separator")
- + "taverna-security-"
- + randomGenerator.nextInt(1000000);
- System.out.println("Credential Manager's directory path: "
- + credentialManagerDirectoryPath);
- credentialManagerDirectory = new File(credentialManagerDirectoryPath);
- try {
- credentialManager
- .setConfigurationDirectoryPath(credentialManagerDirectory);
- } catch (CMException e) {
- System.out.println(e.getStackTrace());
- }
-
- // Create the dummy master password provider
- masterPasswordProvider = new DummyMasterPasswordProvider();
- /* Short password to avoid issues with key sizes and Java strong crypto policy*/
- masterPasswordProvider.setMasterPassword("uber");
- List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
- masterPasswordProviders.add(masterPasswordProvider);
- credentialManager.setMasterPasswordProviders(masterPasswordProviders);
-
- // Put our HTTP authenticator in the list of service username and password providers
- httpAuthProvider = new HTTPAuthenticatorServiceUsernameAndPasswordProvider();
- ArrayList<ServiceUsernameAndPasswordProvider> serviceUsernameAndPasswordProviders = new ArrayList<ServiceUsernameAndPasswordProvider>();
- serviceUsernameAndPasswordProviders.add(httpAuthProvider);
- credentialManager.setServiceUsernameAndPasswordProviders(serviceUsernameAndPasswordProviders);
-
- // These can be empty
- credentialManager.setJavaTruststorePasswordProviders(new ArrayList<JavaTruststorePasswordProvider>());
- credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());
- }
-
- @AfterClass
- // Clean up the credentialManagerDirectory we created for testing
- public static void cleanUp(){
-
- if (credentialManagerDirectory.exists()){
- try {
- FileUtils.deleteDirectory(credentialManagerDirectory);
- System.out.println("Deleting Credential Manager's directory: "
- + credentialManagerDirectory.getAbsolutePath());
- } catch (IOException e) {
- System.out.println(e.getStackTrace());
- }
- }
- }
-
- @BeforeClass
- public static void jettyServer() throws Exception {
-
- server = new Server();
-
- Connector connector = new SelectChannelConnector();
- connector.setPort(PORT);
- server.setConnectors(new Connector[] { connector });
- ConstraintMapping cm = new ConstraintMapping();
- Constraint constraint = new Constraint();
- constraint.setName(Constraint.__BASIC_AUTH);
- constraint.setRoles(new String[] { ROLE_NAME });
- constraint.setAuthenticate(true);
- cm.setConstraint(constraint);
- cm.setPathSpec("/*");
-
- sh = new SecurityHandler();
- userRealm = new HashUserRealm(REALM);
- userRealm.put(USERNAME, PASSWORD);
- userRealm.addUserToRole(USERNAME, ROLE_NAME);
- sh.setUserRealm(userRealm);
- sh.setConstraintMappings(new ConstraintMapping[] { cm });
-
- WebAppContext webappcontext = new WebAppContext();
- webappcontext.setContextPath("/");
-
- URL htmlRoot = HTTPAuthenticatorIT.class.getResource(HTML);
- assertNotNull("Could not find " + HTML, htmlRoot);
- webappcontext.setWar(htmlRoot.toExternalForm());
-
- webappcontext.addHandler(sh);
-
- HandlerCollection handlers = new HandlerCollection();
- handlers.setHandlers(new Handler[] { webappcontext,
- new DefaultHandler() });
-
- server.setHandler(handlers);
- server.start();
- }
-
-
- @AfterClass
- public static void shutdownJetty() throws Exception {
- server.stop();
- }
-
- @Before
- @After
- public void resetAuthenticator() throws CMException {
- Authenticator.setDefault(new NullAuthenticator());
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
- }
-
- @Before
- public void resetAuthCache() throws CMException {
- credentialManager.resetAuthCache();
- }
-
- @Before
- public void resetUserRealmPassword() {
- userRealm.put(USERNAME, PASSWORD);
- userRealm.setName(REALM);
- }
-
- @Test()
- public void failsWithoutAuthenticator() throws Exception {
- URL url = new URL("http://localhost:" + PORT + "/test.html");
- URLConnection c = url.openConnection();
- assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));
- }
-
- @Test()
- public void withAuthenticator() throws Exception {
- assertEquals("Unexpected calls to password provider", 0,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- // Set the authenticator to our Credential Manager-backed one that also
- // counts calls to itself
- CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
- assertEquals("Unexpected calls to authenticator", 0,
- authenticator.calls);
- Authenticator.setDefault(authenticator);
-// FixedPasswordProvider.setUsernamePassword(new UsernamePassword(
-// USERNAME, PASSWORD));
-
- URL url = new URL("http://localhost:" + PORT + "/test.html");
- httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(
- USERNAME, PASSWORD));
- URLConnection c = url.openConnection();
-
- c.connect();
- try {
- c.getContent();
- } catch (Exception ex) {
- }
- System.out.println(c.getHeaderField(0));
- assertEquals("Did not invoke authenticator", 1, authenticator.calls);
- assertEquals("Did not invoke our password provider", 1,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));
-
-
- assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
- assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider
- .getServiceURI().toASCIIString());
-
- // And test Java's cache:
- URLConnection c2 = url.openConnection();
- c2.connect();
- assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
- assertEquals("JVM invoked our authenticator again instead of caching", 1,
- authenticator.calls);
- assertEquals("Invoked our password provider again instead of caching",
- 1, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
-
- }
-
- @Test()
- public void withAuthenticatorResetJava() throws Exception {
- assertTrue("Could not reset JVMs authCache, ignore on non-Sun JVM",
- credentialManager.resetAuthCache());
-
- assertEquals("Unexpected calls to password provider", 0,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
- assertEquals("Unexpected calls to authenticator", 0,
- authenticator.calls);
- Authenticator.setDefault(authenticator);
-// FixedPasswordProvider.setUsernamePassword(new UsernamePassword(
-// USERNAME, PASSWORD));
-
- URL url = new URL("http://localhost:" + PORT + "/test.html");
- httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(
- USERNAME, PASSWORD));
- URLConnection c = url.openConnection();
-
- c.connect();
- try {
- c.getContent();
- } catch (Exception ex) {
- }
-
- assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));
-
- assertEquals("Did not invoke authenticator", 1, authenticator.calls);
- assertEquals("Did not invoke our password provider", 1,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
-
- assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
- assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider
- .getServiceURI().toASCIIString());
-
-
-
- // And without Java's cache:
- assertTrue("Could not reset VMs authCache, ignore on non-Sun VM",
- credentialManager.resetAuthCache());
-
- URLConnection c2 = url.openConnection();
- c2.connect();
- assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
- assertEquals("Did not invoke our authenticator again", 2,
- authenticator.calls);
- assertEquals("Did not invoke our password provider again",
- 2, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
-
- }
-
-
- @Test()
- public void differentRealm() throws Exception {
-
- assertEquals("Unexpected calls to password provider", 0,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
- assertEquals("Unexpected calls to authenticator", 0,
- authenticator.calls);
- Authenticator.setDefault(authenticator);
- // Different password in case resetAuthCache() did not run
- UsernamePassword userPassword = new UsernamePassword(
- USERNAME, PASSWORD4);
- userRealm.put(USERNAME, PASSWORD4);
-// userPassword.setShouldSave(true);
- //FixedPasswordProvider.setUsernamePassword(userPassword);
-
- URL url = new URL("http://localhost:" + PORT + "/test.html");
- httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), userPassword);
- URLConnection c = url.openConnection();
-
- c.connect();
- try {
- c.getContent();
- } catch (Exception ex) {
- }
-
- assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
- assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider
- .getServiceURI().toASCIIString());
-
- assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));
-
- assertEquals("Did not invoke authenticator", 1, authenticator.calls);
- assertEquals("Did not invoke our password provider", 1,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
-
-
- // different realm should be treated as a second connection, and not even use saved credentials
-
- credentialManager.resetAuthCache();
- userRealm.setName(REALM2);
-
- URLConnection c2 = url.openConnection();
- c2.connect();
- try {
- c.getContent();
- } catch (Exception ex) {
- }
-
- assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
-
- assertEquals("Did not invoke authenticator again", 2,
- authenticator.calls);
- assertEquals("Did not invoke provider again",
- 2, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
-
- assertEquals("Unexpected prompt/realm", REALM2, httpAuthProvider
- .getRequestMessage());
- assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM2, HTTPAuthenticatorServiceUsernameAndPasswordProvider
- .getServiceURI().toASCIIString());
- }
-
-
- @Test()
- public void wrongPasswordDontSave() throws Exception {
- assertEquals("Unexpected calls to password provider", 0,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
- assertEquals("Unexpected calls to authenticator", 0,
- authenticator.calls);
- Authenticator.setDefault(authenticator);
-
- // Make the server expect different password so our cache is no longer
- // valid
- userRealm.put(USERNAME, PASSWORD2);
- // But we'll try with the old one, which we'll this time ask to save in
- // DB
- UsernamePassword usernamePassword = new UsernamePassword(USERNAME,
- PASSWORD);
- assertFalse("Should not be set to save by default", usernamePassword
- .isShouldSave());
- //FixedPasswordProvider.setUsernamePassword(usernamePassword);
-
- URL url = new URL("http://localhost:" + PORT + "/test.html");
- httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
- URLConnection c = url.openConnection();
- try {
- c.getContent();
- } catch (Exception ex) {
- }
-
- assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider
- .getRequestMessage());
- assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider
- .getServiceURI().toASCIIString());
-
- assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));
-
- assertTrue("Did not invoke authenticator enough times",
- authenticator.calls > 1);
- assertEquals("Should have asked provider as much as authenticator",
- authenticator.calls, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
-
-
- // Update provider to now provide the right one
-// HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
-// USERNAME, PASSWORD2));
- httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(
- USERNAME, PASSWORD2));
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
- authenticator.calls = 0;
-
- URLConnection c2 = url.openConnection();
- try {
- c2.getContent();
- } catch (Exception ex) {
- }
- assertEquals("Did not call authenticator again with cache pw invalid",
- 1, authenticator.calls);
- assertEquals(
- "id not called our password provider once",
- 1, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
- }
-
- @Test()
- public void saveToDatabase() throws Exception {
- assertEquals("Unexpected calls to password provider", 0,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
- assertEquals("Unexpected calls to authenticator", 0,
- authenticator.calls);
- Authenticator.setDefault(authenticator);
-
- // Make the server expect different password so our cache is no longer
- // valid (In case CredManager.resetAuthCache() did not succeed on non-Sun VMs)
- userRealm.put(USERNAME, PASSWORD3);
- // But we'll try with the old one, which we'll this time ask to save in
- // DB
- UsernamePassword usernamePassword = new UsernamePassword(USERNAME,
- PASSWORD2);
- usernamePassword.setShouldSave(true);
- //HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(usernamePassword);
-
- URL url = new URL("http://localhost:" + PORT + "/test.html");
- httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
- URLConnection c = url.openConnection();
- try {
- c.getContent();
- } catch (Exception ex) {
- }
-
- assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider
- .getRequestMessage());
- assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider
- .getServiceURI().toASCIIString());
-
- assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));
-
- assertTrue("Did not invoke authenticator enough times",
- authenticator.calls > 1);
- assertEquals(
- "Asked our provider more than once, not saved in credMan?", 1,
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
-
-
-
- // Expect the old one again
- userRealm.put(USERNAME, PASSWORD2);
- // We'll now set our provider to give an invalid password, but we should
- // not be asked
- // as the old one (now correct agian) is stored in DB
-// HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
-// USERNAME, WRONG_PASSWORD));
- httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(
- USERNAME, WRONG_PASSWORD));
-
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
- authenticator.calls = 0;
-
- URLConnection c2 = url.openConnection();
- try {
- c2.getContent();
- } catch (Exception ex) {
- }
- assertEquals("Did not call authenticator again with cache pw invalid",
- 1, authenticator.calls);
- assertEquals(
- "Called our password provider instead of using credMan saved one",
- 0, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
- assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorServiceUsernameAndPasswordProvider.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorServiceUsernameAndPasswordProvider.java b/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorServiceUsernameAndPasswordProvider.java
deleted file mode 100644
index 5d3d6f2..0000000
--- a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPAuthenticatorServiceUsernameAndPasswordProvider.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2008-2010 The University of Manchester
- *
- * Modifications to the initial code base are copyright of their
- * respective authors, or their employers as appropriate.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import java.net.URI;
-
-import net.sf.taverna.t2.security.credentialmanager.ServiceUsernameAndPasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.UsernamePassword;
-
-/**
- *
- * @author Stian Soiland-Reyes
- * @author Alex Nenadic
- *
- */
-public class HTTPAuthenticatorServiceUsernameAndPasswordProvider implements ServiceUsernameAndPasswordProvider {
-
- private static UsernamePassword usernamePassword;
- private static URI serviceURI;
- private static String requestMessage;
- private static long calls = 0;
-
- public static long getCalls() {
- return calls;
- }
-
-
- public static void resetCalls() {
- calls = 0;
- }
-
- @Override
- public UsernamePassword getServiceUsernameAndPassword(URI serviceURI,
- String requestMessage) {
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.serviceURI = serviceURI;
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.requestMessage = requestMessage;
- calls++;
- return usernamePassword.clone();
- }
-
- @Override
- public void setServiceUsernameAndPassword(URI serviceURI,
- UsernamePassword usernamePassword) {
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.serviceURI = serviceURI;
- HTTPAuthenticatorServiceUsernameAndPasswordProvider.usernamePassword = usernamePassword;
- }
-
- public static URI getServiceURI() {
- return serviceURI;
- }
-
- public String getRequestMessage() {
- return requestMessage;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPSConnectionAndTrustConfirmationIT.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPSConnectionAndTrustConfirmationIT.java b/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPSConnectionAndTrustConfirmationIT.java
deleted file mode 100644
index a9211b1..0000000
--- a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/HTTPSConnectionAndTrustConfirmationIT.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2008-2010 The University of Manchester
- *
- * Modifications to the initial code base are copyright of their
- * respective authors, or their employers as appropriate.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.net.URL;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.SecureRandom;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.TrustManagerFactory;
-
-import net.sf.taverna.t2.security.credentialmanager.CMException;
-import net.sf.taverna.t2.security.credentialmanager.MasterPasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.TrustConfirmationProvider;
-
-import org.apache.commons.io.FileUtils;
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-//import org.apache.log4j.Logger;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class HTTPSConnectionAndTrustConfirmationIT {
-
-
- private static CredentialManagerImpl credentialManager;
- private static DummyMasterPasswordProvider masterPasswordProvider;
- private static File credentialManagerDirectory;
- //private static URL trustedCertficateFileURL = HTTPSConnectionAndTrustConfirmationIT.class.getResource("/security/tomcat_heater_certificate.pem");
-
- // Log4J Logger
- //private static Logger logger = Logger.getLogger(HTTPSConnectionAndTrustConfirmationIT.class);
-
-// public static void main(String[] args){
-//
-// try {
-// CredentialManagerOld.initialiseSSL();
-// //CredentialManager.getInstance();
-// //HttpsURLConnection.setDefaultSSLSocketFactory(CredentialManager.createTavernaSSLSocketFactory());
-// URL url = new URL ("https://rpc103.cs.man.ac.uk:8443/wsrf/services/cagrid/SecureHelloWorld?wsdl");
-// HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
-// // user should be asked automatically if they want to trust the connection
-// httpsConnection.connect();
-//
-// } catch (CMException e) {
-// logger.error("", e);
-// } catch (MalformedURLException e) {
-// logger.error("", e);
-// } catch (IOException e) {
-// logger.error("", e);
-// }
-// catch(Exception ex){ // anything we did not expect
-// logger.error("", ex);
-// }
-//
-// }
-
- /**
- * @throws java.lang.Exception
- */
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
-
- // Just in case, add the BouncyCastle provider
- // It gets added from the CredentialManagerImpl constructor as well
- // but we may need some crypto operations before we invoke the Cred. Manager
- Security.addProvider(new BouncyCastleProvider());
- }
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
-
- try {
- credentialManager = new CredentialManagerImpl();
- } catch (CMException e) {
- System.out.println(e.getStackTrace());
- }
- Random randomGenerator = new Random();
- String credentialManagerDirectoryPath = System
- .getProperty("java.io.tmpdir")
- + System.getProperty("file.separator")
- + "taverna-security-"
- + randomGenerator.nextInt(1000000);
- System.out.println("Credential Manager's directory path: "
- + credentialManagerDirectoryPath);
- credentialManagerDirectory = new File(credentialManagerDirectoryPath);
- try {
- credentialManager
- .setConfigurationDirectoryPath(credentialManagerDirectory);
- } catch (CMException e) {
- System.out.println(e.getStackTrace());
- }
-
- // Create the dummy master password provider
- masterPasswordProvider = new DummyMasterPasswordProvider();
- masterPasswordProvider.setMasterPassword("uber");
- List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
- masterPasswordProviders.add(masterPasswordProvider);
- credentialManager.setMasterPasswordProviders(masterPasswordProviders);
-
- // Set an empty list for trust confirmation providers
- credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());
- }
-
- @After
- // Clean up the credentialManagerDirectory we created for testing
- public void cleanUp() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException{
-// assertTrue(credentialManagerDirectory.exists());
-// assertFalse(credentialManagerDirectory.listFiles().length == 0); // something was created there
-
- if (credentialManagerDirectory.exists()){
- try {
- FileUtils.deleteDirectory(credentialManagerDirectory);
- System.out.println("Deleting Credential Manager's directory: "
- + credentialManagerDirectory.getAbsolutePath());
- } catch (IOException e) {
- System.out.println(e.getStackTrace());
- }
- }
-
- // Reset the SSLSocketFactory in JVM so we always have a clean start
- SSLContext sc = null;
- sc = SSLContext.getInstance("SSLv3");
-
- // Create a "default" JSSE X509KeyManager.
- KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509",
- "SunJSSE");
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(null, null);
- kmf.init(ks, "blah".toCharArray());
-
- // Create a "default" JSSE X509TrustManager.
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(
- "SunX509", "SunJSSE");
- KeyStore ts = KeyStore.getInstance("JKS");
- ts.load(null, null);
- tmf.init(ts);
-
- sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
- SSLContext.setDefault(sc);
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- }
-
- @Test
- public void testTrustConfirmationProvidersTrustAlways() throws IOException, CMException {
- // Initially trust provider list is empty, we only verify by what is in
- // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/)
-
- // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory
- credentialManager.initializeSSL();
-
- URL url = new URL("https://heater.cs.man.ac.uk:7443/");
- HttpsURLConnection conn;
- conn = (HttpsURLConnection) url.openConnection();
- try{
- // This should fail
- conn.connect();
- fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
- }
- catch(SSLHandshakeException sslex){
- // expected to fail so all is good
- System.out.println(sslex.getStackTrace());
- }
- finally{
- conn.disconnect();
- }
-
- // Add the trust confirmation provider that trusts everyone
- List<TrustConfirmationProvider> trustProviders = new ArrayList<TrustConfirmationProvider>();
- trustProviders.add(new TrustAlwaysTrustConfirmationProvider());
- credentialManager.setTrustConfirmationProviders(trustProviders);
-
- HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection();
- // This should work now
- conn2.connect();
- System.out.println("Status header: "+ conn2.getHeaderField(0));
-
- assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0));
- conn2.disconnect();
- }
-
- @Test
- public void testTrustConfirmationProvidersTrustNever() throws IOException, CMException {
- // Initially trust provider list is empty, we only verify by what is in
- // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/)
-
- // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory
- credentialManager.initializeSSL();
-
- URL url = new URL("https://heater.cs.man.ac.uk:7443/");
- HttpsURLConnection conn;
- conn = (HttpsURLConnection) url.openConnection();
- try{
- // This should fail
- conn.connect();
- fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
- }
- catch(SSLHandshakeException sslex){
- // expected to fail so all is good
- }
- finally{
- conn.disconnect();
- }
-
- // Add the trust confirmation provider that trusts no one
- List<TrustConfirmationProvider> trustProviders = new ArrayList<TrustConfirmationProvider>();
- credentialManager.setTrustConfirmationProviders(trustProviders);
- trustProviders = new ArrayList<TrustConfirmationProvider>();
- trustProviders.add(new TrustNeverTrustConfimationProvider());
- credentialManager.setTrustConfirmationProviders(trustProviders);
-
- HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection();
- try{
- // This should still fail as our trust providers are not trusting anyone
- // and we have not added heater's certificate to Credential Manager's Truststore
- conn2.connect();
- fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
- }
- catch(SSLHandshakeException sslex){
- // expected to fail so all is good
- }
- finally{
- conn2.disconnect();
- }
- }
-
- @Test
- public void testTrustConfirmationAddDeleteCertificateDirectly() throws CMException, IOException, CertificateException{
- // Initially trust provider list is empty, we only verify by what is in
- // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/)
-
- // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory
- credentialManager.initializeSSL();
-
- URL url = new URL("https://heater.cs.man.ac.uk:7443/");
- HttpsURLConnection conn;
- conn = (HttpsURLConnection) url.openConnection();
- try{
- // This should fail
- conn.connect();
- fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
- }
- catch(SSLHandshakeException sslex){
- // expected to fail so all is good
- }
- finally{
- conn.disconnect();
- }
-
- // Add heater's certificate directly to Credential Manager's Truststore
-
- // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
- X509Certificate trustedCertficate;
- URL trustedCertficateFileURL = getClass().getResource("/security/tomcat_heater_certificate.pem");
- System.out.println("testTrustConfirmationAddDeleteCertificateDirectly: trusted certficate file URL " + trustedCertficateFileURL);
- File trustedCertFile = new File(trustedCertficateFileURL.getPath());
- FileInputStream inStream = new FileInputStream(trustedCertFile);
- //InputStream inStream = getClass().getClassLoader().getResourceAsStream("security/tomcat_heater_certificate.pem");
- CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
- trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
- try{
- inStream.close();
- }
- catch (Exception e) {
- // Ignore
- }
- String alias = credentialManager.addTrustedCertificate(trustedCertficate);
-
- HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection();
- // This should work now
- conn2.connect();
- //System.out.println(conn2.getHeaderField(0));
-
- assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0));
- conn2.disconnect();
-
- // Now remove certificate and see if the "trust" changes
- credentialManager.deleteTrustedCertificate(alias);
- HttpsURLConnection conn3;
- conn3 = (HttpsURLConnection) url.openConnection();
- try{
- // This should fail
- conn3.connect();
- fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
- }
- catch(SSLHandshakeException sslex){
- // expected to fail so all is good
- }
- finally{
- conn3.disconnect();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/PossibleURILookupsTest.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/PossibleURILookupsTest.java b/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/PossibleURILookupsTest.java
deleted file mode 100644
index 1cf20ff..0000000
--- a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/PossibleURILookupsTest.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2008-2010 The University of Manchester
- *
- * Modifications to the initial code base are copyright of their
- * respective authors, or their employers as appropriate.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Random;
-
-import net.sf.taverna.t2.security.credentialmanager.CMException;
-import net.sf.taverna.t2.security.credentialmanager.JavaTruststorePasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.MasterPasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.ServiceUsernameAndPasswordProvider;
-import net.sf.taverna.t2.security.credentialmanager.TrustConfirmationProvider;
-
-import org.apache.commons.io.FileUtils;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-/**
- *
- * @author Stian Soiland-Reyes
- * @author Alex Nenadic
- *
- */
-public class PossibleURILookupsTest {
- private static final String SIMPLE_URI = "http://www.taverna.org.uk/filename.html";
- private static final String ROOT_URI = "http://www.taverna.org.uk/";
- private static final String NAIVE_ROOT_URI = "http://www.taverna.org.uk";
-
- private static final String NASTY_URI = "http://www.taverna.org.uk/path1/path2/path3/filename.html?query=1&query2=2";
-
- private static final String NASTY_URI_FRAGMENT = "http://www.taverna.org.uk/path1/path2/path3/filename.html?query=1&query2=2#frag1337";
-
- private static final String NASTY_URI_PARENT = "http://www.taverna.org.uk/path1/path2/path3/";
-
- private static final String NASTY_DOT_DOT_URI = "http://www.taverna.org.uk/path1/path2/path3/path4/../fish.html";
-
- private static CredentialManagerImpl credentialManager;
- private static File credentialManagerDirectory;
- private static DummyMasterPasswordProvider masterPasswordProvider;
- private static HTTPAuthenticatorServiceUsernameAndPasswordProvider httpAuthProvider;
-
- @BeforeClass
- public static void setUp() throws CMException, IOException {
-
- try {
- credentialManager = new CredentialManagerImpl();
- } catch (CMException e) {
- System.out.println(e.getStackTrace());
- }
- Random randomGenerator = new Random();
- String credentialManagerDirectoryPath = System
- .getProperty("java.io.tmpdir")
- + System.getProperty("file.separator")
- + "taverna-security-"
- + randomGenerator.nextInt(1000000);
- System.out.println("Credential Manager's directory path: "
- + credentialManagerDirectoryPath);
- credentialManagerDirectory = new File(credentialManagerDirectoryPath);
- try {
- credentialManager
- .setConfigurationDirectoryPath(credentialManagerDirectory);
- } catch (CMException e) {
- System.out.println(e.getStackTrace());
- }
-
- // Create the dummy master password provider
- masterPasswordProvider = new DummyMasterPasswordProvider();
- /* Short password to avoid issues with key sizes and Java strong crypto policy*/
- masterPasswordProvider.setMasterPassword("uber");
- List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
- masterPasswordProviders.add(masterPasswordProvider);
- credentialManager.setMasterPasswordProviders(masterPasswordProviders);
-
- // Put our HTTP authenticator in the list of service username and password providers
- httpAuthProvider = new HTTPAuthenticatorServiceUsernameAndPasswordProvider();
- ArrayList<ServiceUsernameAndPasswordProvider> serviceUsernameAndPasswordProviders = new ArrayList<ServiceUsernameAndPasswordProvider>();
- serviceUsernameAndPasswordProviders.add(httpAuthProvider);
- credentialManager.setServiceUsernameAndPasswordProviders(serviceUsernameAndPasswordProviders);
-
- // These can be empty
- credentialManager.setJavaTruststorePasswordProviders(new ArrayList<JavaTruststorePasswordProvider>());
- credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());
- }
-
- @AfterClass
- // Clean up the credentialManagerDirectory we created for testing
- public static void cleanUp(){
-
- if (credentialManagerDirectory.exists()){
- try {
- FileUtils.deleteDirectory(credentialManagerDirectory);
- System.out.println("Deleting Credential Manager's directory: "
- + credentialManagerDirectory.getAbsolutePath());
- } catch (IOException e) {
- System.out.println(e.getStackTrace());
- }
- }
- }
-
- @Test
- public void possibleLookupsNoRecursion() throws Exception {
- URI uri = URI.create(NASTY_URI);
- LinkedHashSet<URI> lookups = credentialManager.getPossibleServiceURIsToLookup(uri,
- false);
- assertTrue("Did not contain " + uri, lookups.remove(uri));
- assertTrue("Unexpected lookups:" + lookups, lookups.isEmpty());
- }
-
- @Test
- public void possibleLookupsDotDot() throws Exception {
- URI uri = URI.create(NASTY_DOT_DOT_URI);
- List<URI> expected = Arrays
- .asList(
- URI.create("http://www.taverna.org.uk/path1/path2/path3/fish.html"),
- URI.create("http://www.taverna.org.uk/path1/path2/path3/"),
- URI.create("http://www.taverna.org.uk/path1/path2/"),
- URI.create("http://www.taverna.org.uk/path1/"),
- URI.create("http://www.taverna.org.uk/"));
-
- ArrayList<URI> lookups = new ArrayList<URI>(credentialManager
- .getPossibleServiceURIsToLookup(uri, true));
-
- assertEquals("Did not match expected URIs", expected, lookups);
- }
-
- @Test
- public void possibleLookups() throws Exception {
- URI uri = URI.create(NASTY_URI);
- List<URI> expected = Arrays
- .asList(
- URI.create("http://www.taverna.org.uk/path1/path2/path3/filename.html?query=1&query2=2"),
- URI.create("http://www.taverna.org.uk/path1/path2/path3/filename.html"),
- URI.create("http://www.taverna.org.uk/path1/path2/path3/"),
- URI.create("http://www.taverna.org.uk/path1/path2/"),
- URI.create("http://www.taverna.org.uk/path1/"), URI
- .create("http://www.taverna.org.uk/"));
-
- ArrayList<URI> lookups = new ArrayList<URI>(credentialManager
- .getPossibleServiceURIsToLookup(uri, true));
-
- assertEquals("Did not match expected URIs", expected, lookups);
- }
-
-
- @Test
- public void possibleLookupsWithFragment() throws Exception {
- URI uri = URI.create(NASTY_URI_FRAGMENT);
- List<URI> expected = Arrays
- .asList(
- URI.create("http://www.taverna.org.uk/path1/path2/path3/filename.html?query=1&query2=2#frag1337"),
- URI.create("http://www.taverna.org.uk/path1/path2/path3/filename.html#frag1337"),
- URI.create("http://www.taverna.org.uk/path1/path2/path3/#frag1337"),
- URI.create("http://www.taverna.org.uk/path1/path2/#frag1337"),
- URI.create("http://www.taverna.org.uk/path1/#frag1337"), URI
- .create("http://www.taverna.org.uk/#frag1337"),
- // And then again without fragment
- URI.create("http://www.taverna.org.uk/path1/path2/path3/filename.html?query=1&query2=2"),
- URI.create("http://www.taverna.org.uk/path1/path2/path3/filename.html"),
- URI.create("http://www.taverna.org.uk/path1/path2/path3/"),
- URI.create("http://www.taverna.org.uk/path1/path2/"),
- URI.create("http://www.taverna.org.uk/path1/"), URI
- .create("http://www.taverna.org.uk/")
-
- );
-
- ArrayList<URI> lookups = new ArrayList<URI>(credentialManager
- .getPossibleServiceURIsToLookup(uri, true));
-
- assertEquals("Did not match expected URIs", expected, lookups);
- }
-
- @Test
- public void possibleLookupDirectory() throws Exception {
- URI uri = URI.create(NASTY_URI_PARENT);
- List<URI> expected = Arrays.asList(URI
- .create("http://www.taverna.org.uk/path1/path2/path3/"), URI
- .create("http://www.taverna.org.uk/path1/path2/"), URI
- .create("http://www.taverna.org.uk/path1/"), URI
- .create("http://www.taverna.org.uk/"));
-
- ArrayList<URI> lookups = new ArrayList<URI>(credentialManager
- .getPossibleServiceURIsToLookup(uri, true));
-
- assertEquals("Did not match expected URIs", expected, lookups);
- }
-
- @Test
- public void possibleLookupSimple() throws Exception {
- URI uri = URI.create(SIMPLE_URI);
- List<URI> expected = Arrays.asList(URI
- .create("http://www.taverna.org.uk/filename.html"), URI
- .create("http://www.taverna.org.uk/"));
-
- ArrayList<URI> lookups = new ArrayList<URI>(credentialManager
- .getPossibleServiceURIsToLookup(uri, true));
-
- assertEquals("Did not match expected URIs", expected, lookups);
- }
-
- @Test
- public void possibleLookupRoot() throws Exception {
- URI uri = URI.create(ROOT_URI);
- List<URI> expected = Arrays.asList(URI
- .create("http://www.taverna.org.uk/"));
-
- ArrayList<URI> lookups = new ArrayList<URI>(credentialManager
- .getPossibleServiceURIsToLookup(uri, true));
-
- assertEquals("Did not match expected URIs", expected, lookups);
- }
-
- @Test
- public void possibleLookupNaiveRoot() throws Exception {
- URI uri = URI.create(NAIVE_ROOT_URI);
- List<URI> expected = Arrays.asList(URI
- .create("http://www.taverna.org.uk"), URI
- .create("http://www.taverna.org.uk/"));
-
- ArrayList<URI> lookups = new ArrayList<URI>(credentialManager
- .getPossibleServiceURIsToLookup(uri, true));
-
- assertEquals("Did not match expected URIs", expected, lookups);
- }
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustAlwaysTrustConfirmationProvider.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustAlwaysTrustConfirmationProvider.java b/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustAlwaysTrustConfirmationProvider.java
deleted file mode 100644
index bae9e54..0000000
--- a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustAlwaysTrustConfirmationProvider.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2008-2010 The University of Manchester
- *
- * Modifications to the initial code base are copyright of their
- * respective authors, or their employers as appropriate.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import java.security.cert.X509Certificate;
-
-import net.sf.taverna.t2.security.credentialmanager.TrustConfirmationProvider;
-
-public class TrustAlwaysTrustConfirmationProvider implements TrustConfirmationProvider{
-
- @Override
- public Boolean shouldTrustCertificate(X509Certificate[] chain) {
-
- // Always trust
- return Boolean.TRUE;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustNeverTrustConfimationProvider.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustNeverTrustConfimationProvider.java b/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustNeverTrustConfimationProvider.java
deleted file mode 100644
index f7e0aee..0000000
--- a/taverna-credential-manager-impl/src/test/java/net/sf/taverna/t2/security/credentialmanager/impl/TrustNeverTrustConfimationProvider.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2008-2010 The University of Manchester
- *
- * Modifications to the initial code base are copyright of their
- * respective authors, or their employers as appropriate.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import java.security.cert.X509Certificate;
-
-import net.sf.taverna.t2.security.credentialmanager.TrustConfirmationProvider;
-
-public class TrustNeverTrustConfimationProvider implements TrustConfirmationProvider{
-
- @Override
- public Boolean shouldTrustCertificate(X509Certificate[] chain) {
-
- // Never trust
- return Boolean.FALSE;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/test/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerImplIT.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/test/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerImplIT.java b/taverna-credential-manager-impl/src/test/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerImplIT.java
new file mode 100644
index 0000000..01b224b
--- /dev/null
+++ b/taverna-credential-manager-impl/src/test/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerImplIT.java
@@ -0,0 +1,338 @@
+/*
+* 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.taverna.security.credentialmanager.impl;
+
+import static org.junit.Assert.*;
+
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.Security;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Random;
+
+import javax.net.ssl.HttpsURLConnection;
+
+import net.sf.taverna.t2.lang.observer.Observable;
+import net.sf.taverna.t2.lang.observer.Observer;
+import org.apache.taverna.security.credentialmanager.CMException;
+import org.apache.taverna.security.credentialmanager.KeystoreChangedEvent;
+import org.apache.taverna.security.credentialmanager.MasterPasswordProvider;
+import org.apache.taverna.security.credentialmanager.TrustConfirmationProvider;
+import org.apache.taverna.security.credentialmanager.UsernamePassword;
+
+import org.apache.commons.io.FileUtils;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * Tests here require Java strong/unlimited cryptography policy to be installed
+ * so they are part of integration tests.
+ *
+ * Java strong/unlimited cryptography policy is required to use the Credential Manager and
+ * the full security capabilities in Taverna. Java by default comes with the weak policy
+ * that disables the use of certain cryto algorithms and bigger key sizes. Although
+ * it is claimed that as of Java 6 the default policy is strong, we have seen otherwise,
+ * so make sure you install it.
+ *
+ * For Java 6, strong/unlimited cryptography policy can be downloaded
+ * (together with the installation instructions) from:
+ * http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html
+ *
+ * These tests use an existing keystore (in resources/security/t2keystore.ubr) and
+ * truststore (in resources/security/t2truststore.ubr) that are not empty.
+ *
+ * @author Alex Nenadic
+ *
+ */
+public class CredentialManagerImplIT {
+
+ private static CredentialManagerImpl credentialManager;
+ // Master password for Credential Manager's Keystore and Truststore
+ private static String masterPassword = "(cl%ZDxu66AN/{vNXbLF";
+ private static DummyMasterPasswordProvider masterPasswordProvider;
+ private static File credentialManagerDirectory;
+
+ private static UsernamePassword usernamePassword;
+ private static URI serviceURI;
+ private static UsernamePassword usernamePassword2;
+ private static URI serviceURI2;
+ private static UsernamePassword usernamePassword3;
+ private static URI serviceURI3;
+
+ private static Key privateKey;
+ private static Certificate[] privateKeyCertChain;
+ private static URL privateKeyFileURL = CredentialManagerImplTest.class.getResource(
+ "/security/test-private-key-cert.p12");
+ private static final String privateKeyAndPKCS12KeystorePassword = "test"; // password for the test PKCS#12 keystore in resources
+
+ private static X509Certificate trustedCertficateGoogle;
+ private static URL trustedCertficateGoogleFileURL = CredentialManagerImplTest.class.getResource(
+ "/security/google-trusted-certificate.pem");
+ private static X509Certificate trustedCertficateHeater;
+ private static URL trustedCertficateHeaterFileURL = CredentialManagerImplTest.class.getResource(
+ "/security/tomcat_heater_certificate.pem");
+
+ private static Observer<KeystoreChangedEvent> keystoreChangedObserver;
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @BeforeClass
+ @Ignore
+ public static void setUpBeforeCLass() throws Exception {
+
+ Security.addProvider(new BouncyCastleProvider());
+
+ // Create some test username and passwords for services
+ serviceURI = new URI("http://someservice");
+ usernamePassword = new UsernamePassword("testuser", "testpasswd");
+ serviceURI2 = new URI("http://someservice2");
+ usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
+ serviceURI3 = new URI("http://someservice3");
+ usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");
+
+ // Load the test private key and its certificate
+ File privateKeyCertFile = new File(privateKeyFileURL.getPath());
+ KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
+ FileInputStream inStream = new FileInputStream(privateKeyCertFile);
+ pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
+ // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
+ Enumeration<String> aliases = pkcs12Keystore.aliases();
+ while (aliases.hasMoreElements()) {
+ // The test-private-key-cert.p12 file contains only one private key
+ // and corresponding certificate entry
+ String alias = aliases.nextElement();
+ if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
+ privateKey = pkcs12Keystore.getKey(alias,
+ privateKeyAndPKCS12KeystorePassword.toCharArray());
+ privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
+ break;
+ }
+ }
+ inStream.close();
+
+ // Load the test trusted certificate (belonging to *.Google.com)
+ File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
+ inStream = new FileInputStream(trustedCertFile);
+ CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
+ trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
+ try{
+ inStream.close();
+ }
+ catch (Exception e) {
+ // Ignore
+ }
+ // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
+ File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
+ inStream = new FileInputStream(trustedCertFile2);
+ trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
+ try{
+ inStream.close();
+ }
+ catch (Exception e) {
+ // Ignore
+ }
+
+ credentialManager = new CredentialManagerImpl();
+
+// // The code below sets up the Keystore and Truststore files and loads some data into them
+// // and saves them into a temp directory. These files can later be used for testing the Credential
+// // Manager with non-empty keystores.
+// Random randomGenerator = new Random();
+// String credentialManagerDirectoryPath = System
+// .getProperty("java.io.tmpdir")
+// + System.getProperty("file.separator")
+// + "taverna-security-"
+// + randomGenerator.nextInt(1000000);
+// System.out.println("Credential Manager's directory path: "
+// + credentialManagerDirectoryPath);
+// credentialManagerDirectory = new File(credentialManagerDirectoryPath);
+// credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
+//
+// // Create the dummy master password provider
+// masterPasswordProvider = new DummyMasterPasswordProvider();
+// masterPasswordProvider.setMasterPassword(masterPassword);
+// List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
+// masterPasswordProviders.add(masterPasswordProvider);
+// credentialManager.setMasterPasswordProviders(masterPasswordProviders);
+//
+// // Add some stuff into Credential Manager
+// credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
+// credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
+// credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
+// credentialManager.addKeyPair(privateKey, privateKeyCertChain);
+// credentialManager.addTrustedCertificate(trustedCertficate);
+
+
+ // Set up a random temp directory and copy the test keystore files
+ // from resources/security
+ Random randomGenerator = new Random();
+ String credentialManagerDirectoryPath = System
+ .getProperty("java.io.tmpdir")
+ + System.getProperty("file.separator")
+ + "taverna-security-"
+ + randomGenerator.nextInt(1000000);
+ System.out.println("Credential Manager's directory path: "
+ + credentialManagerDirectoryPath);
+ credentialManagerDirectory = new File(credentialManagerDirectoryPath);
+ if (!credentialManagerDirectory.exists()) {
+ credentialManagerDirectory.mkdir();
+ }
+ URL keystoreFileURL = CredentialManagerImplIT.class
+ .getResource("/security/t2keystore.ubr");
+ File keystoreFile = new File(keystoreFileURL.getPath());
+ File keystoreDestFile = new File(credentialManagerDirectory,
+ "taverna-keystore.ubr");
+ URL truststroreFileURL = CredentialManagerImplIT.class
+ .getResource("/security/t2truststore.ubr");
+ File truststoreFile = new File(truststroreFileURL.getPath());
+ File truststoreDestFile = new File(credentialManagerDirectory,
+ "taverna-truststore.ubr");
+ FileUtils.copyFile(keystoreFile, keystoreDestFile);
+ FileUtils.copyFile(truststoreFile, truststoreDestFile);
+ credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
+
+ // Create the dummy master password provider
+ masterPasswordProvider = new DummyMasterPasswordProvider();
+ masterPasswordProvider.setMasterPassword(masterPassword);
+ List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
+ masterPasswordProviders.add(masterPasswordProvider);
+ credentialManager.setMasterPasswordProviders(masterPasswordProviders);
+
+ // Set an empty list for trust confirmation providers
+ credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());
+
+ keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
+ @Override
+ public void notify(Observable<KeystoreChangedEvent> sender,
+ KeystoreChangedEvent message) throws Exception {
+ // TODO Auto-generated method stub
+ }
+ };
+ credentialManager.addObserver(keystoreChangedObserver);
+ }
+
+ @AfterClass
+ @Ignore
+ // Clean up the credentialManagerDirectory we created for testing
+ public static void cleanUp(){
+
+ if (credentialManagerDirectory.exists()){
+ try {
+ FileUtils.deleteDirectory(credentialManagerDirectory);
+ System.out.println("Deleting Credential Manager's directory: "
+ + credentialManagerDirectory.getAbsolutePath());
+ } catch (IOException e) {
+ System.out.println(e.getStackTrace());
+ }
+ }
+ }
+
+ @Test
+ @Ignore
+ public void testCredentialManager() throws CMException, URISyntaxException, IOException{
+
+ // There are 3 service username and password entries in the Keystore
+ List<URI> serviceList = credentialManager.getServiceURIsForAllUsernameAndPasswordPairs();
+ assertTrue(serviceList.size() == 3);
+ System.out.println();
+ assertTrue(serviceList.contains(serviceURI2));
+
+ credentialManager.deleteUsernameAndPasswordForService(serviceURI3);
+ assertFalse(credentialManager.hasUsernamePasswordForService(serviceURI3));
+
+ // There are 2 private/public key pair entries in the Keystore
+ credentialManager.hasKeyPair(privateKey, privateKeyCertChain);
+
+ // There are Google's and heater.cs.man.ac's trusted certificates in the Truststore
+ credentialManager.hasTrustedCertificate(trustedCertficateGoogle);
+ // Open a HTTPS connection to Google
+ URL url = new URL("https://code.google.com/p/taverna/");
+ HttpsURLConnection conn;
+ conn = (HttpsURLConnection) url.openConnection();
+ // This should work
+ conn.connect();
+ assertEquals("HTTP/1.1 200 OK", conn.getHeaderField(0));
+ conn.disconnect();
+
+ credentialManager.hasTrustedCertificate(trustedCertficateHeater);
+ // Open a HTTPS connection to heater
+ url = new URL("https://heater.cs.man.ac.uk:7443/");
+ conn = (HttpsURLConnection) url.openConnection();
+ // This should work
+ conn.connect();
+ assertEquals("HTTP/1.1 200 OK", conn.getHeaderField(0));
+ conn.disconnect();
+
+ }
+
+ public void generateKeystores() throws Exception{
+
+ setUpBeforeCLass();
+
+ // The code below sets up the Keystore and Truststore files and loads some data into them
+ // and saves them into a temp directory. These files can later be used for testing the Credential
+ // Manager with non-empty keystores.
+ Random randomGenerator = new Random();
+ String credentialManagerDirectoryPath = System
+ .getProperty("java.io.tmpdir")
+ + System.getProperty("file.separator")
+ + "taverna-security-"
+ + randomGenerator.nextInt(1000000);
+ System.out.println("Credential Manager's Keystore and Truststore will be saved to: "
+ + credentialManagerDirectoryPath);
+ credentialManagerDirectory = new File(credentialManagerDirectoryPath);
+ credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
+
+ // Create the dummy master password provider
+ masterPasswordProvider = new DummyMasterPasswordProvider();
+// masterPasswordProvider.setMasterPassword(masterPassword);
+ masterPasswordProvider.setMasterPassword("uber");
+ List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
+ masterPasswordProviders.add(masterPasswordProvider);
+ credentialManager.setMasterPasswordProviders(masterPasswordProviders);
+
+ // Add some stuff into Credential Manager
+ credentialManager.addUsernameAndPasswordForService(usernamePassword, new URI("http://heater.cs.man.ac.uk:7070/axis/services/HelloService-PlaintextPassword?wsdl"));
+
+// credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
+// credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
+// credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
+// credentialManager.addKeyPair(privateKey, privateKeyCertChain);
+ credentialManager.addTrustedCertificate(trustedCertficateHeater);
+ }
+
+
+}