acbd8bbd4d039f9b94ebd56b32a20c128c06b788
[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
31 import javax.ws.rs.NotAuthorizedException;
32 import javax.ws.rs.core.Context;
33 import javax.ws.rs.core.SecurityContext;
34
35 import org.onap.clamp.clds.util.LoggingUtils;
36
37 /**
38  * Base/abstract Service class. Implements shared security methods.
39  */
40 public abstract class SecureServiceBase {
41     protected static final EELFLogger logger          = EELFManager.getInstance().getLogger(SecureServiceBase.class);
42     protected static final EELFLogger auditLogger     = EELFManager.getInstance().getAuditLogger();
43
44     // By default we'll set it to a default handler
45     private static UserNameHandler    userNameHandler = new DefaultUserNameHandler();
46
47     @Context
48     private SecurityContext           securityContext;
49
50     /**
51      * Get the userId from AAF/CSP.
52      *
53      * @return
54      */
55     public String getUserId() {
56         return getUserName();
57     }
58
59     /**
60      * Get the Full name.
61      *
62      * @return
63      */
64     public String getUserName() {
65         String name = userNameHandler.retrieveUserName(securityContext);
66         logger.debug("userName={}", name);
67         return name;
68     }
69
70     /**
71      * Get the principal name.
72      *
73      * @return
74      */
75     public String getPrincipalName() {
76         Principal principal = securityContext.getUserPrincipal();
77         String name = "Not found";
78         if (principal != null) {
79             name = principal.getName();
80         }
81         logger.debug("userPrincipal.getName()={}", name);
82         return name;
83     }
84
85     /**
86      * Check if user is authorized for the given the permission. Allow matches
87      * if user has a permission with an "*" in permission instance or permission
88      * action even if the permission to check has a specific value in those
89      * fields. For example: if the user has this permission: app-perm-type|*|*
90      * it will be authorized if the inPermission to check is:
91      * app-perm-type|dev|read
92      *
93      * @param inPermission
94      *            The permission to validate
95      * @return A boolean to indicate if the user has the permission to do
96      *         execute the inPermission
97      * @throws NotAuthorizedException
98      *             In case of issues with the permission test, error is returned
99      *             in this exception
100      */
101     public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException {
102         boolean authorized = false;
103         logger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
104         // check if the user has the permission key or the permission key with a
105         // combination of all instance and/or all action.
106         if (securityContext.isUserInRole(inPermission.getKey())) {
107             logger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());
108             authorized = true;
109             // the rest of these don't seem to be required - isUserInRole method
110             // appears to take * as a wildcard
111         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
112             logger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(),
113                     inPermission.getKey());
114             authorized = true;
115         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
116             logger.info("{} authorized because user has permission with * for instance and * for action: {}",
117                     getPrincipalName(), inPermission.getKey());
118             authorized = true;
119         } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
120             logger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(),
121                     inPermission.getKey());
122             authorized = true;
123         } else {
124             String msg = getPrincipalName() + " does not have permission: " + inPermission;
125             LoggingUtils.setErrorContext("100", "Authorization Error");
126             logger.warn(msg);
127             throw new NotAuthorizedException(msg);
128         }
129         return authorized;
130     }
131
132     /**
133      * Check if user is authorized for the given aaf permission. Allow matches
134      * if user has a permission with an "*" in permission instance or permission
135      * action even if the permission to check has a specific value in those
136      * fields. For example: if the user has this permission: app-perm-type|*|*
137      * it will be authorized if the inPermission to check is:
138      * app-perm-type|dev|read
139      *
140      * @param inPermission
141      *            The permission to validate
142      * @return A boolean to indicate if the user has the permission to do
143      *         execute the inPermission
144      */
145     public boolean isAuthorizedNoException(SecureServicePermission inPermission) {
146         boolean authorized = false;
147         logger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
148         // check if the user has the permission key or the permission key with a
149         // combination of all instance and/or all action.
150         if (securityContext.isUserInRole(inPermission.getKey())) {
151             logger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());
152             authorized = true;
153             // the rest of these don't seem to be required - isUserInRole method
154             // appears to take * as a wildcard
155         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
156             logger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(),
157                     inPermission.getKey());
158             authorized = true;
159         } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
160             logger.info("{} authorized because user has permission with * for instance and * for action: {}",
161                     getPrincipalName(), inPermission.getKey());
162             authorized = true;
163         } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
164             logger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(),
165                     inPermission.getKey());
166             authorized = true;
167         } else {
168             String msg = getPrincipalName() + " does not have permission: " + inPermission;
169             LoggingUtils.setErrorContext("100", "Authorization Error");
170             logger.warn(msg);
171         }
172         return authorized;
173     }
174
175     /**
176      * This method can be used by the Application.class to set the
177      * UserNameHandler that must be used in this class. The UserNameHandler
178      * where to get the User name
179      * 
180      * @param handler
181      *            The Handler impl to use
182      */
183     public static final void setUserNameHandler(UserNameHandler handler) {
184         if (handler != null) {
185             userNameHandler = handler;
186         }
187     }
188
189     public void setSecurityContext(SecurityContext securityContext) {
190         this.securityContext = securityContext;
191     }
192
193 }