Sonar Changes for Authentication Classes 90/90490/2
authorNelson, Thomas (tn1381) <tn1381@att.com>
Tue, 25 Jun 2019 23:44:53 +0000 (19:44 -0400)
committerNelson, Thomas (tn1381) <tn1381@att.com>
Wed, 26 Jun 2019 15:20:50 +0000 (11:20 -0400)
Issue-ID: MUSIC-418
Signed-off-by: Nelson, Thomas (tn1381) <tn1381@att.com>
Change-Id: I42240c66179a8a7a1b27093d3fffc180a73f4d14
Signed-off-by: Nelson, Thomas (tn1381) <tn1381@att.com>
src/main/java/org/onap/music/authentication/AuthUtil.java
src/main/java/org/onap/music/authentication/CadiAuthFilter.java
src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java
src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java [new file with mode: 0644]

index de9c272..223fa74 100644 (file)
@@ -37,14 +37,16 @@ import org.onap.aaf.cadi.CadiWrap;
 import org.onap.aaf.cadi.Permission;
 import org.onap.aaf.cadi.aaf.AAFPermission;
 import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.exceptions.MusicAuthenticationException;
 
 public class AuthUtil {
 
-    private static final String decodeValueOfForwardSlash = "2f";
-    private static final String decodeValueOfHyphen = "2d";
-    private static final String decodeValueOfAsterisk = "2a";
     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AuthUtil.class);
 
+    private AuthUtil() {
+        throw new IllegalStateException("Utility class");
+    }
+    
     /**
      * Get the list of permissions from the Request object.
      * 
@@ -104,20 +106,23 @@ public class AuthUtil {
      * @return returns the decoded string.
      * @throws Exception throws excpetion
      */
-    public static String decodeFunctionCode(String str) throws Exception {
+    public static String decodeFunctionCode(String str) throws MusicAuthenticationException {
+        final String DECODEVALUE_FORWARDSLASH = "2f";
+        final String DECODEVALUE_HYPHEN = "2d";
+        final String DECODEVALUE_ASTERISK = "2a";
         String decodedString = str;
         List<Pattern> decodingList = new ArrayList<>();
-        decodingList.add(Pattern.compile(decodeValueOfForwardSlash));
-        decodingList.add(Pattern.compile(decodeValueOfHyphen));
-        decodingList.add(Pattern.compile(decodeValueOfAsterisk));
+        decodingList.add(Pattern.compile(DECODEVALUE_FORWARDSLASH));
+        decodingList.add(Pattern.compile(DECODEVALUE_HYPHEN));
+        decodingList.add(Pattern.compile(DECODEVALUE_ASTERISK));
         for (Pattern xssInputPattern : decodingList) {
             try {
                 decodedString = decodedString.replaceAll("%" + xssInputPattern,
                         new String(Hex.decodeHex(xssInputPattern.toString().toCharArray())));
             } catch (DecoderException e) {
-                logger.error(EELFLoggerDelegate.applicationLogger, 
+                logger.error(EELFLoggerDelegate.securityLogger, 
                     "AuthUtil Decode Failed! for instance: " + str);
-                throw new Exception("decode failed", e);
+                throw new MusicAuthenticationException("Decode failed", e);
             }
         }
 
@@ -132,23 +137,21 @@ public class AuthUtil {
      * @return boolean value if the access is allowed
      * @throws Exception throws exception
      */
-    public static boolean isAccessAllowed(ServletRequest request, String nameSpace) throws Exception {
+    public static boolean isAccessAllowed(ServletRequest request, String nameSpace) throws MusicAuthenticationException {
 
         if (request==null) {
-            throw new Exception("Request cannot be null");
+            throw new MusicAuthenticationException("Request cannot be null");
         }
         
         if (nameSpace==null || nameSpace.isEmpty()) {
-            throw new Exception("NameSpace not Declared!");
+            throw new MusicAuthenticationException("NameSpace not Declared!");
         }
         
         boolean isauthorized = false;
         List<AAFPermission> aafPermsList = getAAFPermissions(request);
-        //logger.info(EELFLoggerDelegate.applicationLogger,
-        //        "AAFPermission  of the requested MechId for all the namespaces: " + aafPermsList);
-
-        logger.debug(EELFLoggerDelegate.applicationLogger, "Requested nameSpace: " + nameSpace);
-
+        logger.info(EELFLoggerDelegate.securityLogger,
+            "AAFPermission  of the requested MechId for all the namespaces: " + aafPermsList);
+        logger.debug(EELFLoggerDelegate.securityLogger, "Requested nameSpace: " + nameSpace);
 
         List<AAFPermission> aafPermsFinalList = filterNameSpacesAAFPermissions(nameSpace, aafPermsList);
 
@@ -162,10 +165,10 @@ public class AuthUtil {
         logger.debug(EELFLoggerDelegate.securityLogger,
                 "AuthUtil requestUri :::" + requestUri);
 
-        for (Iterator iterator = aafPermsFinalList.iterator(); iterator.hasNext();) {
+        for (Iterator<AAFPermission> iterator = aafPermsFinalList.iterator(); iterator.hasNext();) {
             AAFPermission aafPermission = (AAFPermission) iterator.next();
             if(!isauthorized) {
-                isauthorized = isMatchPatternWithInstanceAndAction(aafPermission, requestUri, httpRequest.getMethod());
+                isauthorized = isMatchPattern(aafPermission, requestUri, httpRequest.getMethod());
             }
         }
         
@@ -205,23 +208,21 @@ public class AuthUtil {
      * @return returns a boolean
      * @throws Exception - throws an exception
      */
-    private static boolean isMatchPatternWithInstanceAndAction(
+    private static boolean isMatchPattern(
         AAFPermission aafPermission, 
         String requestUri, 
-        String method) throws Exception {
+        String method) throws MusicAuthenticationException {
         if (null == aafPermission || null == requestUri || null == method) {
             return false;
         }
 
         String permKey = aafPermission.getKey();
         
-        logger.debug(EELFLoggerDelegate.auditLogger, "isMatchPattern permKey: " 
+        logger.debug(EELFLoggerDelegate.securityLogger, "isMatchPattern permKey: " 
             + permKey + ", requestUri " + requestUri + " ," + method);
         
         String[] keyArray = permKey.split("\\|");
         String[] subPath = null;
-        //String type = null;
-        //type = keyArray[0];
         String instance = keyArray[1];
         String action = keyArray[2];
         
@@ -251,13 +252,7 @@ public class AuthUtil {
             subPath = path[i].split("\\.");
             for (int j = 0; j < subPath.length; j++) {
                 if (instanceList.contains(subPath[j])) {
-                    if ("*".equals(action) || "ALL".equalsIgnoreCase(action)) {
-                        return true;
-                    } else if (method.equalsIgnoreCase(action)) {
-                        return true;
-                    } else {
-                        return false;
-                    }
+                    return checkAction(method,action);
                 } else {
                     continue;
                 }
@@ -265,4 +260,15 @@ public class AuthUtil {
         }
         return false;
     }
+
+    private static boolean checkAction(String method, String action) {
+        if ("*".equals(action) || "ALL".equalsIgnoreCase(action)) {
+            return true;
+        } else {
+            return (method.equalsIgnoreCase(action));
+        }
+    }
+
+
+
 }
\ No newline at end of file
index cd58d35..d043e6d 100644 (file)
@@ -58,13 +58,8 @@ public class CadiAuthFilter extends CadiFilter {
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
             throws IOException, ServletException {
             logger.info(EELFLoggerDelegate.securityLogger, "Request is entering cadifilter");
-            
             long startTime = System.currentTimeMillis();
             request.setAttribute("startTime", startTime);
-            
             super.doFilter(request, response, chain);
-            
-            //Commented by saumya (sp931a) on 04/11/19 for auth filter
-            //chain.doFilter(request, response);
     }
 }
\ No newline at end of file
index a9930d8..bde3e20 100644 (file)
 package org.onap.music.authentication;
 
 import java.io.IOException;
-import java.util.Base64;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
 
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
@@ -36,10 +32,10 @@ import javax.servlet.FilterConfig;
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.exceptions.MusicAuthenticationException;
 import org.onap.music.main.MusicUtil;
 import com.fasterxml.jackson.databind.ObjectMapper;
 
@@ -62,7 +58,7 @@ public class MusicAuthorizationFilter implements Filter {
 
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {
-
+        // Do Nothing
     }
 
     @Override
@@ -83,9 +79,12 @@ public class MusicAuthorizationFilter implements Filter {
 
             try {
                 isAuthAllowed = AuthUtil.isAccessAllowed(servletRequest, musicNS);
-            } catch (Exception e) {
+            } catch (MusicAuthenticationException e) {
+                logger.error(EELFLoggerDelegate.securityLogger,
+                    "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage(),e);
+            } catch ( Exception e) {
                 logger.error(EELFLoggerDelegate.securityLogger,
-                    "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage());
+                    "Error while checking authorization Music Namespace: " + musicNS + " : " + e.getMessage(),e);
             }
 
             long endTime = System.currentTimeMillis();
@@ -119,39 +118,5 @@ public class MusicAuthorizationFilter implements Filter {
         String serialized = new ObjectMapper().writeValueAsString(eErrorResponse);
         return serialized.getBytes();
     }
-
-    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
-
-        Map<String, String> map = new HashMap<String, String>();
-
-        Enumeration headerNames = request.getHeaderNames();
-        while (headerNames.hasMoreElements()) {
-            String key = (String) headerNames.nextElement();
-            String value = request.getHeader(key);
-            map.put(key, value);
-        }
-
-        return map;
-    }
-
-    private static String getUserNamefromRequest(HttpServletRequest httpRequest) {
-        String authHeader = httpRequest.getHeader("Authorization");
-        String username = null;
-        if (authHeader != null) {
-            String[] split = authHeader.split("\\s+");
-            if (split.length > 0) {
-                String basic = split[0];
-
-                if ("Basic".equalsIgnoreCase(basic)) {
-                    byte[] decodedBytes = Base64.getDecoder().decode(split[1]);
-                    String decodedString = new String(decodedBytes);
-                    int p = decodedString.indexOf(":");
-                    if (p != -1) {
-                        username = decodedString.substring(0, p);
-                    }
-                }
-            }
-        }
-        return username;
-    }
 }
+
diff --git a/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java b/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java
new file mode 100644 (file)
index 0000000..ab44fd6
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * ============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.exceptions;
+
+/**
+ * @author inam
+ *
+ */
+public class MusicAuthenticationException extends Exception {
+
+    /**
+     * 
+     */
+    public MusicAuthenticationException() {
+
+    }
+
+    /**
+     * @param message
+     */
+    public MusicAuthenticationException(String message) {
+        super(message);
+
+    }
+
+    /**
+     * @param cause
+     */
+    public MusicAuthenticationException(Throwable cause) {
+        super(cause);
+
+    }
+
+    /**
+     * @param message
+     * @param cause
+     */
+    public MusicAuthenticationException(String message, Throwable cause) {
+        super(message, cause);
+
+    }
+
+    /**
+     * @param message
+     * @param cause
+     * @param enableSuppression
+     * @param writableStackTrace
+     */
+    public MusicAuthenticationException(String message, Throwable cause, boolean enableSuppression,
+                    boolean writableStackTrace) {
+        super(message, cause, enableSuppression, writableStackTrace);
+
+    }
+
+}