Add encryption for passwords
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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         boolean authorized = false;
108        
109         Date startTime = new Date();
110         LoggingUtils.setTargetContext("CLDS", "isAuthorized");
111         LoggingUtils.setTimeContext(startTime, new Date());
112         
113         securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
114         
115         // check if the user has the permission key or the permission key with a
116         // combination of all instance and/or all action.
117         if (securityContext.isUserInRole(inPermission.getKey())) {
118             securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());            
119             authorized = true;
120             // the rest of these don't seem to be required - isUserInRole method
121             // appears to take * as a wildcard
122         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
123             securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey());
124             authorized = true;
125         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
126              securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey());            
127             authorized = true;
128         } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
129             securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey());            
130             authorized = true;
131         } else {
132             String msg = getPrincipalName() + " does not have permission: " + inPermission;
133             LoggingUtils.setErrorContext("100", "Authorization Error");
134             securityLogger.warn(msg);
135             throw new NotAuthorizedException(msg);
136         }
137         return authorized;
138     }
139
140     /**
141      * Check if user is authorized for the given aaf permission. Allow matches
142      * if user has a permission with an "*" in permission instance or permission
143      * action even if the permission to check has a specific value in those
144      * fields. For example: if the user has this permission: app-perm-type|*|*
145      * it will be authorized if the inPermission to check is:
146      * app-perm-type|dev|read
147      *
148      * @param inPermission
149      *            The permission to validate
150      * @return A boolean to indicate if the user has the permission to do
151      *         execute the inPermission
152      */
153     public boolean isAuthorizedNoException(SecureServicePermission inPermission) {
154         boolean authorized = false;
155         
156         securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
157         Date startTime = new Date();
158         LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException");
159         LoggingUtils.setTimeContext(startTime, new Date());
160         
161         // check if the user has the permission key or the permission key with a
162         // combination of all instance and/or all action.
163         if (securityContext.isUserInRole(inPermission.getKey())) {
164             securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());
165             authorized = true;
166             // the rest of these don't seem to be required - isUserInRole method
167             // appears to take * as a wildcard
168         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
169             securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(),inPermission.getKey());
170             authorized = true;
171         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
172             securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey());
173             authorized = true;
174         } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
175             securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey());
176             authorized = true;
177         } else {
178             String msg = getPrincipalName() + " does not have permission: " + inPermission;
179             LoggingUtils.setErrorContext("100", "Authorization Error");
180             securityLogger.warn(msg);
181             logger.warn(msg);
182         }
183         return authorized;
184     }
185
186     /**
187      * This method can be used by the Application.class to set the
188      * UserNameHandler that must be used in this class. The UserNameHandler
189      * where to get the User name
190      * 
191      * @param handler
192      *            The Handler impl to use
193      */
194     public static final void setUserNameHandler(UserNameHandler handler) {
195         if (handler != null) {
196             userNameHandler = handler;
197         }
198     }
199
200     public void setSecurityContext(SecurityContext securityContext) {
201         this.securityContext = securityContext;
202     }
203
204 }