Minor Improvement
[clamp.git] / src / main / java / org / onap / clamp / clds / service / SecureServiceBase.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * 
22  */
23
24 package org.onap.clamp.clds.service;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.security.Principal;
30 import java.util.Date;
31
32 import javax.ws.rs.NotAuthorizedException;
33 import javax.ws.rs.core.Context;
34 import javax.ws.rs.core.SecurityContext;
35
36 import org.onap.clamp.clds.util.LoggingUtils;
37
38 /**
39  * Base/abstract Service class. Implements shared security methods.
40  */
41 public abstract class SecureServiceBase {
42     protected static final EELFLogger logger          = EELFManager.getInstance().getLogger(SecureServiceBase.class);
43     protected static final EELFLogger auditLogger     = EELFManager.getInstance().getAuditLogger();
44     protected static final EELFLogger securityLogger  = EELFManager.getInstance().getSecurityLogger();
45
46     // By default we'll set it to a default handler
47     private static UserNameHandler    userNameHandler = new DefaultUserNameHandler();
48
49     @Context
50     private SecurityContext           securityContext;
51
52     /**
53      * Get the userId from AAF/CSP.
54      *
55      * @return
56      */
57     public String getUserId() {
58         return getUserName();
59     }
60
61     /**
62      * Get the Full name.
63      *
64      * @return
65      */
66     public String getUserName() {
67         String name = userNameHandler.retrieveUserName(securityContext);
68         Date startTime = new Date();
69         LoggingUtils.setTargetContext("CLDS", "getUserName");
70         LoggingUtils.setTimeContext(startTime, new Date());
71         securityLogger.debug("User logged into the CLDS system={}", name);
72         return name;
73     }
74
75     /**
76      * Get the principal name.
77      *
78      * @return
79      */
80     public String getPrincipalName() {
81         Principal principal = securityContext.getUserPrincipal();
82         String name = "Not found";
83         if (principal != null) {
84             name = principal.getName();
85         }
86         logger.debug("userPrincipal.getName()={}", name);
87         return name;
88     }
89
90     /**
91      * Check if user is authorized for the given the permission. Allow matches
92      * if user has a permission with an "*" in permission instance or permission
93      * action even if the permission to check has a specific value in those
94      * fields. For example: if the user has this permission: app-perm-type|*|*
95      * it will be authorized if the inPermission to check is:
96      * app-perm-type|dev|read
97      *
98      * @param inPermission
99      *            The permission to validate
100      * @return A boolean to indicate if the user has the permission to do
101      *         execute the inPermission
102      * @throws NotAuthorizedException
103      *             In case of issues with the permission test, error is returned
104      *             in this exception
105      */
106         public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException {
107                 Date startTime = new Date();
108                 LoggingUtils.setTargetContext("CLDS", "isAuthorized");
109                 LoggingUtils.setTimeContext(startTime, new Date());
110                 securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
111                 try {
112                         return isUserPermitted(inPermission);
113                 } catch (NotAuthorizedException nae) {
114                         String msg = getPrincipalName() + " does not have permission: " + inPermission;
115                         LoggingUtils.setErrorContext("100", "Authorization Error");
116                         securityLogger.warn(msg);
117                         throw new NotAuthorizedException(msg);
118                 }
119         }
120
121     /**
122      * Check if user is authorized for the given aaf permission. Allow matches
123      * if user has a permission with an "*" in permission instance or permission
124      * action even if the permission to check has a specific value in those
125      * fields. For example: if the user has this permission: app-perm-type|*|*
126      * it will be authorized if the inPermission to check is:
127      * app-perm-type|dev|read
128      *
129      * @param inPermission
130      *            The permission to validate
131      * @return A boolean to indicate if the user has the permission to do
132      *         execute the inPermission
133      */
134         public boolean isAuthorizedNoException(SecureServicePermission inPermission) {
135                 securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
136                 Date startTime = new Date();
137                 LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException");
138                 LoggingUtils.setTimeContext(startTime, new Date());
139                 try {
140                         return isUserPermitted(inPermission);
141                 } catch (NotAuthorizedException nae) {
142                         String msg = getPrincipalName() + " does not have permission: " + inPermission;
143                         LoggingUtils.setErrorContext("100", "Authorization Error");
144                         securityLogger.warn(msg);
145                 }
146                 return false;
147         }
148
149     /**
150      * This method can be used by the Application.class to set the
151      * UserNameHandler that must be used in this class. The UserNameHandler
152      * where to get the User name
153      * 
154      * @param handler
155      *            The Handler impl to use
156      */
157     public static final void setUserNameHandler(UserNameHandler handler) {
158         if (handler != null) {
159             userNameHandler = handler;
160         }
161     }
162
163     public void setSecurityContext(SecurityContext securityContext) {
164         this.securityContext = securityContext;
165     }
166     
167     private boolean isUserPermitted(SecureServicePermission inPermission) throws NotAuthorizedException {
168         boolean authorized = false;
169         // check if the user has the permission key or the permission key with a
170         // combination of  all instance and/or all action.
171         if (securityContext.isUserInRole(inPermission.getKey())) {
172             securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());            
173             authorized = true;
174             // the rest of these don't seem to be required - isUserInRole method
175             // appears to take * as a wildcard
176         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
177             securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey());
178             authorized = true;
179         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
180              securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey());            
181             authorized = true;
182         } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
183             securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey());            
184             authorized = true;
185         } else {
186             throw new NotAuthorizedException("");
187         }
188         return authorized;
189     }
190 }