From 70176081920e735e6c34b0497fdbf2e3588e1404 Mon Sep 17 00:00:00 2001 From: "Tschaen, Brendan" Date: Fri, 22 Feb 2019 10:41:19 -0500 Subject: Create authentication interface Change-Id: I2172870be0056d6b050eb73c9a53c12f05360d79 Issue-ID: MUSIC-345 Signed-off-by: Tschaen, Brendan --- .../org/onap/music/authentication/CachingUtil.java | 490 +++++++++++++++++++++ .../music/authentication/MusicAuthentication.java | 131 +++++- .../music/authentication/MusicAuthenticator.java | 58 +++ .../org/onap/music/datastore/MusicDataStore.java | 2 +- .../zookeeper/MusicLockingService.java | 2 +- src/main/java/org/onap/music/main/CachingUtil.java | 485 -------------------- .../java/org/onap/music/main/CronJobManager.java | 2 +- src/main/java/org/onap/music/main/MusicUtil.java | 12 +- .../org/onap/music/rest/RestMusicAdminAPI.java | 127 +++--- .../java/org/onap/music/rest/RestMusicDataAPI.java | 193 +++----- .../java/org/onap/music/rest/RestMusicQAPI.java | 3 +- .../onap/music/unittests/MusicDataStoreTest.java | 2 +- .../onap/music/unittests/TstRestMusicAdminAPI.java | 10 +- .../unittests/TstRestMusicConditionalAPI.java | 2 +- .../onap/music/unittests/TstRestMusicDataAPI.java | 2 +- .../onap/music/unittests/TstRestMusicLockAPI.java | 2 +- 16 files changed, 807 insertions(+), 716 deletions(-) create mode 100755 src/main/java/org/onap/music/authentication/CachingUtil.java create mode 100644 src/main/java/org/onap/music/authentication/MusicAuthenticator.java delete mode 100755 src/main/java/org/onap/music/main/CachingUtil.java (limited to 'src') diff --git a/src/main/java/org/onap/music/authentication/CachingUtil.java b/src/main/java/org/onap/music/authentication/CachingUtil.java new file mode 100755 index 00000000..534038e3 --- /dev/null +++ b/src/main/java/org/onap/music/authentication/CachingUtil.java @@ -0,0 +1,490 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018 IBM + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.authentication; + +import java.util.Calendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.jcs.JCS; +import org.apache.commons.jcs.access.CacheAccess; +import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.authentication.MusicAuthenticator.Operation; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.eelf.logging.format.AppMessages; +import org.onap.music.eelf.logging.format.ErrorSeverity; +import org.onap.music.eelf.logging.format.ErrorTypes; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.PreparedStatement; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.exceptions.InvalidQueryException; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; + +/** + * All Caching related logic is handled by this class and a schedule cron runs to update cache. + * + * @author Vikram + * + */ +public class CachingUtil implements Runnable { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class); + + private static CacheAccess musicCache = JCS.getInstance("musicCache"); + private static CacheAccess> aafCache = JCS.getInstance("aafCache"); + private static CacheAccess appNameCache = JCS.getInstance("appNameCache"); + private static CacheAccess> musicValidateCache = JCS.getInstance("musicValidateCache"); + private static CacheAccess> callbackNotifyList = JCS.getInstance("eternalCache"); + private static Map userAttempts = new HashMap<>(); + private static Map lastFailedTime = new HashMap<>(); + private static CacheAccess queryBank = JCS.getInstance("statementBank"); + private static CacheAccess adminUserCache = JCS.getInstance("adminUserCache"); + + public static CacheAccess getAdminUserCache() { + return adminUserCache; + } + + public static void updateAdminUserCache(String authorization,String userId) { + adminUserCache.put(authorization,userId); + } + + + public static void updateStatementBank(String query,PreparedStatement statement) { + queryBank.put(query, statement); + } + + public static void resetStatementBank() { + queryBank.clear(); + } + + public static CacheAccess getStatementBank() { + return queryBank; + } + + private static final String USERNAME="username"; + private static final String PASSWORD="password"; + + + public boolean isCacheRefreshNeeded() { + if (aafCache.get("initBlankMap") == null) + return true; + return false; + } + + public static void updateCallbackNotifyList(List notifyList) { + logger.info("callbackNotifyList: updating cache....."); + callbackNotifyList.put("callbackNotify", notifyList); + } + + public static List getCallbackNotifyList() { + return callbackNotifyList.get("callbackNotify"); + } + + public void initializeMusicCache() { + logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache..."); + musicCache.put("isInitialized", "true"); + } + + public void initializeAafCache() throws MusicServiceException { + logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache..."); + + String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering"; + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString(query); + try { + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false)); + } catch (Exception e1) { + logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + } + ResultSet rs = MusicCore.get(pQuery); + Iterator it = rs.iterator(); + Map map = null; + while (it.hasNext()) { + Row row = it.next(); + String nameSpace = row.getString("keyspace_name"); + String userId = row.getString(USERNAME); + String password = row.getString(PASSWORD); + String keySpace = row.getString("application_name"); + try { + userAttempts.put(nameSpace, 0); + boolean responseObj = triggerAAF(nameSpace, userId, password); + if (responseObj) { + map = new HashMap<>(); + map.put(userId, password); + aafCache.put(nameSpace, map); + musicCache.put(keySpace, nameSpace); + logger.debug("Cronjob: Cache Updated with AAF response for namespace " + + nameSpace); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. "); + } + } + + } + + @Override + public void run() { + logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache..."); + try { + initializeAafCache(); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR); + } + } + + public static boolean authenticateAAFUser(String nameSpace, String userId, String password, + String keySpace) throws Exception { + + if (aafCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) { + if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) { + logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace."); + } else if (aafCache.get(nameSpace).get(userId).equals(password)) { + logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value.."); + // reset invalid attempts to 0 + userAttempts.put(nameSpace, 0); + return true; + } else { + // call AAF update cache with new password + if (userAttempts.get(nameSpace) == null) + userAttempts.put(nameSpace, 0); + if ((Integer) userAttempts.get(nameSpace) >= 3) { + logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out.."); + logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime()); + Calendar calendar = Calendar.getInstance(); + long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis()); + logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime); + if( delayTime > 120000) { + logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt."); + userAttempts.put(nameSpace, 0); + } else { + logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min."); + throw new Exception("No more attempts allowed. Please wait for atleast 2 min."); + } + } + logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again..."); + } + } + + boolean responseObj = false; + try { + responseObj = triggerAAF(nameSpace, userId, password); + }catch (Exception ex) { + logger.info("Exception while trigger aaf"); + logger.info("Exception: " + ex.getMessage()); + throw new Exception("Exception raised while triggering AAF authentication" +ex.getMessage()); + } + if (responseObj) { + logger.info(EELFLoggerDelegate.applicationLogger,"Valid user. Cache is updated for "+nameSpace); + Map map = new HashMap<>(); + map.put(userId, password); + aafCache.put(nameSpace, map); + musicCache.put(keySpace, nameSpace); + return true; + } + logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated"); + return false; + } + + private static boolean triggerAAF(String nameSpace, String userId, String password) + throws Exception { + logger.info(EELFLoggerDelegate.applicationLogger,"Inside AAF authorization"); + if (MusicUtil.getAafEndpointUrl() == null) { + logger.error(EELFLoggerDelegate.errorLogger,"AAF endpoint is not set. Please specify in the properties file.",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + throw new Exception("AAF endpoint is not set. Please specify in the properties file."); + } + Client client = Client.create(); + // WebResource webResource = + // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace); + WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace)); + String plainCreds = userId + ":" + password; + byte[] plainCredsBytes = plainCreds.getBytes(); + byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); + String base64Creds = new String(base64CredsBytes); + + ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON) + .header("Authorization", "Basic " + base64Creds) + .header("content-type", "application/json").get(ClientResponse.class); + logger.info(EELFLoggerDelegate.applicationLogger, "aaf response: "+response.toString()); + if (response.getStatus() != 200) { + if (userAttempts.get(nameSpace) == null) + userAttempts.put(nameSpace, 0); + if ((Integer) userAttempts.get(nameSpace) >= 2) { + lastFailedTime.put(nameSpace, Calendar.getInstance()); + userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1)); + throw new Exception( + "Reached max invalid attempts. Please contact admin and retry with valid credentials."); + } + userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1)); + throw new Exception( + "Unable to authenticate. Please check the AAF credentials against namespace."); + // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values + // for specific time. + } + /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE, + Arrays.asList(MediaType.APPLICATION_JSON)); + // AAFResponse output = response.getEntity(AAFResponse.class); + response.bufferEntity(); + String x = response.getEntity(String.class); + AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/ + + return true; + } + + public static void updateMusicCache(String keyspace, String nameSpace) { + logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace); + musicCache.put(keyspace, nameSpace); + } + + public static void updateCadiCache(String user, String keyspace) { + musicCache.put(user, keyspace); + } + + public static String getKSFromCadiCache(String user) { + return musicCache.get(user); + } + + public static void updateMusicValidateCache(String nameSpace, String userId, String password) { + logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId); + Map map = new HashMap<>(); + map.put(userId, password); + musicValidateCache.put(nameSpace, map); + } + + public static void updateisAAFCache(String namespace, String isAAF) { + appNameCache.put(namespace, isAAF); + } + + public static String isAAFApplication(String namespace) throws MusicServiceException { + String isAAF = appNameCache.get(namespace); + if (isAAF == null) { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "SELECT is_aaf from admin.keyspace_master where application_name = '" + + namespace + "' allow filtering"); + Row rs = null; + try { + rs = MusicCore.get(pQuery).one(); + } catch(InvalidQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage()); + throw new MusicServiceException("Please make sure admin.keyspace_master table is configured."); + } + try { + isAAF = String.valueOf(rs.getBool("is_aaf")); + if(isAAF != null) + appNameCache.put(namespace, isAAF); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + } + } + return isAAF; + } + + public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException { + String uuid = null; + if (uuid == null) { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "SELECT uuid from admin.keyspace_master where keyspace_name = '" + + keyspace + "' allow filtering"); + Row rs = MusicCore.get(pQuery).one(); + try { + uuid = rs.getUUID("uuid").toString(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred during uuid retrieval from DB."+e.getMessage()); + } + } + return uuid; + } + + public static String getAppName(String keyspace) throws MusicServiceException { + String appName = null; + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "SELECT application_name from admin.keyspace_master where keyspace_name = '" + + keyspace + "' allow filtering"); + Row rs = MusicCore.get(pQuery).one(); + try { + appName = rs.getString("application_name"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); + } + return appName; + } + + @Deprecated + public static Map validateRequest(String nameSpace, String userId, + String password, String keyspace, String aid, String operation) { + Map resultMap = new HashMap<>(); + if (!"createKeySpace".equals(operation)) { + if (nameSpace == null) { + resultMap.put("Exception", "Application namespace is mandatory."); + } + } + return resultMap; + } + + public static Map validateRequest(String nameSpace, String userId, + String password, String keyspace, String aid, Operation operation) { + Map resultMap = new HashMap<>(); + if (Operation.CREATE_KEYSPACE!=operation) { + if (nameSpace == null) { + resultMap.put("Exception", "Application namespace is mandatory."); + } + } + return resultMap; + } + + public static Map verifyOnboarding(String ns, String userId, String password) { + Map resultMap = new HashMap<>(); + if (ns == null || userId == null || password == null) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password); + resultMap.put("Exception", + "One or more required headers appName(ns), userId, password is missing. Please check."); + return resultMap; + } + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString( + "select * from admin.keyspace_master where application_name = ? allow filtering"); + try { + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); + } catch(Exception e) { + resultMap.put("Exception", + "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage()); + return resultMap; + } + Row rs = null; + try { + rs = MusicCore.get(queryObject).one(); + } catch (MusicServiceException e) { + String errorMsg = "Unable to process operation. Error is "+e.getMessage(); + logger.error(EELFLoggerDelegate.errorLogger, errorMsg); + resultMap.put("Exception", errorMsg); + return resultMap; + } catch (InvalidQueryException e) { + logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage()); + resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured."); + return resultMap; + } + if (rs == null) { + logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin."); + resultMap.put("Exception", "Application is not onboarded. Please contact admin."); + } else { + if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId); + resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId); + return resultMap; + } + } + return resultMap; + } + + public static Map authenticateAIDUser(String nameSpace, String userId, String password, + String keyspace) { + Map resultMap = new HashMap<>(); + String pwd = null; + if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null) + && (musicValidateCache.get(nameSpace).containsKey(userId))) { + if(!musicCache.get(keyspace).equals(nameSpace)) { + resultMap.put("Exception", "Namespace and keyspace doesn't match"); + return resultMap; + } + if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) { + resultMap.put("Exception", "Namespace, userId and password doesn't match"); + return resultMap; + } + return resultMap; + } + PreparedQueryObject queryObject = new PreparedQueryObject(); + queryObject.appendQueryString( + "select * from admin.keyspace_master where keyspace_name = ? allow filtering"); + try { + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,"Adding value to query object failed: " + e.getMessage()); + } + Row rs = null; + try { + rs = MusicCore.get(queryObject).one(); + } catch (MusicServiceException e) { + String errMsg = "Unable to process operation. Error is "+e.getMessage(); + logger.error(EELFLoggerDelegate.errorLogger, errMsg); + resultMap.put("Exception", errMsg); + return resultMap; + } + if(rs == null) { + resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists."); + return resultMap; + } + else { + String user = rs.getString(USERNAME); + pwd = rs.getString(PASSWORD); + String ns = rs.getString("application_name"); + if(!ns.equals(nameSpace)) { + resultMap.put("Exception", "Namespace and keyspace doesn't match"); + return resultMap; + } + if(!user.equals(userId)) { + resultMap.put("Exception", "Invalid userId :"+userId); + return resultMap; + } + if(!BCrypt.checkpw(password, pwd)) { + resultMap.put("Exception", "Invalid password"); + return resultMap; + } + } + CachingUtil.updateMusicCache(keyspace, nameSpace); + CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd); + return resultMap; + } + + public static void deleteKeysFromDB(String deleteKeys) { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")"); + try { + MusicCore.nonKeyRelatedPut(pQuery, "eventual"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), "Deleting keys from " + + "DB failed."); + } + } +} diff --git a/src/main/java/org/onap/music/authentication/MusicAuthentication.java b/src/main/java/org/onap/music/authentication/MusicAuthentication.java index 1d845b3c..10f1e30c 100644 --- a/src/main/java/org/onap/music/authentication/MusicAuthentication.java +++ b/src/main/java/org/onap/music/authentication/MusicAuthentication.java @@ -34,7 +34,7 @@ import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.CachingUtil; +import org.onap.music.authentication.MusicAuthenticator.Operation; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; @@ -44,7 +44,7 @@ import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; -public class MusicAuthentication { +public class MusicAuthentication implements MusicAuthenticator { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthentication.class); @@ -60,6 +60,7 @@ public class MusicAuthentication { * @return * @throws Exception */ + @Deprecated public static Map autheticateUser(String nameSpace, String userId, String password, String keyspace, String aid, String operation) throws Exception { @@ -142,7 +143,7 @@ public class MusicAuthentication { resultMap.put("uuid", "existing"); } catch (Exception e) { logger.error(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID."); - uuid = CachingUtil.generateUUID(); + uuid = MusicUtil.generateUUID(); resultMap.put("uuid", "new"); } resultMap.put("aid", uuid); @@ -152,21 +153,9 @@ public class MusicAuthentication { return resultMap; } - - public static boolean authenticateAdmin(String id,String password) { - return (id.equals(MusicUtil.getAdminId()) && password.equals(MusicUtil.getAdminPass())); - } - - public static boolean authenticateAdmin(Map adminCredentials) { - if(adminCredentials.containsKey("ERROR")) - return false; - String admin_id = adminCredentials.get(MusicUtil.USERID); - String admin_password = adminCredentials.get(MusicUtil.PASSWORD); - return (admin_id.equals(MusicUtil.getAdminId()) && admin_password.equals(MusicUtil.getAdminPass())); - } - - public static boolean authenticateAdmin(String authorization) throws Exception { - logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: "+authorization); + @Override + public boolean authenticateAdmin(String authorization) { + logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: "); String userId = MusicUtil.extractBasicAuthentication(authorization).get(MusicUtil.USERID); if(MusicUtil.getIsCadi()) { CachingUtil.updateAdminUserCache(authorization, userId); @@ -174,18 +163,23 @@ public class MusicAuthentication { } CacheAccess adminCache = CachingUtil.getAdminUserCache(); if (authorization == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Authorization cannot be empty..."+authorization); - throw new Exception("Authorization cannot be empty"); + logger.error(EELFLoggerDelegate.errorLogger, "Authorization cannot be empty..."); + return false; } if (adminCache.get(authorization) != null && adminCache.get(authorization).equals(userId)) { - logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: Validated against admincache.. "+authorization); + logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: Validated against admincache.. "); return true; } else { Client client = Client.create(); + String aafUrl = MusicUtil.getAafAdminUrl(); + if (aafUrl==null) { + logger.error(EELFLoggerDelegate.errorLogger, "Admin url is not set, please set in properties"); + return false; + } + WebResource webResource = client.resource( MusicUtil.getAafAdminUrl().concat(userId).concat("/").concat(MusicUtil.getAdminAafRole())); - ; ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON) .header("Authorization", authorization).get(ClientResponse.class); @@ -195,7 +189,100 @@ public class MusicAuthentication { } } return false; + } + + @Override + public boolean authenticateUser(String namespace, String authorization, String keyspace, + String aid, Operation operation) { + logger.info(EELFLoggerDelegate.applicationLogger,"Inside User Authentication......."); + Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + Map resultMap = new HashMap<>(); + String uuid = null; + if(! MusicUtil.getIsCadi()) { + resultMap = CachingUtil.validateRequest(namespace, userId, password, keyspace, aid, + operation); + if (!resultMap.isEmpty()) + return false; + String isAAFApp = null; + try { + isAAFApp= CachingUtil.isAAFApplication(namespace); + } catch(MusicServiceException e) { + logger.error(e.getErrorMessage(), e); + resultMap.put("Exception", e.getMessage()); + return false; + } + if(isAAFApp == null) { + resultMap.put("Exception", "Namespace: "+namespace+" doesn't exist. Please make sure ns(appName)" + + " is correct and Application is onboarded."); + return false; + } + boolean isAAF = Boolean.parseBoolean(isAAFApp); + if (userId == null || password == null) { + logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,"UserId/Password or more required headers is missing."); + resultMap.put("Exception", + "UserId and Password are mandatory for the operation " + operation); + return false; + } + if(!isAAF && !(operation==Operation.CREATE_KEYSPACE)) { + resultMap = CachingUtil.authenticateAIDUser(namespace, userId, password, keyspace); + if (!resultMap.isEmpty()) + return false; + + } + if (isAAF && namespace != null && userId != null && password != null) { + boolean isValid = true; + try { + isValid = CachingUtil.authenticateAAFUser(namespace, userId, password, keyspace); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger,"Error while aaf authentication for user:" + userId); + logger.error(EELFLoggerDelegate.errorLogger,"Error: "+ e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + namespace); + resultMap.put("Exception", e.getMessage()); + } + if (!isValid) { + logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated...", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); + resultMap.put("Exception", "User not authenticated..."); + } + if (!resultMap.isEmpty()) + return false; + + } + } else { + + String cachedKS = CachingUtil.getKSFromCadiCache(userId); + if(cachedKS != null && !cachedKS.equals(keyspace)) { + resultMap.put("Exception", "User not authenticated to access this keyspace..."); + return false; + } + } + + if (operation==Operation.CREATE_KEYSPACE) { + try { + logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace."); + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString( + "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering"); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), namespace)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); + pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), + MusicUtil.DEFAULTKEYSPACENAME)); + Row rs = MusicCore.get(pQuery).one(); + uuid = rs.getUUID("uuid").toString(); + resultMap.put("uuid", "existing"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID."); + uuid = MusicUtil.generateUUID(); + resultMap.put("uuid", "new"); + } + resultMap.put("aid", uuid); + CachingUtil.updateCadiCache(userId, keyspace); + } + return true; } } diff --git a/src/main/java/org/onap/music/authentication/MusicAuthenticator.java b/src/main/java/org/onap/music/authentication/MusicAuthenticator.java new file mode 100644 index 00000000..0b1fd5c8 --- /dev/null +++ b/src/main/java/org/onap/music/authentication/MusicAuthenticator.java @@ -0,0 +1,58 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.authentication; + +public interface MusicAuthenticator { + public enum Operation{ + CREATE_KEYSPACE, + DROP_KEYSPACE, + CREATE_TABLE, + CREATE_INDEX, + INSERT_INTO_TABLE, + UPDATE_TABLE, + DELETE_FROM_TABLE, + DROP_TABLE, + SELECT_CRITICAL, + SELECT + } + + /** + * Authenticate a user account + * @param namespace - user's namespace + * @param authorization - basicAuth representation of username/password + * @param keyspace - keyspace user is trying to access + * @param aid - aid that identifies the user + * @param operation - operation that user is trying to do + * @return true if user has access + */ + public boolean authenticateUser(String namespace, String authorization, + String keyspace, String aid, Operation operation); + + /** + * Authenticate an administrative account + * @param authorization - basicAuth representation of username/password + * @return true if user has admin privileges + */ + public boolean authenticateAdmin(String authorization); + +} diff --git a/src/main/java/org/onap/music/datastore/MusicDataStore.java b/src/main/java/org/onap/music/datastore/MusicDataStore.java index 22304f47..f58bd831 100755 --- a/src/main/java/org/onap/music/datastore/MusicDataStore.java +++ b/src/main/java/org/onap/music/datastore/MusicDataStore.java @@ -35,13 +35,13 @@ import java.util.Iterator; import java.util.Map; import org.apache.commons.jcs.access.CacheAccess; +import org.onap.music.authentication.CachingUtil; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicUtil; import com.codahale.metrics.JmxReporter; diff --git a/src/main/java/org/onap/music/lockingservice/zookeeper/MusicLockingService.java b/src/main/java/org/onap/music/lockingservice/zookeeper/MusicLockingService.java index e7cad139..a35e236b 100644 --- a/src/main/java/org/onap/music/lockingservice/zookeeper/MusicLockingService.java +++ b/src/main/java/org/onap/music/lockingservice/zookeeper/MusicLockingService.java @@ -32,6 +32,7 @@ import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; +import org.onap.music.authentication.CachingUtil; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; @@ -39,7 +40,6 @@ import org.onap.music.eelf.logging.format.ErrorTypes; import org.onap.music.exceptions.MusicLockingException; import org.onap.music.exceptions.MusicServiceException; import org.onap.music.lockingservice.cassandra.MusicLockState; -import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicUtil; diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java deleted file mode 100755 index db74aceb..00000000 --- a/src/main/java/org/onap/music/main/CachingUtil.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * Modifications Copyright (c) 2018 IBM - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ - -package org.onap.music.main; - -import java.util.Calendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.ws.rs.core.MediaType; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.jcs.JCS; -import org.apache.commons.jcs.access.CacheAccess; -import org.mindrot.jbcrypt.BCrypt; -import org.onap.music.datastore.PreparedQueryObject; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.eelf.logging.format.AppMessages; -import org.onap.music.eelf.logging.format.ErrorSeverity; -import org.onap.music.eelf.logging.format.ErrorTypes; -import org.onap.music.exceptions.MusicServiceException; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.PreparedStatement; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.exceptions.InvalidQueryException; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; - -/** - * All Caching related logic is handled by this class and a schedule cron runs to update cache. - * - * @author Vikram - * - */ -public class CachingUtil implements Runnable { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class); - - private static CacheAccess musicCache = JCS.getInstance("musicCache"); - private static CacheAccess> aafCache = JCS.getInstance("aafCache"); - private static CacheAccess appNameCache = JCS.getInstance("appNameCache"); - private static CacheAccess> musicValidateCache = JCS.getInstance("musicValidateCache"); - private static CacheAccess> callbackNotifyList = JCS.getInstance("eternalCache"); - private static Map userAttempts = new HashMap<>(); - private static Map lastFailedTime = new HashMap<>(); - private static CacheAccess queryBank = JCS.getInstance("statementBank"); - private static CacheAccess adminUserCache = JCS.getInstance("adminUserCache"); - - public static CacheAccess getAdminUserCache() { - return adminUserCache; - } - - public static void updateAdminUserCache(String authorization,String userId) { - adminUserCache.put(authorization,userId); - } - - - public static void updateStatementBank(String query,PreparedStatement statement) { - queryBank.put(query, statement); - } - - public static void resetStatementBank() { - queryBank.clear(); - } - - public static CacheAccess getStatementBank() { - return queryBank; - } - - private static final String USERNAME="username"; - private static final String PASSWORD="password"; - - - public boolean isCacheRefreshNeeded() { - if (aafCache.get("initBlankMap") == null) - return true; - return false; - } - - public static void updateCallbackNotifyList(List notifyList) { - logger.info("callbackNotifyList: updating cache....."); - callbackNotifyList.put("callbackNotify", notifyList); - } - - public static List getCallbackNotifyList() { - return callbackNotifyList.get("callbackNotify"); - } - - public void initializeMusicCache() { - logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache..."); - musicCache.put("isInitialized", "true"); - } - - public void initializeAafCache() throws MusicServiceException { - logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache..."); - - String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering"; - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString(query); - try { - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false)); - } catch (Exception e1) { - logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); - } - ResultSet rs = MusicCore.get(pQuery); - Iterator it = rs.iterator(); - Map map = null; - while (it.hasNext()) { - Row row = it.next(); - String nameSpace = row.getString("keyspace_name"); - String userId = row.getString(USERNAME); - String password = row.getString(PASSWORD); - String keySpace = row.getString("application_name"); - try { - userAttempts.put(nameSpace, 0); - boolean responseObj = triggerAAF(nameSpace, userId, password); - if (responseObj) { - map = new HashMap<>(); - map.put(userId, password); - aafCache.put(nameSpace, map); - musicCache.put(keySpace, nameSpace); - logger.debug("Cronjob: Cache Updated with AAF response for namespace " - + nameSpace); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR); - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. "); - } - } - - } - - @Override - public void run() { - logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache..."); - try { - initializeAafCache(); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR); - } - } - - public static boolean authenticateAAFUser(String nameSpace, String userId, String password, - String keySpace) throws Exception { - - if (aafCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) { - if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) { - logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace."); - } else if (aafCache.get(nameSpace).get(userId).equals(password)) { - logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value.."); - // reset invalid attempts to 0 - userAttempts.put(nameSpace, 0); - return true; - } else { - // call AAF update cache with new password - if (userAttempts.get(nameSpace) == null) - userAttempts.put(nameSpace, 0); - if ((Integer) userAttempts.get(nameSpace) >= 3) { - logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out.."); - logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime()); - Calendar calendar = Calendar.getInstance(); - long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis()); - logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime); - if( delayTime > 120000) { - logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt."); - userAttempts.put(nameSpace, 0); - } else { - logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min."); - throw new Exception("No more attempts allowed. Please wait for atleast 2 min."); - } - } - logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again..."); - } - } - - boolean responseObj = false; - try { - responseObj = triggerAAF(nameSpace, userId, password); - }catch (Exception ex) { - logger.info("Exception while trigger aaf"); - logger.info("Exception: " + ex.getMessage()); - throw new Exception("Exception raised while triggering AAF authentication" +ex.getMessage()); - } - if (responseObj) { - logger.info(EELFLoggerDelegate.applicationLogger,"Valid user. Cache is updated for "+nameSpace); - Map map = new HashMap<>(); - map.put(userId, password); - aafCache.put(nameSpace, map); - musicCache.put(keySpace, nameSpace); - return true; - } - logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated"); - return false; - } - - private static boolean triggerAAF(String nameSpace, String userId, String password) - throws Exception { - logger.info(EELFLoggerDelegate.applicationLogger,"Inside AAF authorization"); - if (MusicUtil.getAafEndpointUrl() == null) { - logger.error(EELFLoggerDelegate.errorLogger,"AAF endpoint is not set. Please specify in the properties file.",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); - throw new Exception("AAF endpoint is not set. Please specify in the properties file."); - } - Client client = Client.create(); - // WebResource webResource = - // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace); - WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace)); - String plainCreds = userId + ":" + password; - byte[] plainCredsBytes = plainCreds.getBytes(); - byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); - String base64Creds = new String(base64CredsBytes); - - ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON) - .header("Authorization", "Basic " + base64Creds) - .header("content-type", "application/json").get(ClientResponse.class); - logger.info(EELFLoggerDelegate.applicationLogger, "aaf response: "+response.toString()); - if (response.getStatus() != 200) { - if (userAttempts.get(nameSpace) == null) - userAttempts.put(nameSpace, 0); - if ((Integer) userAttempts.get(nameSpace) >= 2) { - lastFailedTime.put(nameSpace, Calendar.getInstance()); - userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1)); - throw new Exception( - "Reached max invalid attempts. Please contact admin and retry with valid credentials."); - } - userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1)); - throw new Exception( - "Unable to authenticate. Please check the AAF credentials against namespace."); - // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values - // for specific time. - } - /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE, - Arrays.asList(MediaType.APPLICATION_JSON)); - // AAFResponse output = response.getEntity(AAFResponse.class); - response.bufferEntity(); - String x = response.getEntity(String.class); - AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/ - - return true; - } - - public static void updateMusicCache(String keyspace, String nameSpace) { - logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace); - musicCache.put(keyspace, nameSpace); - } - - public static void updateCadiCache(String user, String keyspace) { - musicCache.put(user, keyspace); - } - - public static String getKSFromCadiCache(String user) { - return musicCache.get(user); - } - - public static void updateMusicValidateCache(String nameSpace, String userId, String password) { - logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId); - Map map = new HashMap<>(); - map.put(userId, password); - musicValidateCache.put(nameSpace, map); - } - - public static void updateisAAFCache(String namespace, String isAAF) { - appNameCache.put(namespace, isAAF); - } - - public static String isAAFApplication(String namespace) throws MusicServiceException { - String isAAF = appNameCache.get(namespace); - if (isAAF == null) { - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString( - "SELECT is_aaf from admin.keyspace_master where application_name = '" - + namespace + "' allow filtering"); - Row rs = null; - try { - rs = MusicCore.get(pQuery).one(); - } catch(InvalidQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage()); - throw new MusicServiceException("Please make sure admin.keyspace_master table is configured."); - } - try { - isAAF = String.valueOf(rs.getBool("is_aaf")); - if(isAAF != null) - appNameCache.put(namespace, isAAF); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - } - } - return isAAF; - } - - public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException { - String uuid = null; - if (uuid == null) { - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString( - "SELECT uuid from admin.keyspace_master where keyspace_name = '" - + keyspace + "' allow filtering"); - Row rs = MusicCore.get(pQuery).one(); - try { - uuid = rs.getUUID("uuid").toString(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred during uuid retrieval from DB."+e.getMessage()); - } - } - return uuid; - } - - public static String getAppName(String keyspace) throws MusicServiceException { - String appName = null; - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString( - "SELECT application_name from admin.keyspace_master where keyspace_name = '" - + keyspace + "' allow filtering"); - Row rs = MusicCore.get(pQuery).one(); - try { - appName = rs.getString("application_name"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR); - } - return appName; - } - - public static String generateUUID() { - String uuid = UUID.randomUUID().toString(); - logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid); - return uuid; - } - - public static Map validateRequest(String nameSpace, String userId, - String password, String keyspace, String aid, String operation) { - Map resultMap = new HashMap<>(); - if (!"createKeySpace".equals(operation)) { - if (nameSpace == null) { - resultMap.put("Exception", "Application namespace is mandatory."); - } - } - return resultMap; - - } - - public static Map verifyOnboarding(String ns, String userId, String password) { - Map resultMap = new HashMap<>(); - if (ns == null || userId == null || password == null) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password); - resultMap.put("Exception", - "One or more required headers appName(ns), userId, password is missing. Please check."); - return resultMap; - } - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString( - "select * from admin.keyspace_master where application_name = ? allow filtering"); - try { - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); - } catch(Exception e) { - resultMap.put("Exception", - "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage()); - return resultMap; - } - Row rs = null; - try { - rs = MusicCore.get(queryObject).one(); - } catch (MusicServiceException e) { - String errorMsg = "Unable to process operation. Error is "+e.getMessage(); - logger.error(EELFLoggerDelegate.errorLogger, errorMsg); - resultMap.put("Exception", errorMsg); - return resultMap; - } catch (InvalidQueryException e) { - logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage()); - resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured."); - return resultMap; - } - if (rs == null) { - logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin."); - resultMap.put("Exception", "Application is not onboarded. Please contact admin."); - } else { - if(!(rs.getString(USERNAME).equals(userId)) || !(BCrypt.checkpw(password, rs.getString(PASSWORD)))) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId); - resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId); - return resultMap; - } - } - return resultMap; - } - - public static Map authenticateAIDUser(String nameSpace, String userId, String password, - String keyspace) { - Map resultMap = new HashMap<>(); - String pwd = null; - if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null) - && (musicValidateCache.get(nameSpace).containsKey(userId))) { - if(!musicCache.get(keyspace).equals(nameSpace)) { - resultMap.put("Exception", "Namespace and keyspace doesn't match"); - return resultMap; - } - if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) { - resultMap.put("Exception", "Namespace, userId and password doesn't match"); - return resultMap; - } - return resultMap; - } - PreparedQueryObject queryObject = new PreparedQueryObject(); - queryObject.appendQueryString( - "select * from admin.keyspace_master where keyspace_name = ? allow filtering"); - try { - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,"Adding value to query object failed: " + e.getMessage()); - } - Row rs = null; - try { - rs = MusicCore.get(queryObject).one(); - } catch (MusicServiceException e) { - String errMsg = "Unable to process operation. Error is "+e.getMessage(); - logger.error(EELFLoggerDelegate.errorLogger, errMsg); - resultMap.put("Exception", errMsg); - return resultMap; - } - if(rs == null) { - resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists."); - return resultMap; - } - else { - String user = rs.getString(USERNAME); - pwd = rs.getString(PASSWORD); - String ns = rs.getString("application_name"); - if(!ns.equals(nameSpace)) { - resultMap.put("Exception", "Namespace and keyspace doesn't match"); - return resultMap; - } - if(!user.equals(userId)) { - resultMap.put("Exception", "Invalid userId :"+userId); - return resultMap; - } - if(!BCrypt.checkpw(password, pwd)) { - resultMap.put("Exception", "Invalid password"); - return resultMap; - } - } - CachingUtil.updateMusicCache(keyspace, nameSpace); - CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd); - return resultMap; - } - - public static void deleteKeysFromDB(String deleteKeys) { - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString( - "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")"); - try { - MusicCore.nonKeyRelatedPut(pQuery, "eventual"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), "Deleting keys from " - + "DB failed."); - } - } -} diff --git a/src/main/java/org/onap/music/main/CronJobManager.java b/src/main/java/org/onap/music/main/CronJobManager.java index ea2fa685..0d7d9239 100644 --- a/src/main/java/org/onap/music/main/CronJobManager.java +++ b/src/main/java/org/onap/music/main/CronJobManager.java @@ -27,7 +27,7 @@ package org.onap.music.main; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Iterator; - +import org.onap.music.authentication.CachingUtil; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java index dd089683..06eeb805 100755 --- a/src/main/java/org/onap/music/main/MusicUtil.java +++ b/src/main/java/org/onap/music/main/MusicUtil.java @@ -48,7 +48,6 @@ import java.util.concurrent.ConcurrentMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; - import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.eelf.logging.EELFLoggerDelegate; @@ -815,7 +814,6 @@ public class MusicUtil { public static void setIsCadi(boolean isCadi) { - // TODO Auto-generated method stub MusicUtil.isCadi = isCadi; } @@ -859,5 +857,15 @@ public class MusicUtil { return MusicUtil.isCadi; } + + /** + * @return a random uuid + */ + public static String generateUUID() { + String uuid = UUID.randomUUID().toString(); + logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid); + return uuid; + } + } diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 6ad6c03b..0bca1f99 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -46,7 +46,9 @@ import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.authentication.CachingUtil; import org.onap.music.authentication.MusicAuthentication; +import org.onap.music.authentication.MusicAuthenticator; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonOnboard; import org.onap.music.eelf.logging.EELFLoggerDelegate; @@ -54,8 +56,6 @@ import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; import org.onap.music.exceptions.MusicServiceException; -//import org.onap.music.main.CacheAccess; -import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; @@ -80,6 +80,8 @@ public class RestMusicAdminAPI { EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class); // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist. private static final boolean KEYSPACE_ACTIVE = false; + + private MusicAuthenticator authenticator = new MusicAuthentication(); /* * API to onboard an application with MUSIC. This is the mandatory first step. @@ -95,27 +97,22 @@ public class RestMusicAdminAPI { logger.info(EELFLoggerDelegate.errorLogger, "oboarding app"); ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String userId = jsonObj.getUserId(); String isAAF = jsonObj.getIsAAF(); String password = jsonObj.getPassword(); String keyspace_name = jsonObj.getKeyspace(); - try { - if (!MusicAuthentication.authenticateAdmin(authorization)) { - logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response - .entity(new JsonResponse(ResultType.FAILURE) - .setError("Unauthorized: Please check admin username,password and try again").toMap()) - .build(); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Unable to authenticate", e); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } + if (appName == null || userId == null || isAAF == null || password == null) { logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); @@ -137,7 +134,7 @@ public class RestMusicAdminAPI { * " has already been onboarded. Please contact admin.").toMap()).build(); } */ //pQuery = new PreparedQueryObject(); - String uuid = CachingUtil.generateUUID(); + String uuid = MusicUtil.generateUUID(); pQuery.appendQueryString( "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)"); @@ -171,24 +168,20 @@ public class RestMusicAdminAPI { public Response getOnboardedInfoSearch(JsonOnboard jsonObj, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String uuid = jsonObj.getAid(); String isAAF = jsonObj.getIsAAF(); - - try { - if (!MusicAuthentication.authenticateAdmin(authorization)) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response - .entity(new JsonResponse(ResultType.FAILURE) - .setError("Unauthorized: Please check admin username,password and try again").toMap()) - .build(); - } - } catch (Exception e) { - return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } if (appName == null && uuid == null && isAAF == null) { logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); @@ -248,24 +241,21 @@ public class RestMusicAdminAPI { public Response deleteOnboardApp(JsonOnboard jsonObj, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String appName = jsonObj.getAppname(); String aid = jsonObj.getAid(); PreparedQueryObject pQuery = new PreparedQueryObject(); - String consistency = MusicUtil.EVENTUAL;; - try { - if (!MusicAuthentication.authenticateAdmin(authorization)) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response - .entity(new JsonResponse(ResultType.FAILURE) - .setError("Unauthorized: Please check admin username,password and try again").toMap()) - .build(); - } - } catch (Exception e) { - return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } + String consistency = MusicUtil.EVENTUAL; if (appName == null && aid == null) { logger.error(EELFLoggerDelegate.errorLogger, "Please make sure either appName(ns) or Aid is present", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); @@ -358,6 +348,15 @@ public class RestMusicAdminAPI { public Response updateOnboardApp(JsonOnboard jsonObj, @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check admin username,password and try again").toMap()) + .build(); + } + Map resultMap = new HashMap<>(); String aid = jsonObj.getAid(); String appName = jsonObj.getAppname(); @@ -366,19 +365,7 @@ public class RestMusicAdminAPI { String password = jsonObj.getPassword(); String consistency = "eventual"; PreparedQueryObject pQuery; - try { - if (!MusicAuthentication.authenticateAdmin(authorization)) { - logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response - .entity(new JsonResponse(ResultType.FAILURE) - .setError("Unauthorized: Please check admin username,password and try again").toMap()) - .build(); - } - } catch (Exception e) { - return response.entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } + if (aid == null) { resultMap.put("Exception", "Please make sure Aid is present"); logger.error(EELFLoggerDelegate.errorLogger, "Please make sure Aid is present", AppMessages.MISSINGDATA, @@ -458,6 +445,12 @@ public class RestMusicAdminAPI { List appList = new ArrayList<>(); ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return appList; + } + PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("SELECT * FROM " + "admin" + "." + "keyspace_master" + ";"); ResultSet results = MusicCore.get(queryObject); @@ -484,6 +477,11 @@ public class RestMusicAdminAPI { @ApiParam(value = "uuid", required = true) @HeaderParam("uuid") String uuid) throws Exception { ResponseBuilder response = Response.noContent().header("X-latestVersion", MusicUtil.getVersion()); + if (!authenticator.authenticateAdmin(authorization)) { + logger.error(EELFLoggerDelegate.errorLogger, "Unauthorized: Please check admin username,password and try again", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.CRITICAL, + ErrorTypes.AUTHENTICATIONERROR); + return false; + } PreparedQueryObject queryObject = new PreparedQueryObject(); queryObject.appendQueryString("delete from admin.keyspace_master where uuid=?"); queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),uuid)); @@ -495,15 +493,4 @@ public class RestMusicAdminAPI { } return true; } - - - @GET - @Path("/login") - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - public boolean login(@ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization) throws Exception { - - boolean result = MusicAuthentication.authenticateAdmin(authorization); - return result; - } } diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index 80654935..ff44abf7 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -48,7 +48,10 @@ import javax.ws.rs.core.UriInfo; import org.apache.commons.lang3.StringUtils; import org.mindrot.jbcrypt.BCrypt; +import org.onap.music.authentication.CachingUtil; import org.onap.music.authentication.MusicAuthentication; +import org.onap.music.authentication.MusicAuthenticator; +import org.onap.music.authentication.MusicAuthenticator.Operation; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonDelete; import org.onap.music.datastore.jsonobjects.JsonInsert; @@ -62,7 +65,6 @@ import org.onap.music.eelf.logging.format.AppMessages; import org.onap.music.eelf.logging.format.ErrorSeverity; import org.onap.music.eelf.logging.format.ErrorTypes; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.datastore.Condition; import org.onap.music.datastore.MusicDataStoreHandle; @@ -115,6 +117,7 @@ public class RestMusicDataAPI { private static final String XPATCHVERSION = "X-patchVersion"; private static final String NS = "ns"; private static final String VERSION = "v2"; + private MusicAuthenticator authenticator = new MusicAuthentication(); // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist. private static final boolean KEYSPACE_ACTIVE = false; @@ -147,7 +150,6 @@ public class RestMusicDataAPI { @ApiOperation(value = "Create Keyspace", response = String.class,hidden = true) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - //public Map createKeySpace( public Response createKeySpace( @ApiParam(value = "Major Version",required = true) @PathParam("version") String version, @ApiParam(value = "Minor Version",required = false) @HeaderParam(XMINORVERSION) String minorVersion, @@ -409,17 +411,13 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, - aid, "createTable"); - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); - } + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_TABLE)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); + } + String consistency = MusicUtil.EVENTUAL; // for now this needs only eventual consistency @@ -640,17 +638,13 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace,aid, "createIndex"); - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); - } + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.CREATE_INDEX)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); + } + MultivaluedMap rowParams = info.getQueryParameters(); String indexName = ""; if (rowParams.getFirst("index_name") != null) @@ -710,23 +704,11 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = null; - - try { - authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, - aid, "insertIntoTable"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.INSERT_INTO_TABLE)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); } Map valuesMap = insObj.getValues(); @@ -738,7 +720,7 @@ public class RestMusicDataAPI { return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Table name doesn't exists. Please check the table name.").toMap()).build(); } } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); @@ -769,7 +751,7 @@ public class RestMusicDataAPI { try { formattedValue = MusicUtil.convertToActualDataType(colType, valueObj); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e); } valueString.append("?"); @@ -942,23 +924,13 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap; - try { - authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, - aid, "updateTable"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.UPDATE_TABLE)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); } + long startTime = System.currentTimeMillis(); String operationId = UUID.randomUUID().toString();// just for infoging // purposes. @@ -975,7 +947,7 @@ public class RestMusicDataAPI { try { tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename); } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } if (tableInfo == null) { @@ -995,14 +967,14 @@ public class RestMusicDataAPI { try { colType = tableInfo.getColumn(entry.getKey()).getType(); } catch(NullPointerException ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Invalid column name : "+entry.getKey()); + logger.error(EELFLoggerDelegate.errorLogger, ex, "Invalid column name : "+entry.getKey()); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build(); } Object valueString = null; try { valueString = MusicUtil.convertToActualDataType(colType, valueObj); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e); } fieldValueString.append(entry.getKey() + "= ?"); queryObject.addValue(valueString); @@ -1042,7 +1014,7 @@ public class RestMusicDataAPI { .setError("Mandatory WHERE clause is missing. Please check the input request.").toMap()).build(); } } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } @@ -1090,7 +1062,7 @@ public class RestMusicDataAPI { operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) { @@ -1098,7 +1070,7 @@ public class RestMusicDataAPI { operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue, queryObject, conditionInfo); } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); } }else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) { @@ -1175,23 +1147,13 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = null; - try { - authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace, - aid, "deleteFromTable"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build(); - } - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DELETE_FROM_TABLE)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); } + if(delObj == null) { logger.error(EELFLoggerDelegate.errorLogger,"Required HTTP Request body is missing.", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap()).build(); @@ -1215,7 +1177,7 @@ public class RestMusicDataAPI { try { rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } String rowSpec = rowId.rowIdString.toString(); @@ -1285,7 +1247,7 @@ public class RestMusicDataAPI { operationResult = MusicCore.eventualPut_nb(queryObject, keyspace, tablename, rowId.primarKeyValue); } } catch (MusicLockingException e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE) .setError("Unable to perform Delete operation. Exception from music").toMap()).build(); } @@ -1338,17 +1300,13 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = - MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "dropTable"); - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.DROP_TABLE)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); } + String consistency = "eventual";// for now this needs only eventual // consistency PreparedQueryObject query = new PreparedQueryObject(); @@ -1356,7 +1314,7 @@ public class RestMusicDataAPI { try { return response.status(Status.OK).entity(new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap()).build(); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } } finally { @@ -1402,16 +1360,13 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspace,aid, "selectCritical"); - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT_CRITICAL)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); } + String lockId = selObj.getConsistencyInfo().get("lockId"); PreparedQueryObject queryObject = new PreparedQueryObject(); @@ -1420,7 +1375,7 @@ public class RestMusicDataAPI { try { rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } queryObject.appendQueryString( @@ -1492,17 +1447,13 @@ public class RestMusicDataAPI { .toMap()).build(); } EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspace+" ) "); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = - MusicAuthentication.autheticateUser(ns, userId, password, keyspace, aid, "select"); - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspace, aid, Operation.SELECT)) { + return response.status(Status.UNAUTHORIZED) + .entity(new JsonResponse(ResultType.FAILURE) + .setError("Unauthorized: Please check username, password and make sure your app is onboarded") + .toMap()).build(); } + PreparedQueryObject queryObject = new PreparedQueryObject(); if (info.getQueryParameters().isEmpty())// select all @@ -1510,10 +1461,9 @@ public class RestMusicDataAPI { else { int limit = -1; // do not limit the number of results try { - queryObject = selectSpecificQuery(VERSION, minorVersion, patchVersion, aid, ns, - userId, password, keyspace, tablename, info, limit); + queryObject = selectSpecificQuery(keyspace, tablename, info, limit); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } } @@ -1525,7 +1475,7 @@ public class RestMusicDataAPI { } return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicDataStoreHandle.marshallResults(results)).setError("No data found").toMap()).build(); } catch (MusicServiceException ex) { - logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); + logger.error(EELFLoggerDelegate.errorLogger, ex, AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR); return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build(); } } finally { @@ -1542,9 +1492,8 @@ public class RestMusicDataAPI { * @return * @throws MusicServiceException */ - public PreparedQueryObject selectSpecificQuery(String version, String minorVersion, - String patchVersion, String aid, String ns, String userId, String password, - String keyspace, String tablename, UriInfo info, int limit) + public PreparedQueryObject selectSpecificQuery(String keyspace, + String tablename, UriInfo info, int limit) throws MusicServiceException { PreparedQueryObject queryObject = new PreparedQueryObject(); @@ -1597,7 +1546,7 @@ public class RestMusicDataAPI { colType = tableInfo.getColumn(entry.getKey()).getType(); formattedValue = MusicUtil.convertToActualDataType(colType, indValue); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger,e); } if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) primaryKey.append(indValue); diff --git a/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/src/main/java/org/onap/music/rest/RestMusicQAPI.java index 4164f27f..800dad71 100755 --- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicQAPI.java @@ -377,8 +377,7 @@ public class RestMusicQAPI { else { try { - queryObject = new RestMusicDataAPI().selectSpecificQuery(version, minorVersion, - patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); + queryObject = new RestMusicDataAPI().selectSpecificQuery(keyspace, tablename, info, limit); } catch (MusicServiceException ex) { logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR, ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR); diff --git a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java index ab10335e..ec17d17d 100644 --- a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java +++ b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java @@ -34,10 +34,10 @@ import org.junit.runners.MethodSorters; import org.mockito.Mock; import org.onap.music.exceptions.MusicQueryException; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.CachingUtil; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.onap.music.authentication.CachingUtil; import org.onap.music.datastore.MusicDataStore; import org.onap.music.datastore.PreparedQueryObject; diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java index b00c4fcc..38be56fa 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java @@ -194,8 +194,7 @@ public class TstRestMusicAdminAPI { Response response = admin.getOnboardedInfoSearch(jsonOnboard,adminAuthorization); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); //TODO FIX when we can authenticate - //should be 401 error - assertEquals(204, response.getStatus()); + assertEquals(401, response.getStatus()); } // Missing appname @@ -255,8 +254,7 @@ public class TstRestMusicAdminAPI { Response response = admin.updateOnboardApp(jsonOnboard,adminAuthorization); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - //Should be 401 error - assertEquals(204, response.getStatus()); + assertEquals(401, response.getStatus()); } // Aid null @@ -296,6 +294,7 @@ public class TstRestMusicAdminAPI { assertNotNull(resultMap); } + @Ignore @Test public void test9_onboardDelete() throws Exception { JsonOnboard jsonOnboard = new JsonOnboard(); @@ -315,8 +314,7 @@ public class TstRestMusicAdminAPI { Response response = admin.deleteOnboardApp(jsonOnboard,adminAuthorization); System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity()); - //Should be 401 error - assertEquals(204, response.getStatus()); + assertEquals(401, response.getStatus()); } @Ignore diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java index 1f0e24c2..6e661da6 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java @@ -40,6 +40,7 @@ import org.mindrot.jbcrypt.BCrypt; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.authentication.CachingUtil; import org.onap.music.conductor.conditionals.JsonConditional; import org.onap.music.conductor.conditionals.RestMusicConditionalAPI; import org.onap.music.datastore.MusicDataStoreHandle; @@ -51,7 +52,6 @@ import org.onap.music.datastore.jsonobjects.JsonSelect; import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java index 0f0545e8..a8345d86 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java @@ -40,6 +40,7 @@ import org.mindrot.jbcrypt.BCrypt; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.authentication.CachingUtil; import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonDelete; @@ -49,7 +50,6 @@ import org.onap.music.datastore.jsonobjects.JsonSelect; import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.datastore.jsonobjects.JsonUpdate; import org.onap.music.exceptions.MusicServiceException; -import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.main.ResultType; diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java index 7e45e160..3896c52f 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java @@ -36,6 +36,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mindrot.jbcrypt.BCrypt; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.authentication.CachingUtil; import org.onap.music.datastore.MusicDataStoreHandle; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonInsert; @@ -43,7 +44,6 @@ import org.onap.music.datastore.jsonobjects.JsonLeasedLock; import org.onap.music.datastore.jsonobjects.JsonTable; import org.onap.music.exceptions.MusicServiceException; import org.onap.music.lockingservice.cassandra.CassaLockStore; -import org.onap.music.main.CachingUtil; import org.onap.music.main.MusicCore; import org.onap.music.main.MusicUtil; import org.onap.music.rest.RestMusicDataAPI; -- cgit 1.2.3-korg