diff options
15 files changed, 333 insertions, 242 deletions
diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/authentication/CachingUtil.java index db74aceb..534038e3 100755 --- a/src/main/java/org/onap/music/main/CachingUtil.java +++ b/src/main/java/org/onap/music/authentication/CachingUtil.java @@ -23,28 +23,28 @@ * ==================================================================== */ -package org.onap.music.main; +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 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.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; @@ -348,12 +348,7 @@ public class CachingUtil implements Runnable { return appName; } - public static String generateUUID() { - String uuid = UUID.randomUUID().toString(); - logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid); - return uuid; - } - + @Deprecated public static Map<String, Object> validateRequest(String nameSpace, String userId, String password, String keyspace, String aid, String operation) { Map<String, Object> resultMap = new HashMap<>(); @@ -363,9 +358,19 @@ public class CachingUtil implements Runnable { } } return resultMap; - } + public static Map<String, Object> validateRequest(String nameSpace, String userId, + String password, String keyspace, String aid, Operation operation) { + Map<String, Object> resultMap = new HashMap<>(); + if (Operation.CREATE_KEYSPACE!=operation) { + if (nameSpace == null) { + resultMap.put("Exception", "Application namespace is mandatory."); + } + } + return resultMap; + } + public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) { Map<String, Object> resultMap = new HashMap<>(); if (ns == null || userId == null || password == null) { 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<String, Object> 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<String,String> 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<String, String> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); + String userId = userCredentials.get(MusicUtil.USERID); + String password = userCredentials.get(MusicUtil.PASSWORD); + Map<String, Object> 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/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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<Application> 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 973bd44e..f72a1ac9 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<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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<String, String> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map<String, Object> 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 93d8fcb9..58d1d11b 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java @@ -193,8 +193,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 @@ -254,8 +253,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 @@ -295,6 +293,7 @@ public class TstRestMusicAdminAPI { assertNotNull(resultMap); } + @Ignore @Test public void test9_onboardDelete() throws Exception { JsonOnboard jsonOnboard = new JsonOnboard(); @@ -314,8 +313,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 e253d185..3adab912 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java @@ -39,6 +39,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; @@ -50,7 +51,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 a4ea84f0..07a1b8e1 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java @@ -39,6 +39,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; @@ -48,7 +49,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; |