http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAO.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAO.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAO.java new file mode 100644 index 0000000..b9dc2ef --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAO.java @@ -0,0 +1,458 @@ +/* + * + * 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.airavata.credential.store.store.impl.db; + +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.KeyStorePasswordCallback; +import org.apache.airavata.common.utils.SecurityUtil; +import org.apache.airavata.credential.store.credential.Credential; +import org.apache.airavata.credential.store.store.CredentialStoreException; + +import java.io.*; +import java.security.GeneralSecurityException; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + +/** + * Data access class for credential store. + */ +public class CredentialsDAO extends ParentDAO { + + private String keyStorePath = null; + private String secretKeyAlias = null; + private KeyStorePasswordCallback keyStorePasswordCallback = null; + + public CredentialsDAO() { + } + + public CredentialsDAO(String keyStore, String alias, KeyStorePasswordCallback passwordCallback) { + this.keyStorePath = keyStore; + this.secretKeyAlias = alias; + this.keyStorePasswordCallback = passwordCallback; + } + + public String getKeyStorePath() { + return keyStorePath; + } + + public void setKeyStorePath(String keyStorePath) { + this.keyStorePath = keyStorePath; + } + + public String getSecretKeyAlias() { + return secretKeyAlias; + } + + public void setSecretKeyAlias(String secretKeyAlias) { + this.secretKeyAlias = secretKeyAlias; + } + + public KeyStorePasswordCallback getKeyStorePasswordCallback() { + return keyStorePasswordCallback; + } + + public void setKeyStorePasswordCallback(KeyStorePasswordCallback keyStorePasswordCallback) { + this.keyStorePasswordCallback = keyStorePasswordCallback; + } + + /** + * String createTable = "CREATE TABLE CREDENTIALS\n" + "(\n" + " GATEWAY_ID VARCHAR(256) NOT NULL,\n" + + * " TOKEN_ID VARCHAR(256) NOT NULL,\n" + // Actual token used to identify the credential + * " CREDENTIAL BLOB NOT NULL,\n" + " PORTAL_USER_ID VARCHAR(256) NOT NULL,\n" + + * " TIME_PERSISTED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n" + " PRIMARY KEY (GATEWAY_ID, TOKEN_ID)\n" + * + ")"; + */ + + public void addCredentials(String gatewayId, Credential credential, Connection connection) + throws CredentialStoreException { + + String sql = "INSERT INTO CREDENTIALS VALUES (?, ?, ?, ?, ?)"; + + PreparedStatement preparedStatement = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, gatewayId); + preparedStatement.setString(2, credential.getToken()); + + InputStream isCert = new ByteArrayInputStream(convertObjectToByteArray(credential)); + preparedStatement.setBinaryStream(3, isCert); + + preparedStatement.setString(4, credential.getPortalUserName()); + + java.util.Date date = new java.util.Date(); + Timestamp timestamp = new Timestamp(date.getTime()); + + preparedStatement.setTimestamp(5, timestamp); + + preparedStatement.executeUpdate(); + + } catch (SQLException e) { + StringBuilder stringBuilder = new StringBuilder("Error persisting credentials."); + stringBuilder.append(" gateway - ").append(gatewayId); + stringBuilder.append(" token id - ").append(credential.getToken()); + + log.error(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + + DBUtil.cleanup(preparedStatement); + } + } + + public void deleteCredentials(String gatewayName, String tokenId, Connection connection) + throws CredentialStoreException { + + String sql = "DELETE FROM CREDENTIALS WHERE GATEWAY_ID=? AND TOKEN_ID=?"; + + PreparedStatement preparedStatement = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, gatewayName); + preparedStatement.setString(2, tokenId); + + preparedStatement.executeUpdate(); + + } catch (SQLException e) { + StringBuilder stringBuilder = new StringBuilder("Error deleting credentials for ."); + stringBuilder.append("gateway - ").append(gatewayName); + stringBuilder.append("token id - ").append(tokenId); + + log.error(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + DBUtil.cleanup(preparedStatement); + } + } + + /** + * String createTable = "CREATE TABLE CREDENTIALS\n" + "(\n" + " GATEWAY_ID VARCHAR(256) NOT NULL,\n" + + * " TOKEN_ID VARCHAR(256) NOT NULL,\n" + // Actual token used to identify the credential + * " CREDENTIAL BLOB NOT NULL,\n" + " PORTAL_USER_ID VARCHAR(256) NOT NULL,\n" + + * " TIME_PERSISTED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n" + " PRIMARY KEY (GATEWAY_ID, TOKEN_ID)\n" + * + ")"; + */ + public void updateCredentials(String gatewayId, Credential credential, Connection connection) + throws CredentialStoreException { + + String sql = "UPDATE CREDENTIALS set CREDENTIAL = ?, PORTAL_USER_ID = ?, TIME_PERSISTED = ? where GATEWAY_ID = ? and TOKEN_ID = ?"; + + PreparedStatement preparedStatement = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + InputStream isCert = new ByteArrayInputStream(convertObjectToByteArray(credential)); + preparedStatement.setBinaryStream(1, isCert); + + preparedStatement.setString(2, credential.getPortalUserName()); + + preparedStatement.setTimestamp(3, new Timestamp(new java.util.Date().getTime())); + preparedStatement.setString(4, gatewayId); + preparedStatement.setString(5, credential.getToken()); + + preparedStatement.executeUpdate(); + + } catch (SQLException e) { + StringBuilder stringBuilder = new StringBuilder("Error updating credentials."); + stringBuilder.append(" gateway - ").append(gatewayId); + stringBuilder.append(" token id - ").append(credential.getToken()); + + log.error(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + + DBUtil.cleanup(preparedStatement); + } + + } + + /** + * String createTable = "CREATE TABLE CREDENTIALS\n" + "(\n" + " GATEWAY_ID VARCHAR(256) NOT NULL,\n" + + * " TOKEN_ID VARCHAR(256) NOT NULL,\n" + // Actual token used to identify the credential + * " CREDENTIAL BLOB NOT NULL,\n" + " PORTAL_USER_ID VARCHAR(256) NOT NULL,\n" + + * " TIME_PERSISTED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n" + " PRIMARY KEY (GATEWAY_ID, TOKEN_ID)\n" + * + ")"; + */ + public Credential getCredential(String gatewayName, String tokenId, Connection connection) + throws CredentialStoreException { + + String sql = "SELECT * FROM CREDENTIALS WHERE GATEWAY_ID=? AND TOKEN_ID=?"; + + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, gatewayName); + preparedStatement.setString(2, tokenId); + + resultSet = preparedStatement.executeQuery(); + + if (resultSet.next()) { + // CertificateCredential certificateCredential = new CertificateCredential(); + + Blob blobCredentials = resultSet.getBlob("CREDENTIAL"); + byte[] certificate = blobCredentials.getBytes(1, (int) blobCredentials.length()); + + Credential certificateCredential = (Credential) convertByteArrayToObject(certificate); + + certificateCredential.setPortalUserName(resultSet.getString("PORTAL_USER_ID")); + certificateCredential.setCertificateRequestedTime(resultSet.getTimestamp("TIME_PERSISTED")); + + return certificateCredential; + } + + } catch (SQLException e) { + StringBuilder stringBuilder = new StringBuilder("Error retrieving credentials for user."); + stringBuilder.append("gateway - ").append(gatewayName); + stringBuilder.append("token id - ").append(tokenId); + + log.debug(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + DBUtil.cleanup(preparedStatement, resultSet); + } + + return null; + } + /** + * + */ + public String getGatewayID(String tokenId, Connection connection) + throws CredentialStoreException { + + String sql = "SELECT GATEWAY_ID FROM CREDENTIALS WHERE TOKEN_ID=?"; + + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, tokenId); + + resultSet = preparedStatement.executeQuery(); + + if (resultSet.next()) { + return resultSet.getString("GATEWAY_ID"); + } + + } catch (SQLException e) { + StringBuilder stringBuilder = new StringBuilder("Error retrieving credentials for user."); + stringBuilder.append("token id - ").append(tokenId); + + log.debug(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + DBUtil.cleanup(preparedStatement, resultSet); + } + + return null; + } + /** + * String createTable = "CREATE TABLE CREDENTIALS\n" + "(\n" + " GATEWAY_ID VARCHAR(256) NOT NULL,\n" + + * " TOKEN_ID VARCHAR(256) NOT NULL,\n" + // Actual token used to identify the credential + * " CREDENTIAL BLOB NOT NULL,\n" + " PORTAL_USER_ID VARCHAR(256) NOT NULL,\n" + + * " TIME_PERSISTED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n" + " PRIMARY KEY (GATEWAY_ID, TOKEN_ID)\n" + * + ")"; + */ + public List<Credential> getCredentials(String gatewayName, Connection connection) throws CredentialStoreException { + + List<Credential> credentialList = new ArrayList<Credential>(); + + String sql = "SELECT * FROM CREDENTIALS WHERE GATEWAY_ID=?"; + + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, gatewayName); + + resultSet = preparedStatement.executeQuery(); + + Credential certificateCredential; + + while (resultSet.next()) { + + Blob blobCredentials = resultSet.getBlob("CREDENTIAL"); + byte[] certificate = blobCredentials.getBytes(1, (int) blobCredentials.length()); + + certificateCredential = (Credential) convertByteArrayToObject(certificate); + + certificateCredential.setPortalUserName(resultSet.getString("PORTAL_USER_ID")); + certificateCredential.setCertificateRequestedTime(resultSet.getTimestamp("TIME_PERSISTED")); + + credentialList.add(certificateCredential); + } + + } catch (SQLException e) { + StringBuilder stringBuilder = new StringBuilder("Error retrieving credential list for "); + stringBuilder.append("gateway - ").append(gatewayName); + + log.debug(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + DBUtil.cleanup(preparedStatement, resultSet); + } + + return credentialList; + } + + /** + * Gets all credentials. + * @param connection The database connection + * @return All credentials as a list + * @throws CredentialStoreException If an error occurred while rerieving credentials. + */ + public List<Credential> getCredentials(Connection connection) throws CredentialStoreException { + + List<Credential> credentialList = new ArrayList<Credential>(); + + String sql = "SELECT * FROM CREDENTIALS"; + + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + resultSet = preparedStatement.executeQuery(); + + Credential certificateCredential; + + while (resultSet.next()) { + + Blob blobCredentials = resultSet.getBlob("CREDENTIAL"); + byte[] certificate = blobCredentials.getBytes(1, (int) blobCredentials.length()); + + certificateCredential = (Credential) convertByteArrayToObject(certificate); + + certificateCredential.setPortalUserName(resultSet.getString("PORTAL_USER_ID")); + certificateCredential.setCertificateRequestedTime(resultSet.getTimestamp("TIME_PERSISTED")); + + credentialList.add(certificateCredential); + } + + } catch (SQLException e) { + StringBuilder stringBuilder = new StringBuilder("Error retrieving all credentials"); + + log.debug(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + DBUtil.cleanup(preparedStatement, resultSet); + } + + return credentialList; + } + + public Object convertByteArrayToObject(byte[] data) throws CredentialStoreException { + ObjectInputStream objectInputStream = null; + Object o = null; + try { + try { + //decrypt the data first + if (encrypt()) { + data = SecurityUtil.decrypt(this.keyStorePath, this.secretKeyAlias, this.keyStorePasswordCallback, data); + } + + objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data)); + o = objectInputStream.readObject(); + + } catch (IOException e) { + throw new CredentialStoreException("Error de-serializing object.", e); + } catch (ClassNotFoundException e) { + throw new CredentialStoreException("Error de-serializing object.", e); + } catch (GeneralSecurityException e) { + throw new CredentialStoreException("Error decrypting data.", e); + } + } finally { + if (objectInputStream != null) { + try { + objectInputStream.close(); + } catch (IOException e) { + log.error("Error occurred while closing the stream", e); + } + } + } + return o; + } + + public byte[] convertObjectToByteArray(Serializable o) throws CredentialStoreException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + + ObjectOutputStream objectOutputStream = null; + try { + objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); + objectOutputStream.writeObject(o); + objectOutputStream.flush(); + } catch (IOException e) { + throw new CredentialStoreException("Error serializing object.", e); + } finally { + if (objectOutputStream != null) { + try { + objectOutputStream.close(); + } catch (IOException e) { + log.error("Error occurred while closing object output stream", e); + } + } + } + + // encrypt the byte array + if (encrypt()) { + byte[] array = byteArrayOutputStream.toByteArray(); + try { + return SecurityUtil.encrypt(this.keyStorePath, this.secretKeyAlias, this.keyStorePasswordCallback, array); + } catch (GeneralSecurityException e) { + throw new CredentialStoreException("Error encrypting data", e); + } catch (IOException e) { + throw new CredentialStoreException("Error encrypting data. IO exception.", e); + } + } else { + return byteArrayOutputStream.toByteArray(); + } + } + + /** + * Says whether to encrypt data or not. if alias, keystore is set + * we treat encryption true. + * @return true if data should encrypt else false. + */ + private boolean encrypt() { + return this.keyStorePath != null; + } + +}
http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/ParentDAO.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/ParentDAO.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/ParentDAO.java new file mode 100644 index 0000000..8ef0d69 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/ParentDAO.java @@ -0,0 +1,37 @@ +/* + * + * 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.airavata.credential.store.store.impl.db; + +import org.apache.airavata.common.utils.DBUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Super class to abstract out Data access classes. + */ +public class ParentDAO { + protected static Logger log = LoggerFactory.getLogger(ParentDAO.class); + + public ParentDAO() { + } + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/ConfigurationReader.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/ConfigurationReader.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/ConfigurationReader.java new file mode 100644 index 0000000..e44d4d8 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/ConfigurationReader.java @@ -0,0 +1,121 @@ +/* + * + * 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.airavata.credential.store.util; + +import org.apache.airavata.credential.store.store.CredentialStoreException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.io.InputStream; + +/** + * User: AmilaJ ([email protected]) + * Date: 8/25/13 + * Time: 6:40 AM + */ + +/** + * Reads credential store specific configurations from the client.xml file. + */ +public class ConfigurationReader { + + private String successUrl; + + private String errorUrl; + + private String portalRedirectUrl; + + public String getPortalRedirectUrl() { + return portalRedirectUrl; + } + + public void setPortalRedirectUrl(String portalRedirectUrl) { + this.portalRedirectUrl = portalRedirectUrl; + } + + public ConfigurationReader() throws CredentialStoreException { + + try { + loadConfigurations(); + } catch (Exception e) { + throw new CredentialStoreException("Unable to read credential store specific configurations." , e); + } + + + } + + private void loadConfigurations() throws ParserConfigurationException, + IOException, SAXException { + InputStream inputStream + = this.getClass().getClassLoader().getResourceAsStream("credential-store/client.xml"); + + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(inputStream); + + doc.getDocumentElement().normalize(); + + NodeList nodeList = doc.getElementsByTagName("credential-store"); + + readElementValue(nodeList); + + } + + private void readElementValue(NodeList nodeList) { + for (int temp = 0; temp < nodeList.getLength(); temp++) { + + Node nNode = nodeList.item(temp); + + if (nNode.getNodeType() == Node.ELEMENT_NODE) { + + Element eElement = (Element) nNode; + + this.successUrl = eElement.getElementsByTagName("successUri").item(0).getTextContent(); + this.errorUrl = eElement.getElementsByTagName("errorUri").item(0).getTextContent(); + this.portalRedirectUrl = eElement.getElementsByTagName("redirectUri").item(0).getTextContent(); + } + } + } + + public String getSuccessUrl() { + return successUrl; + } + + public void setSuccessUrl(String successUrl) { + this.successUrl = successUrl; + } + + public String getErrorUrl() { + return errorUrl; + } + + public void setErrorUrl(String errorUrl) { + this.errorUrl = errorUrl; + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/CredentialStoreConstants.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/CredentialStoreConstants.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/CredentialStoreConstants.java new file mode 100644 index 0000000..de3c59c --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/CredentialStoreConstants.java @@ -0,0 +1,37 @@ +/* + * + * 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.airavata.credential.store.util; + +/** + * User: AmilaJ ([email protected]) + * Date: 8/25/13 + * Time: 4:34 PM + */ + +public class CredentialStoreConstants { + + public static final String GATEWAY_NAME_QUERY_PARAMETER = "gatewayName"; + public static final String PORTAL_USER_QUERY_PARAMETER = "portalUserName"; + public static final String PORTAL_USER_EMAIL_QUERY_PARAMETER = "email"; + public static final String PORTAL_TOKEN_ID_ASSIGNED = "associatedToken"; + public static final String DURATION_QUERY_PARAMETER = "duration"; +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/PrivateKeyStore.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/PrivateKeyStore.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/PrivateKeyStore.java new file mode 100644 index 0000000..cd6db7e --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/PrivateKeyStore.java @@ -0,0 +1,70 @@ +/* + * + * 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.airavata.credential.store.util; + +import java.security.PrivateKey; +import java.util.HashMap; +import java.util.Map; + +/** + * User: AmilaJ ([email protected]) + * Date: 9/5/13 + * Time: 6:47 PM + */ + +public class PrivateKeyStore { + + private Map<String, PrivateKey> privateKeyMap; + + private static PrivateKeyStore privateKeyStore = null; + + private PrivateKeyStore() { + privateKeyMap = new HashMap<String, PrivateKey>(); + } + + public static PrivateKeyStore getPrivateKeyStore() { + + if (privateKeyStore == null) { + privateKeyStore = new PrivateKeyStore(); + } + + return privateKeyStore; + } + + public synchronized void addKey(String tokenId, PrivateKey privateKey) { + + privateKeyMap.put(tokenId, privateKey); + } + + public synchronized PrivateKey getKey(String tokenId) { + + PrivateKey privateKey = privateKeyMap.get(tokenId); + + if (privateKey != null) { + privateKeyMap.remove(tokenId); + } + + return privateKey; + } + + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/TokenGenerator.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/TokenGenerator.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/TokenGenerator.java new file mode 100644 index 0000000..1c36f8d --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/TokenGenerator.java @@ -0,0 +1,57 @@ +/* + * + * 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.airavata.credential.store.util; + +/** + * User: AmilaJ ([email protected]) + * Date: 5/21/13 + * Time: 3:07 PM + */ + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Timestamp; +import java.util.UUID; + +/** + * Generates tokens for users. + */ +public class TokenGenerator { + + protected static Logger log = LoggerFactory.getLogger(TokenGenerator.class); + + + public TokenGenerator() { + + } + + public static String generateToken(String gatewayId, String metadata) { + + return UUID.randomUUID().toString(); + } + + public String encryptToken(String token) { + return null; + } + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/Utility.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/Utility.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/Utility.java new file mode 100644 index 0000000..0ea7bc1 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/util/Utility.java @@ -0,0 +1,110 @@ +/* + * + * 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.airavata.credential.store.util; + +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.KeyPair; +import org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential; +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Contains some utility methods. + */ +public class Utility { + + protected static Logger log = LoggerFactory.getLogger(Utility.class); + + private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss"; + + public static String convertDateToString(Date date) { + + DateFormat df = new SimpleDateFormat(DATE_FORMAT); + return df.format(date); + } + + public static Date convertStringToDate(String date) throws ParseException { + + DateFormat df = new SimpleDateFormat(DATE_FORMAT); + return df.parse(date); + } + + public static String encrypt(String stringToEncrypt) { + return null; + + } + + public static KeyStore loadKeyStore(String keyStoreFile) throws Exception { + KeyStore ks = KeyStore.getInstance("JKS"); + // get user password and file input stream + char[] password = getPassword(); + + java.io.FileInputStream fis = null; + try { + fis = new FileInputStream(keyStoreFile); + ks.load(fis, password); + + return ks; + } finally { + if (fis != null) { + fis.close(); + } + } + } + + public static char[] getPassword() { + return new char[0]; + } + + public static org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential generateKeyPair(SSHCredential credential) throws Exception{ + JSch jsch=new JSch(); + try{ + KeyPair kpair=KeyPair.genKeyPair(jsch, KeyPair.RSA); + File file = File.createTempFile("id_rsa", ""); + String fileName = file.getAbsolutePath(); + + kpair.writePrivateKey(fileName,credential.getPassphrase().getBytes()); + kpair.writePublicKey(fileName + ".pub" , ""); + kpair.dispose(); + byte[] priKey = FileUtils.readFileToByteArray(new File(fileName)); + + byte[] pubKey = FileUtils.readFileToByteArray(new File(fileName + ".pub")); + credential.setPrivateKey(priKey); + credential.setPublicKey(pubKey); + return credential; + } + catch(Exception e){ + log.error("Error while creating key pair", e); + throw new Exception("Error while creating key pair", e); + } + } + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierTest.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierTest.java b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierTest.java new file mode 100644 index 0000000..05d7a10 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierTest.java @@ -0,0 +1,56 @@ +/* + * + * 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.airavata.credential.store.notifier.impl; + +import junit.framework.TestCase; +import org.apache.airavata.credential.store.notifier.NotificationMessage; + +/** + * User: AmilaJ ([email protected]) + * Date: 12/27/13 + * Time: 1:54 PM + */ + +public class EmailNotifierTest extends TestCase { + public void setUp() throws Exception { + super.setUp(); + + } + + // Test is disabled. Need to fill in parameters to send mails + public void xtestNotifyMessage() throws Exception { + + EmailNotifierConfiguration emailNotifierConfiguration = new EmailNotifierConfiguration("smtp.googlemail.com", + 465, "yyy", "xxx", true, "[email protected]"); + + EmailNotifier notifier = new EmailNotifier(emailNotifierConfiguration); + EmailNotificationMessage emailNotificationMessage = new EmailNotificationMessage("Test", + "[email protected]", "Testing credential store"); + notifier.notifyMessage(emailNotificationMessage); + + } + + // Just to ignore test failures. + public void testIgnore() { + + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAOTest.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAOTest.java b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAOTest.java new file mode 100644 index 0000000..8ed8a6a --- /dev/null +++ b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAOTest.java @@ -0,0 +1,207 @@ +/* + * + * 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.airavata.credential.store.store.impl.db; + +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.DatabaseTestCases; +import org.apache.airavata.common.utils.DerbyUtil; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.junit.*; + +import java.sql.Connection; +import java.util.List; + +/** + * Test for community user DAO. + */ +public class CommunityUserDAOTest extends DatabaseTestCases { + + private CommunityUserDAO communityUserDAO; + + @BeforeClass + public static void setUpDatabase() throws Exception { + + DerbyUtil.startDerbyInServerMode(getHostAddress(), getPort(), getUserName(), getPassword()); + + waitTillServerStarts(); + + String createTable = "CREATE TABLE COMMUNITY_USER\n" + " (\n" + + " GATEWAY_NAME VARCHAR(256) NOT NULL,\n" + + " COMMUNITY_USER_NAME VARCHAR(256) NOT NULL,\n" + + " TOKEN_ID VARCHAR(256) NOT NULL,\n" + + " COMMUNITY_USER_EMAIL VARCHAR(256) NOT NULL,\n" + + " PRIMARY KEY (GATEWAY_NAME, COMMUNITY_USER_NAME, TOKEN_ID)\n" + + " )"; + + String dropTable = "drop table COMMUNITY_USER"; + + try { + executeSQL(dropTable); + } catch (Exception e) { + } + + executeSQL(createTable); + + } + + @AfterClass + public static void shutDownDatabase() throws Exception { + DerbyUtil.stopDerbyServer(); + } + + @Before + public void setUp() throws Exception { + + communityUserDAO = new CommunityUserDAO(); + + Connection connection = getDbUtil().getConnection(); + + try { + DBUtil.truncate("community_user", connection); + } finally { + connection.close(); + } + + } + + @Test + public void testAddCommunityUser() throws Exception { + + Connection connection = getConnection(); + + try { + + CommunityUser communityUser = new CommunityUser("gw1", "ogce", "[email protected]"); + communityUserDAO.addCommunityUser(communityUser, "Token1", connection); + + communityUser = new CommunityUser("gw1", "ogce2", "[email protected]"); + communityUserDAO.addCommunityUser(communityUser, "Token2", connection); + + CommunityUser user = communityUserDAO.getCommunityUser("gw1", "ogce", connection); + Assert.assertNotNull(user); + Assert.assertEquals("[email protected]", user.getUserEmail()); + + user = communityUserDAO.getCommunityUser("gw1", "ogce2", connection); + Assert.assertNotNull(user); + Assert.assertEquals("[email protected]", user.getUserEmail()); + + user = communityUserDAO.getCommunityUserByToken("gw1", "Token1", connection); + Assert.assertNotNull(user); + Assert.assertEquals("ogce", user.getUserName()); + Assert.assertEquals("[email protected]", user.getUserEmail()); + + user = communityUserDAO.getCommunityUserByToken("gw1", "Token2", connection); + Assert.assertNotNull(user); + Assert.assertEquals("ogce2", user.getUserName()); + Assert.assertEquals("[email protected]", user.getUserEmail()); + + } finally { + connection.close(); + } + + } + + @Test + public void testDeleteCommunityUser() throws Exception { + + Connection connection = getConnection(); + + try { + CommunityUser communityUser = new CommunityUser("gw1", "ogce", "[email protected]"); + communityUserDAO.addCommunityUser(communityUser, "Token1", connection); + + CommunityUser user = communityUserDAO.getCommunityUser("gw1", "ogce", connection); + Assert.assertNotNull(user); + + communityUser = new CommunityUser("gw1", "ogce", "[email protected]"); + communityUserDAO.deleteCommunityUser(communityUser, connection); + + user = communityUserDAO.getCommunityUser("gw1", "ogce", connection); + Assert.assertNull(user); + + } finally { + connection.close(); + } + } + + @Test + public void testDeleteCommunityUserByToken() throws Exception { + + Connection connection = getConnection(); + + try { + CommunityUser communityUser = new CommunityUser("gw1", "ogce", "[email protected]"); + communityUserDAO.addCommunityUser(communityUser, "Token1", connection); + + CommunityUser user = communityUserDAO.getCommunityUser("gw1", "ogce", connection); + Assert.assertNotNull(user); + + communityUser = new CommunityUser("gw1", "ogce", "[email protected]"); + communityUserDAO.deleteCommunityUserByToken(communityUser, "Token1", connection); + + user = communityUserDAO.getCommunityUser("gw1", "ogce", connection); + Assert.assertNull(user); + + } finally { + connection.close(); + } + + } + + @Test + public void testGetCommunityUsers() throws Exception { + + Connection connection = getConnection(); + + try { + CommunityUser communityUser = new CommunityUser("gw1", "ogce", "[email protected]"); + communityUserDAO.addCommunityUser(communityUser, "Token1", connection); + + CommunityUser user = communityUserDAO.getCommunityUser("gw1", "ogce", connection); + Assert.assertNotNull(user); + Assert.assertEquals("[email protected]", user.getUserEmail()); + + } finally { + connection.close(); + } + + } + + @Test + public void testGetCommunityUsersForGateway() throws Exception { + + Connection connection = getConnection(); + + CommunityUser communityUser = new CommunityUser("gw1", "ogce", "[email protected]"); + communityUserDAO.addCommunityUser(communityUser, "Token1", connection); + + communityUser = new CommunityUser("gw1", "ogce2", "[email protected]"); + communityUserDAO.addCommunityUser(communityUser, "Token2", connection); + + List<CommunityUser> users = communityUserDAO.getCommunityUsers("gw1", connection); + Assert.assertNotNull(users); + Assert.assertEquals(2, users.size()); + + Assert.assertEquals(users.get(0).getUserName(), "ogce"); + Assert.assertEquals(users.get(1).getUserName(), "ogce2"); + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAOTest.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAOTest.java b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAOTest.java new file mode 100644 index 0000000..c175454 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/store/impl/db/CredentialsDAOTest.java @@ -0,0 +1,421 @@ +/* + * + * 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.airavata.credential.store.store.impl.db; + +import junit.framework.Assert; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.DatabaseTestCases; +import org.apache.airavata.common.utils.DerbyUtil; +import org.apache.airavata.common.utils.KeyStorePasswordCallback; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.apache.airavata.credential.store.credential.Credential; +import org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; +import org.apache.airavata.credential.store.store.CredentialStoreException; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.net.URL; +import java.security.*; +import java.security.cert.X509Certificate; +import java.sql.Connection; +import java.util.Arrays; +import java.util.List; + +/** + * Test class for credential class + */ +public class CredentialsDAOTest extends DatabaseTestCases { + + private static final Logger logger = LoggerFactory.getLogger(CredentialsDAOTest.class); + + private CredentialsDAO credentialsDAO; + + private X509Certificate[] x509Certificates; + private PrivateKey privateKey; + + @BeforeClass + public static void setUpDatabase() throws Exception { + DerbyUtil.startDerbyInServerMode(getHostAddress(), getPort(), getUserName(), getPassword()); + + waitTillServerStarts(); + + /* + * String createTable = "CREATE TABLE CREDENTIALS\n" + "(\n" + " GATEWAY_NAME VARCHAR(256) NOT NULL,\n" + + * " COMMUNITY_USER_NAME VARCHAR(256) NOT NULL,\n" + " CREDENTIAL BLOB NOT NULL,\n" + + * " PRIVATE_KEY BLOB NOT NULL,\n" + " NOT_BEFORE VARCHAR(256) NOT NULL,\n" + + * " NOT_AFTER VARCHAR(256) NOT NULL,\n" + " LIFETIME INTEGER NOT NULL,\n" + + * " REQUESTING_PORTAL_USER_NAME VARCHAR(256) NOT NULL,\n" + + * " REQUESTED_TIME TIMESTAMP DEFAULT '0000-00-00 00:00:00',\n" + + * " PRIMARY KEY (GATEWAY_NAME, COMMUNITY_USER_NAME)\n" + ")"; + */ + + String createTable = "CREATE TABLE CREDENTIALS\n" + "(\n" + + " GATEWAY_ID VARCHAR(256) NOT NULL,\n" + + " TOKEN_ID VARCHAR(256) NOT NULL,\n" + + // Actual token used to identify the credential + " CREDENTIAL BLOB NOT NULL,\n" + " PORTAL_USER_ID VARCHAR(256) NOT NULL,\n" + + " TIME_PERSISTED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n" + + " PRIMARY KEY (GATEWAY_ID, TOKEN_ID)\n" + ")"; + + String dropTable = "drop table CREDENTIALS"; + + try { + executeSQL(dropTable); + } catch (Exception e) { + } + + executeSQL(createTable); + + } + + @AfterClass + public static void shutDownDatabase() throws Exception { + DerbyUtil.stopDerbyServer(); + } + + @Before + public void setUp() throws Exception { + + credentialsDAO = new CredentialsDAO(); + + x509Certificates = new X509Certificate[1]; + + // Cleanup tables; + Connection connection = getConnection(); + + try { + DBUtil.truncate("credentials", connection); + } finally { + connection.close(); + } + + initializeKeys(); + } + + private void initializeKeys() throws Exception { + KeyStore ks = KeyStore.getInstance("JKS"); + char[] password = "password".toCharArray(); + + String baseDirectory = System.getProperty("credential.module.directory"); + + String keyStorePath = "src" + File.separator + "test" + File.separator + "resources" + File.separator + + "keystore.jks"; + + if (baseDirectory != null) { + keyStorePath = baseDirectory + File.separator + keyStorePath; + } else { + keyStorePath = "modules" + File.separator + "credential-store" + File.separator + keyStorePath; + } + + File keyStoreFile = new File(keyStorePath); + if (!keyStoreFile.exists()) { + logger.error("Unable to read keystore file " + keyStoreFile); + throw new RuntimeException("Unable to read keystore file " + keyStoreFile); + + } + + java.io.FileInputStream fis = null; + try { + fis = new java.io.FileInputStream(keyStorePath); + ks.load(fis, password); + } finally { + if (fis != null) { + fis.close(); + } + } + + fis.close(); + + privateKey = (PrivateKey) ks.getKey("selfsigned", password); + x509Certificates[0] = (X509Certificate) ks.getCertificate("selfsigned"); + + } + + @Test + public void testKeyReading() throws Exception { + initializeKeys(); + System.out.println(privateKey.getAlgorithm()); + System.out.println(x509Certificates[0].getIssuerDN()); + + Assert.assertNotNull(privateKey); + Assert.assertNotNull(x509Certificates); + } + + private CommunityUser getCommunityUser(String gateway, String name) { + return new CommunityUser(gateway, name, "[email protected]"); + } + + private void addTestCredentials() throws Exception { + + Connection connection = getConnection(); + + try { + CertificateCredential certificateCredential = getTestCredentialObject(); + credentialsDAO.addCredentials(certificateCredential.getCommunityUser().getGatewayName(), + certificateCredential, connection); + + } finally { + connection.close(); + } + } + + public CertificateCredential getTestCredentialObject() { + + CertificateCredential certificateCredential = new CertificateCredential(); + certificateCredential.setToken("tom"); + certificateCredential.setCertificates(x509Certificates); + certificateCredential.setPrivateKey(privateKey); + certificateCredential.setCommunityUser(getCommunityUser("gw1", "tom")); + certificateCredential.setLifeTime(1000); + certificateCredential.setPortalUserName("jerry"); + certificateCredential.setNotBefore("13 OCT 2012 5:34:23"); + certificateCredential.setNotAfter("14 OCT 2012 5:34:23"); + + return certificateCredential; + + } + + @Test + public void testSerialization() throws CredentialStoreException { + + CertificateCredential certificateCredential = getTestCredentialObject(); + + CredentialsDAO credentialsDAO1 = new CredentialsDAO(); + + byte[] array = credentialsDAO1.convertObjectToByteArray(certificateCredential); + CertificateCredential readCertificateCredential = (CertificateCredential) credentialsDAO1 + .convertByteArrayToObject(array); + + checkEquality(certificateCredential.getCertificates(), readCertificateCredential.getCertificates()); + Assert.assertEquals(certificateCredential.getCertificateRequestedTime(), + readCertificateCredential.getCertificateRequestedTime()); + Assert.assertEquals(certificateCredential.getCommunityUser().getGatewayName(), readCertificateCredential + .getCommunityUser().getGatewayName()); + Assert.assertEquals(certificateCredential.getCommunityUser().getUserEmail(), readCertificateCredential + .getCommunityUser().getUserEmail()); + Assert.assertEquals(certificateCredential.getCommunityUser().getUserName(), readCertificateCredential + .getCommunityUser().getUserName()); + Assert.assertEquals(certificateCredential.getLifeTime(), readCertificateCredential.getLifeTime()); + Assert.assertEquals(certificateCredential.getNotAfter(), readCertificateCredential.getNotAfter()); + Assert.assertEquals(certificateCredential.getNotBefore(), readCertificateCredential.getNotBefore()); + Assert.assertEquals(certificateCredential.getPortalUserName(), readCertificateCredential.getPortalUserName()); + + PrivateKey newKey = readCertificateCredential.getPrivateKey(); + + Assert.assertNotNull(newKey); + Assert.assertEquals(privateKey.getClass(), newKey.getClass()); + + Assert.assertEquals(privateKey.getFormat(), newKey.getFormat()); + Assert.assertEquals(privateKey.getAlgorithm(), newKey.getAlgorithm()); + Assert.assertTrue(Arrays.equals(privateKey.getEncoded(), newKey.getEncoded())); + } + + @Test + public void testSerializationWithEncryption() throws CredentialStoreException { + + URL url = this.getClass().getClassLoader().getResource("mykeystore.jks"); + String secretKeyAlias = "mykey"; + + assert url != null; + + CertificateCredential certificateCredential = getTestCredentialObject(); + + CredentialsDAO credentialsDAO1 = new CredentialsDAO(url.getPath(), secretKeyAlias, + new TestACSKeyStoreCallback()); + + byte[] array = credentialsDAO1.convertObjectToByteArray(certificateCredential); + CertificateCredential readCertificateCredential = (CertificateCredential) credentialsDAO1 + .convertByteArrayToObject(array); + + checkEquality(certificateCredential.getCertificates(), readCertificateCredential.getCertificates()); + Assert.assertEquals(certificateCredential.getCertificateRequestedTime(), + readCertificateCredential.getCertificateRequestedTime()); + Assert.assertEquals(certificateCredential.getCommunityUser().getGatewayName(), readCertificateCredential + .getCommunityUser().getGatewayName()); + Assert.assertEquals(certificateCredential.getCommunityUser().getUserEmail(), readCertificateCredential + .getCommunityUser().getUserEmail()); + Assert.assertEquals(certificateCredential.getCommunityUser().getUserName(), readCertificateCredential + .getCommunityUser().getUserName()); + Assert.assertEquals(certificateCredential.getLifeTime(), readCertificateCredential.getLifeTime()); + Assert.assertEquals(certificateCredential.getNotAfter(), readCertificateCredential.getNotAfter()); + Assert.assertEquals(certificateCredential.getNotBefore(), readCertificateCredential.getNotBefore()); + Assert.assertEquals(certificateCredential.getPortalUserName(), readCertificateCredential.getPortalUserName()); + + PrivateKey newKey = readCertificateCredential.getPrivateKey(); + + Assert.assertNotNull(newKey); + Assert.assertEquals(privateKey.getClass(), newKey.getClass()); + + Assert.assertEquals(privateKey.getFormat(), newKey.getFormat()); + Assert.assertEquals(privateKey.getAlgorithm(), newKey.getAlgorithm()); + Assert.assertTrue(Arrays.equals(privateKey.getEncoded(), newKey.getEncoded())); + } + + private class TestACSKeyStoreCallback implements KeyStorePasswordCallback { + + @Override + public char[] getStorePassword() { + return "airavata".toCharArray(); + } + + @Override + public char[] getSecretKeyPassPhrase(String keyAlias) { + if (keyAlias.equals("mykey")) { + return "airavatasecretkey".toCharArray(); + } + + return null; + } + } + + private void checkEquality(X509Certificate[] certificates1, X509Certificate[] certificates2) { + + int i = 0; + + for (X509Certificate certificate : certificates1) { + Assert.assertEquals(certificate, certificates2[i]); + } + + Assert.assertEquals(certificates1.length, certificates2.length); + + } + + @Test + public void testAddCredentials() throws Exception { + + addTestCredentials(); + + Connection connection = getConnection(); + + try { + CertificateCredential certificateCredential = (CertificateCredential) credentialsDAO.getCredential("gw1", + "tom", connection); + //Test get gateway name + String gateway = credentialsDAO.getGatewayID("tom", connection); + Assert.assertNotNull(certificateCredential); + Assert.assertEquals("jerry", certificateCredential.getPortalUserName()); + Assert.assertEquals("gw1", gateway); + checkEquality(x509Certificates, certificateCredential.getCertificates()); + Assert.assertEquals(privateKey.getFormat(), certificateCredential.getPrivateKey().getFormat()); + } finally { + connection.close(); + } + } + + @Test + public void testDeleteCredentials() throws Exception { + + addTestCredentials(); + + Connection connection = getConnection(); + + try { + CertificateCredential certificateCredential = (CertificateCredential) credentialsDAO.getCredential("gw1", + "tom", connection); + Assert.assertNotNull(certificateCredential); + + credentialsDAO.deleteCredentials("gw1", "tom", connection); + + certificateCredential = (CertificateCredential) credentialsDAO.getCredential("gw1", "tom", connection); + Assert.assertNull(certificateCredential); + + } finally { + connection.close(); + } + } + + @Test + public void testUpdateCredentials() throws Exception { + + addTestCredentials(); + + Connection connection = getConnection(); + + try { + CommunityUser communityUser = getCommunityUser("gw1", "tom"); + CertificateCredential certificateCredential = new CertificateCredential(); + certificateCredential.setToken("tom"); + certificateCredential.setCommunityUser(communityUser); + certificateCredential.setCertificates(x509Certificates); + // certificateCredential.setPrivateKey(privateKey); + certificateCredential.setPortalUserName("test2"); + certificateCredential.setLifeTime(50); + certificateCredential.setNotBefore("15 OCT 2012 5:34:23"); + certificateCredential.setNotAfter("16 OCT 2012 5:34:23"); + + credentialsDAO.updateCredentials(communityUser.getGatewayName(), certificateCredential, connection); + + certificateCredential = (CertificateCredential) credentialsDAO.getCredential("gw1", "tom", connection); + + Assert.assertEquals("CN=Airavata Project, OU=IU, O=Indiana University, L=Bloomington, ST=IN, C=US", + certificateCredential.getCertificates()[0].getIssuerDN().toString()); + // Assert.assertNotNull(certificateCredential.getPrivateKey()); + Assert.assertEquals("test2", certificateCredential.getPortalUserName()); + + } finally { + connection.close(); + } + + } + + @Test + public void testGetCredentials() throws Exception { + + addTestCredentials(); + + Connection connection = getConnection(); + + try { + + CertificateCredential certificateCredential = (CertificateCredential) credentialsDAO.getCredential("gw1", + "tom", connection); + Assert.assertEquals("CN=Airavata Project, OU=IU, O=Indiana University, L=Bloomington, ST=IN, C=US", + certificateCredential.getCertificates()[0].getIssuerDN().toString()); + // Assert.assertNotNull(certificateCredential.getPrivateKey()); + + } finally { + connection.close(); + } + } + + @Test + public void testGetGatewayCredentials() throws Exception { + + addTestCredentials(); + + Connection connection = getConnection(); + + try { + List<Credential> list = credentialsDAO.getCredentials("gw1", connection); + + Assert.assertEquals(1, list.size()); + } finally { + connection.close(); + } + + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/ConfigurationReaderTest.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/ConfigurationReaderTest.java b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/ConfigurationReaderTest.java new file mode 100644 index 0000000..7a95e3e --- /dev/null +++ b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/ConfigurationReaderTest.java @@ -0,0 +1,58 @@ +/* + * + * 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.airavata.credential.store.util; + +import junit.framework.Assert; +import junit.framework.TestCase; + +/** + * User: AmilaJ ([email protected]) + * Date: 8/25/13 + * Time: 10:28 AM + */ + +public class ConfigurationReaderTest extends TestCase { + public void setUp() throws Exception { + super.setUp(); + + } + + public void testGetSuccessUrl() throws Exception { + + ConfigurationReader configurationReader = new ConfigurationReader(); + System.out.println(configurationReader.getSuccessUrl()); + Assert.assertEquals("/credential-store/success.jsp", configurationReader.getSuccessUrl()); + } + + public void testGetErrorUrl() throws Exception { + + ConfigurationReader configurationReader = new ConfigurationReader(); + Assert.assertEquals("/credential-store/error.jsp", configurationReader.getErrorUrl()); + + } + + public void testRedirectUrl() throws Exception { + + ConfigurationReader configurationReader = new ConfigurationReader(); + Assert.assertEquals("/credential-store/show-redirect.jsp", configurationReader.getPortalRedirectUrl()); + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/TokenGeneratorTest.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/TokenGeneratorTest.java b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/TokenGeneratorTest.java new file mode 100644 index 0000000..57b52ae --- /dev/null +++ b/modules/credential-store/credential-store-service/src/test/java/org/apache/airavata/credential/store/util/TokenGeneratorTest.java @@ -0,0 +1,42 @@ +/* + * + * 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.airavata.credential.store.util; + +import junit.framework.Assert; +import junit.framework.TestCase; + +/** + * User: AmilaJ ([email protected]) + * Date: 8/5/13 + * Time: 4:20 PM + */ + +public class TokenGeneratorTest extends TestCase { + + public void testGenerateToken() throws Exception { + + String token = TokenGenerator.generateToken("gw1", "admin"); + Assert.assertNotNull(token); + System.out.println(token); + + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/resources/credential-store/client.xml ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/resources/credential-store/client.xml b/modules/credential-store/credential-store-service/src/test/resources/credential-store/client.xml new file mode 100644 index 0000000..8b934e6 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/test/resources/credential-store/client.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!--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. --> + +<config> + <client name="acs"> + <logging + logFileName="../logs/oa4mp.log" + logName="oa4mp" + logSize="1000000" + logFileCount="2" + debug="true"/> + <id>myproxy:oa4mp,2012:/client/24c45c2eb65d93231d02d423e94d0362</id> + <serviceUri>https://oa4mp.xsede.org/oauth</serviceUri> + <callbackUri>https://localhost:8443/airavata/callback</callbackUri> + <lifetime>864000</lifetime> + <publicKeyFile>../webapps/airavata/WEB-INF/classes/credential-store/oauth-pubkey.pem</publicKeyFile> + <privateKeyFile>../webapps/airavata/WEB-INF/classes/credential-store/oauth-privkey.pk8</privateKeyFile> + </client> + + <credential-store> + <successUri>/credential-store/success.jsp</successUri> + <errorUri>/credential-store/error.jsp</errorUri> + <redirectUri>/credential-store/show-redirect.jsp</redirectUri> + </credential-store> + +</config> http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/resources/keystore.jks ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/resources/keystore.jks b/modules/credential-store/credential-store-service/src/test/resources/keystore.jks new file mode 100644 index 0000000..14cf022 Binary files /dev/null and b/modules/credential-store/credential-store-service/src/test/resources/keystore.jks differ http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/test/resources/mykeystore.jks ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/test/resources/mykeystore.jks b/modules/credential-store/credential-store-service/src/test/resources/mykeystore.jks new file mode 100644 index 0000000..335ebf8 Binary files /dev/null and b/modules/credential-store/credential-store-service/src/test/resources/mykeystore.jks differ http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-stubs/pom.xml ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-stubs/pom.xml b/modules/credential-store/credential-store-stubs/pom.xml new file mode 100644 index 0000000..2a1c431 --- /dev/null +++ b/modules/credential-store/credential-store-stubs/pom.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<!--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. --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>credential-store</artifactId> + <groupId>org.apache.airavata</groupId> + <version>0.15-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + + <name>Credential Store CPI Stubs</name> + <artifactId>airavata-credential-store-stubs</artifactId> + <packaging>jar</packaging> + <url>http://airavata.apache.org/</url> + + <dependencies> + <dependency> + <groupId>org.apache.thrift</groupId> + <artifactId>libthrift</artifactId> + <version>${thrift.version}</version> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + <version>${org.slf4j.version}</version> + </dependency> + </dependencies> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> + </properties> + +</project> \ No newline at end of file
