From 4d6e2a982cc0ee48aca9d8531424d795e44842c9 Mon Sep 17 00:00:00 2001 From: "Tschaen, Brendan" Date: Thu, 28 Feb 2019 13:57:51 -0500 Subject: Complete new authentication across REST APIs Change-Id: I0d8ae84bdebbad986d557f722047318d5b72b591 Issue-ID: MUSIC-345 Signed-off-by: Tschaen, Brendan --- src/main/java/org/onap/music/CadiAuthFilter.java | 110 -------- src/main/java/org/onap/music/MusicApplication.java | 1 + .../org/onap/music/authentication/CachingUtil.java | 14 - .../onap/music/authentication/CadiAuthFilter.java | 110 ++++++++ .../authentication/MusicAAFAuthentication.java | 183 +++++++++++++ .../music/authentication/MusicAuthentication.java | 294 --------------------- .../music/authentication/MusicAuthenticator.java | 6 +- .../conditionals/RestMusicConditionalAPI.java | 67 ++--- .../org/onap/music/rest/RestMusicAdminAPI.java | 4 +- .../java/org/onap/music/rest/RestMusicDataAPI.java | 56 ++-- .../org/onap/music/rest/RestMusicLocksAPI.java | 134 ++++------ .../onap/music/unittests/TstRestMusicAdminAPI.java | 6 +- 12 files changed, 396 insertions(+), 589 deletions(-) delete mode 100644 src/main/java/org/onap/music/CadiAuthFilter.java create mode 100644 src/main/java/org/onap/music/authentication/CadiAuthFilter.java create mode 100644 src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java delete mode 100644 src/main/java/org/onap/music/authentication/MusicAuthentication.java (limited to 'src') diff --git a/src/main/java/org/onap/music/CadiAuthFilter.java b/src/main/java/org/onap/music/CadiAuthFilter.java deleted file mode 100644 index 62bf9c73..00000000 --- a/src/main/java/org/onap/music/CadiAuthFilter.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 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; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.aaf.cadi.CadiWrap; -import org.onap.aaf.cadi.Permission; -import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.aaf.AAFPermission; -import org.onap.aaf.cadi.filter.CadiFilter; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.main.MusicCore; - -public class CadiAuthFilter extends CadiFilter { - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CadiAuthFilter.class); - - public CadiAuthFilter(PropAccess access) throws ServletException { - super(true, access); - } - - public void init(FilterConfig filterConfig) throws ServletException { - super.init(filterConfig); - } - - - private boolean matchPattern(String requestedPath, String includeUrl) { - includeUrl = includeUrl.substring(1); - String[] path = requestedPath.split("/"); - if (path.length > 1) { - String[] roleFunctionArray = includeUrl.split("/"); - boolean match = true; - for (int i = 0; i < roleFunctionArray.length; i++) { - if (match) { - if (!"*".equals(roleFunctionArray[i])) { - Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE); - Matcher m = p.matcher(roleFunctionArray[i]); - match = m.matches(); - } else if (roleFunctionArray[i].equals("*")) { - match = true; - } - - } - } - if (match) - return match; - } else { - if (requestedPath.matches(includeUrl)) - return true; - else if ("*".equals(includeUrl)) - return true; - } - return false; - } - - - public static List getAAFPermissions(HttpServletRequest request) { - CadiWrap wrapReq = (CadiWrap) request; - List perms = wrapReq.getPermissions(wrapReq.getUserPrincipal()); - List aafPermsList = new ArrayList<>(); - for (Permission perm : perms) { - AAFPermission aafPerm = (AAFPermission) perm; - aafPermsList.add(aafPerm); - logger.info(aafPerm.toString()); - logger.info(aafPerm.getType()); - } - return aafPermsList; - } - - public static List getAAFPermissions(ServletRequest request) { - CadiWrap wrapReq = (CadiWrap) request; - List perms = wrapReq.getPermissions(wrapReq.getUserPrincipal()); - List aafPermsList = new ArrayList<>(); - for (Permission perm : perms) { - AAFPermission aafPerm = (AAFPermission) perm; - aafPermsList.add(aafPerm); - } - return aafPermsList; - } - -} \ No newline at end of file diff --git a/src/main/java/org/onap/music/MusicApplication.java b/src/main/java/org/onap/music/MusicApplication.java index 90bcbbae..e6fee58f 100755 --- a/src/main/java/org/onap/music/MusicApplication.java +++ b/src/main/java/org/onap/music/MusicApplication.java @@ -30,6 +30,7 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.onap.aaf.cadi.PropAccess; +import org.onap.music.authentication.CadiAuthFilter; import org.onap.music.main.MusicUtil; import org.onap.music.main.PropertiesLoader; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/main/java/org/onap/music/authentication/CachingUtil.java b/src/main/java/org/onap/music/authentication/CachingUtil.java index 80eed1e6..5c379c6e 100755 --- a/src/main/java/org/onap/music/authentication/CachingUtil.java +++ b/src/main/java/org/onap/music/authentication/CachingUtil.java @@ -72,7 +72,6 @@ public class CachingUtil implements Runnable { private static CacheAccess> musicValidateCache = JCS.getInstance("musicValidateCache"); 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() { @@ -83,19 +82,6 @@ public class CachingUtil implements Runnable { 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"; diff --git a/src/main/java/org/onap/music/authentication/CadiAuthFilter.java b/src/main/java/org/onap/music/authentication/CadiAuthFilter.java new file mode 100644 index 00000000..56371c7d --- /dev/null +++ b/src/main/java/org/onap/music/authentication/CadiAuthFilter.java @@ -0,0 +1,110 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 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; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.http.HttpServletRequest; + +import com.att.eelf.configuration.EELFLogger; +import org.onap.aaf.cadi.CadiWrap; +import org.onap.aaf.cadi.Permission; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.aaf.AAFPermission; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.main.MusicCore; + +public class CadiAuthFilter extends CadiFilter { + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CadiAuthFilter.class); + + public CadiAuthFilter(PropAccess access) throws ServletException { + super(true, access); + } + + public void init(FilterConfig filterConfig) throws ServletException { + super.init(filterConfig); + } + + + private boolean matchPattern(String requestedPath, String includeUrl) { + includeUrl = includeUrl.substring(1); + String[] path = requestedPath.split("/"); + if (path.length > 1) { + String[] roleFunctionArray = includeUrl.split("/"); + boolean match = true; + for (int i = 0; i < roleFunctionArray.length; i++) { + if (match) { + if (!"*".equals(roleFunctionArray[i])) { + Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(roleFunctionArray[i]); + match = m.matches(); + } else if (roleFunctionArray[i].equals("*")) { + match = true; + } + + } + } + if (match) + return match; + } else { + if (requestedPath.matches(includeUrl)) + return true; + else if ("*".equals(includeUrl)) + return true; + } + return false; + } + + + public static List getAAFPermissions(HttpServletRequest request) { + CadiWrap wrapReq = (CadiWrap) request; + List perms = wrapReq.getPermissions(wrapReq.getUserPrincipal()); + List aafPermsList = new ArrayList<>(); + for (Permission perm : perms) { + AAFPermission aafPerm = (AAFPermission) perm; + aafPermsList.add(aafPerm); + logger.info(aafPerm.toString()); + logger.info(aafPerm.getType()); + } + return aafPermsList; + } + + public static List getAAFPermissions(ServletRequest request) { + CadiWrap wrapReq = (CadiWrap) request; + List perms = wrapReq.getPermissions(wrapReq.getUserPrincipal()); + List aafPermsList = new ArrayList<>(); + for (Permission perm : perms) { + AAFPermission aafPerm = (AAFPermission) perm; + aafPermsList.add(aafPerm); + } + return aafPermsList; + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java b/src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java new file mode 100644 index 00000000..2d0d4e59 --- /dev/null +++ b/src/main/java/org/onap/music/authentication/MusicAAFAuthentication.java @@ -0,0 +1,183 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 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; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.MediaType; + +import org.apache.commons.jcs.access.CacheAccess; +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.authentication.MusicAuthenticator.Operation; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; + +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.Row; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; + +public class MusicAAFAuthentication implements MusicAuthenticator { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAAFAuthentication.class); + + @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); + return true; + } + CacheAccess adminCache = CachingUtil.getAdminUserCache(); + if (authorization == null) { + 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.. "); + 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); + if (response.getStatus() == 200) { + CachingUtil.updateAdminUserCache(authorization, userId); + return true; + } + } + 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/MusicAuthentication.java b/src/main/java/org/onap/music/authentication/MusicAuthentication.java deleted file mode 100644 index 6c38e6df..00000000 --- a/src/main/java/org/onap/music/authentication/MusicAuthentication.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 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; - -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.core.MediaType; - -import org.apache.commons.jcs.access.CacheAccess; -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.authentication.MusicAuthenticator.Operation; -import org.onap.music.main.MusicCore; -import org.onap.music.main.MusicUtil; - -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.Row; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; - -public class MusicAuthentication implements MusicAuthenticator { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthentication.class); - - /** - * authenticate user logic - * - * @param nameSpace - * @param userId - * @param password - * @param keyspace - * @param aid - * @param operation - * @return - * @throws Exception - */ - @Deprecated - public static Map autheticateUser(String nameSpace, String userId, - String password, String keyspace, String aid, String operation) { - logger.info(EELFLoggerDelegate.applicationLogger,"Inside User Authentication......."); - Map resultMap = new HashMap<>(); - String uuid = null; - if(! MusicUtil.getIsCadi()) { - resultMap = CachingUtil.validateRequest(nameSpace, userId, password, keyspace, aid, - operation); - if (!resultMap.isEmpty()) - return resultMap; - String isAAFApp = null; - try { - isAAFApp= CachingUtil.isAAFApplication(nameSpace); - } catch(MusicServiceException e) { - logger.error(e.getErrorMessage(), e); - resultMap.put("Exception", e.getMessage()); - return resultMap; - } - if(isAAFApp == null) { - resultMap.put("Exception", "Namespace: "+nameSpace+" doesn't exist. Please make sure ns(appName)" - + " is correct and Application is onboarded."); - return resultMap; - } - boolean isAAF = Boolean.parseBoolean(isAAFApp); - if (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", - "UserId and Password are mandatory for the operation " + operation); - return resultMap; - } - if(!isAAF && !(operation.equals("createKeySpace"))) { - resultMap = CachingUtil.authenticateAIDUser(nameSpace, userId, password, keyspace); - if (!resultMap.isEmpty()) - return resultMap; - - } - 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 resultMap; - - } - } else { - - String cachedKS = CachingUtil.getKSFromCadiCache(userId); - if(cachedKS != null && !cachedKS.equals(keyspace)) { - resultMap.put("Exception", "User not authenticated to access this keyspace..."); - } - } - - if (operation.equals("createKeySpace")) { - 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"); - try { - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), nameSpace)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId)); - pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), - MusicUtil.DEFAULTKEYSPACENAME)); - } catch (Exception e1) { - logger.error(EELFLoggerDelegate.errorLogger, e1, "Can not authenticate for createkeyspace", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR); - resultMap.put("Exception", "Cannot authenticate for createKeyspace"); - return resultMap; - } - - - try { - 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 resultMap; - } - - @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); - return true; - } - CacheAccess adminCache = CachingUtil.getAdminUserCache(); - if (authorization == null) { - 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.. "); - 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); - if (response.getStatus() == 200) { - CachingUtil.updateAdminUserCache(authorization, userId); - return true; - } - } - 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 index 0b1fd5c8..78f76ab1 100644 --- a/src/main/java/org/onap/music/authentication/MusicAuthenticator.java +++ b/src/main/java/org/onap/music/authentication/MusicAuthenticator.java @@ -33,7 +33,11 @@ public interface MusicAuthenticator { DELETE_FROM_TABLE, DROP_TABLE, SELECT_CRITICAL, - SELECT + SELECT, + CREATE_LOCKREF, + ACQUIRE_LOCK, + CURRENT_LOCK, + DELETE_LOCK } /** diff --git a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java b/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java index 6ea05c7b..20fd3150 100644 --- a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java +++ b/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java @@ -52,7 +52,9 @@ import org.onap.music.main.ResultType; import org.onap.music.main.ReturnType; import org.onap.music.response.jsonobjects.JsonResponse; import org.onap.music.rest.RestMusicAdminAPI; -import org.onap.music.authentication.MusicAuthentication; +import org.onap.music.authentication.MusicAAFAuthentication; +import org.onap.music.authentication.MusicAuthenticator; +import org.onap.music.authentication.MusicAuthenticator.Operation; import org.onap.music.conductor.*; import com.datastax.driver.core.DataType; @@ -69,6 +71,8 @@ public class RestMusicConditionalAPI { private static final String XPATCHVERSION = "X-patchVersion"; private static final String NS = "ns"; private static final String VERSION = "v2"; + + private MusicAuthenticator authenticator = new MusicAAFAuthentication(); @POST @Path("/insert/keyspaces/{keyspace}/tables/{tablename}") @@ -85,6 +89,14 @@ public class RestMusicConditionalAPI { @ApiParam(value = "Table Name", required = true) @PathParam("tablename") String tablename, JsonConditional jsonObj) throws Exception { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); + + 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(); + } + String primaryKey = jsonObj.getPrimaryKey(); String primaryKeyValue = jsonObj.getPrimaryKeyValue(); String casscadeColumnName = jsonObj.getCasscadeColumnName(); @@ -100,28 +112,6 @@ public class RestMusicConditionalAPI { .setError(String.valueOf("One or more input values missing")).toMap()).build(); } - 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, "", 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, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity( - new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()) - .build(); - } Map valuesMap = new LinkedHashMap<>(); for (Map.Entry entry : tableValues.entrySet()) { @@ -156,7 +146,14 @@ public class RestMusicConditionalAPI { @ApiParam(value = "Major Version", required = true) @PathParam("tablename") String tablename, JsonConditional upObj) throws Exception { ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion); - + + 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(); + } + String primaryKey = upObj.getPrimaryKey(); String primaryKeyValue = upObj.getPrimaryKeyValue(); String casscadeColumnName = upObj.getCasscadeColumnName(); @@ -171,28 +168,6 @@ public class RestMusicConditionalAPI { .setError(String.valueOf("One or more input values missing")).toMap()).build(); } - 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, "updateTable"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "", 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, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL, - ErrorTypes.AUTHENTICATIONERROR); - return response.status(Status.UNAUTHORIZED).entity( - new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()) - .build(); - } String planId = casscadeColumnData.get("key").toString(); Map casscadeColumnValueMap = (Map) casscadeColumnData.get("value"); diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java index 26069ebe..adcb6584 100755 --- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java @@ -47,7 +47,7 @@ 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.MusicAAFAuthentication; import org.onap.music.authentication.MusicAuthenticator; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonOnboard; @@ -81,7 +81,7 @@ public class RestMusicAdminAPI { // 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(); + private MusicAuthenticator authenticator = new MusicAAFAuthentication(); /* * API to onboard an application with MUSIC. This is the mandatory first step. diff --git a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java index a7522b90..dfcf0bdb 100755 --- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicDataAPI.java @@ -49,7 +49,7 @@ 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.MusicAAFAuthentication; import org.onap.music.authentication.MusicAuthenticator; import org.onap.music.authentication.MusicAuthenticator.Operation; import org.onap.music.datastore.PreparedQueryObject; @@ -117,7 +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(); + private MusicAuthenticator authenticator = new MusicAAFAuthentication(); // Set to true in env like ONAP. Where access to creating and dropping keyspaces exist. private static final boolean KEYSPACE_ACTIVE = false; @@ -174,34 +174,21 @@ public class RestMusicDataAPI { response.status(Status.UNAUTHORIZED); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap()).build(); } - if(kspObject == null || kspObject.getReplicationInfo() == null) { - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); - } - - try { - authMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "createKeySpace"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR); - response.status(Status.BAD_REQUEST); - return response.entity(new JsonResponse(ResultType.FAILURE).setError("Unable to authenticate.").toMap()).build(); - } - String newAid = null; - if (!authMap.isEmpty()) { - if (authMap.containsKey("aid")) { - newAid = (String) authMap.get("aid"); - } else { - logger.error(EELFLoggerDelegate.errorLogger,String.valueOf(authMap.get("Exception")), AppMessages.MISSINGDATA ,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, keyspaceName, aid, Operation.CREATE_KEYSPACE)) { + 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 + if(kspObject == null || kspObject.getReplicationInfo() == null) { + response.status(Status.BAD_REQUEST); + return response.entity(new JsonResponse(ResultType.FAILURE).setError(ResultType.BODYMISSING.getResult()).toMap()).build(); + } PreparedQueryObject queryObject = new PreparedQueryObject(); if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && kspObject.getConsistencyInfo().get("consistency") != null) { if(MusicUtil.isValidConsistency(kspObject.getConsistencyInfo().get("consistency"))) @@ -260,7 +247,7 @@ public class RestMusicDataAPI { queryObject.appendQueryString( "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, " + "password, username, is_aaf) values (?,?,?,?,?,?,?)"); - queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid)); + queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), aid)); queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName)); queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns)); queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True")); @@ -312,17 +299,12 @@ public class RestMusicDataAPI { EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); logger.info(EELFLoggerDelegate.applicationLogger,"In Drop Keyspace " + keyspaceName); if ( KEYSPACE_ACTIVE ) { - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - Map authMap = MusicAuthentication.autheticateUser(ns, userId, password,keyspaceName, aid, "dropKeySpace"); - if (authMap.containsKey("aid")) - authMap.remove("aid"); - if (!authMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,authMap.get("Exception").toString(), AppMessages.MISSINGDATA ,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, keyspaceName, aid, Operation.DROP_KEYSPACE)) { + 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 diff --git a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java index 0bb2368a..b3e3b4d5 100644 --- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java +++ b/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java @@ -37,7 +37,9 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; -import org.onap.music.authentication.MusicAuthentication; +import org.onap.music.authentication.MusicAAFAuthentication; +import org.onap.music.authentication.MusicAuthenticator; +import org.onap.music.authentication.MusicAuthenticator.Operation; import org.onap.music.datastore.jsonobjects.JsonLeasedLock; import org.onap.music.eelf.logging.EELFLoggerDelegate; import org.onap.music.eelf.logging.format.AppMessages; @@ -63,6 +65,8 @@ public class RestMusicLocksAPI { private static final String XMINORVERSION = "X-minorVersion"; private static final String XPATCHVERSION = "X-patchVersion"; private static final String VERSION = "v2"; + + private MusicAuthenticator authenticator = new MusicAAFAuthentication(); /** * Puts the requesting process in the q for this lock. The corresponding @@ -96,21 +100,16 @@ public class RestMusicLocksAPI { response.status(Status.BAD_REQUEST); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); - resultMap.remove("keyspace"); - resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "createLockReference"); - if (resultMap.containsKey("aid")) - resultMap.remove("aid"); - if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CREATE_LOCKREF)) { + 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(); } + ResultType status = ResultType.SUCCESS; String lockId = MusicCore.createLockReference(lockName); @@ -155,21 +154,17 @@ public class RestMusicLocksAPI { response.status(Status.BAD_REQUEST); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + String keyspaceName = (String) resultMap.get("keyspace"); EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); - resultMap.remove("keyspace"); - resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "accquireLock"); - if (resultMap.containsKey("aid")) - resultMap.remove("aid"); - if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.ACQUIRE_LOCK)) { + 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(); } + try { String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId); @@ -212,22 +207,16 @@ public class RestMusicLocksAPI { response.status(Status.BAD_REQUEST); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); String keyspaceName = (String) resultMap.get("keyspace"); EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "accquireLockWithLease"); - - if (resultMap.containsKey("aid")) - resultMap.remove("aid"); - if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.ACQUIRE_LOCK)) { + 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 lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$')); ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod()); if ( lockLeaseStatus.getResult().equals(ResultType.SUCCESS)) { @@ -266,21 +255,17 @@ public class RestMusicLocksAPI { response.status(Status.BAD_REQUEST); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + String keyspaceName = (String) resultMap.get("keyspace"); EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "currentLockHolder"); - if (resultMap.containsKey("aid")) - resultMap.remove("aid"); - if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CURRENT_LOCK)) { + 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 who = MusicCore.whoseTurnIsIt(lockName); ResultType status = ResultType.SUCCESS; String error = ""; @@ -321,18 +306,11 @@ public class RestMusicLocksAPI { String keyspaceName = (String) resultMap.get("keyspace"); EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); - resultMap.remove("keyspace"); - resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "currentLockHolder"); - if (resultMap.containsKey("aid")) - resultMap.remove("aid"); - if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.CURRENT_LOCK)) { + 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 who = MusicCore.whoseTurnIsIt(lockName); @@ -394,21 +372,17 @@ public class RestMusicLocksAPI { response.status(Status.BAD_REQUEST); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + String keyspaceName = (String) resultMap.get("keyspace"); EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "unLock"); - if (resultMap.containsKey("aid")) - resultMap.remove("aid"); - if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DELETE_LOCK)) { + 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(); } + boolean voluntaryRelease = true; MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease); if(mls.getErrorMessage() != null) { @@ -458,21 +432,17 @@ public class RestMusicLocksAPI { response.status(Status.BAD_REQUEST); return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); } - Map userCredentials = MusicUtil.extractBasicAuthentication(authorization); - String userId = userCredentials.get(MusicUtil.USERID); - String password = userCredentials.get(MusicUtil.PASSWORD); + String keyspaceName = (String) resultMap.get("keyspace"); EELFLoggerDelegate.mdcPut("keyspace", "( "+keyspaceName+" ) "); resultMap.remove("keyspace"); - resultMap = MusicAuthentication.autheticateUser(ns, userId, password, keyspaceName, aid, - "deleteLock"); - if (resultMap.containsKey("aid")) - resultMap.remove("aid"); - if (!resultMap.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR); - response.status(Status.UNAUTHORIZED); - return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(resultMap.get("Error"))).toMap()).build(); + if (!authenticator.authenticateUser(ns, authorization, keyspaceName, aid, Operation.DELETE_LOCK)) { + 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(); } + try{ MusicCore.deleteLock(lockName); }catch (Exception e) { diff --git a/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java b/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java index 8eb677de..02b7f3a4 100644 --- a/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java +++ b/src/test/java/org/onap/music/unittests/TstRestMusicAdminAPI.java @@ -40,7 +40,7 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.internal.util.reflection.FieldSetter; -import org.onap.music.authentication.MusicAuthentication; +import org.onap.music.authentication.MusicAAFAuthentication; import org.onap.music.datastore.PreparedQueryObject; import org.onap.music.datastore.jsonobjects.JsonOnboard; import org.onap.music.main.MusicCore; @@ -53,7 +53,7 @@ public class TstRestMusicAdminAPI { static PreparedQueryObject testObject; @Mock - MusicAuthentication authMock; + MusicAAFAuthentication authMock; static String appName = "TestApp"; static String userId = "TestUser"; @@ -423,7 +423,7 @@ public class TstRestMusicAdminAPI { * @throws NoSuchFieldException */ public void authenticateAdminTrue() throws NoSuchFieldException { - authMock = Mockito.mock(MusicAuthentication.class); + authMock = Mockito.mock(MusicAAFAuthentication.class); FieldSetter.setField(admin, admin.getClass().getDeclaredField("authenticator"), authMock); Mockito.when(authMock.authenticateAdmin(Mockito.matches(adminAuthorization))).thenReturn(true); -- cgit 1.2.3-korg