Merge "Removed code duplication in PolicyClient"
[clamp.git] / src / main / java / org / onap / clamp / authorization / AuthorizationController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 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.authorization;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.util.Date;
30
31 import javax.ws.rs.NotAuthorizedException;
32
33 import org.apache.camel.Exchange;
34 import org.onap.clamp.clds.config.ClampProperties;
35 import org.onap.clamp.clds.service.SecureServiceBase;
36 import org.onap.clamp.clds.service.SecureServicePermission;
37 import org.onap.clamp.clds.util.LoggingUtils;
38 import org.onap.clamp.util.PrincipalUtils;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.security.core.Authentication;
41 import org.springframework.security.core.GrantedAuthority;
42 import org.springframework.security.core.context.SecurityContext;
43 import org.springframework.security.core.context.SecurityContextHolder;
44 import org.springframework.stereotype.Component;
45
46 /**
47  * Create CLDS Event.
48  */
49 @Component
50 public class AuthorizationController {
51
52     protected static final EELFLogger logger          = EELFManager.getInstance().getLogger(SecureServiceBase.class);
53     protected static final EELFLogger auditLogger     = EELFManager.getInstance().getMetricsLogger();
54     protected static final EELFLogger securityLogger  = EELFManager.getInstance().getSecurityLogger();
55
56     // By default we'll set it to a default handler
57     @Autowired
58     private ClampProperties refProp;
59
60     private SecurityContext securityContext = SecurityContextHolder.getContext();
61     private static final String permPrefix = "security.permission.type.";
62     private static final String permInstance = "security.permission.instance";
63
64     public AuthorizationController() {
65     }
66
67     /**
68      * Insert authorize the api based on the permission
69      *
70      * @param camelExchange
71      *        The Camel Exchange object containing the properties
72      * @param typeVar
73      *        The type of the permissions
74      * @param instanceVar
75      *        The instance of the permissions. e.g. dev
76      * @param action
77      *        The action of the permissions. e.g. read
78      */
79     public void authorize(Exchange camelExchange, String typeVar, String instanceVar, String action) {
80         String type = refProp.getStringValue(permPrefix + typeVar);
81         String instance = refProp.getStringValue(permInstance);
82
83         if (null == type || type.isEmpty()) {
84             //authorization is turned off, since the permission is not defined
85             return;
86         }
87         if (null != instanceVar && !instanceVar.isEmpty()) {
88             instance = instanceVar;
89         }
90         String principalName = PrincipalUtils.getPrincipalName();
91         SecureServicePermission perm = SecureServicePermission.create(type, instance, action);
92         Date startTime = new Date();
93         LoggingUtils.setTargetContext("Clamp", "authorize");
94         LoggingUtils.setTimeContext(startTime, new Date());
95         securityLogger.debug("checking if {} has permission: {}", principalName, perm);
96         try {
97             isUserPermitted(perm);
98         } catch (NotAuthorizedException nae) {
99             String msg = principalName + " does not have permission: " + perm;
100             LoggingUtils.setErrorContext("100", "Authorization Error");
101             securityLogger.warn(msg);
102             throw new NotAuthorizedException(msg);
103         }
104     }
105
106     private boolean isUserPermitted(SecureServicePermission inPermission) {
107         boolean authorized = false;
108         String principalName = PrincipalUtils.getPrincipalName();
109         // check if the user has the permission key or the permission key with a
110         // combination of  all instance and/or all action.
111         if (hasRole(inPermission.getKey())) {
112             auditLogger.info("{} authorized because user has permission with * for instance: {}", 
113                   principalName, inPermission.getKey());
114             authorized = true;
115             // the rest of these don't seem to be required - isUserInRole method
116             // appears to take * as a wildcard
117         } else if (hasRole(inPermission.getKeyAllInstance())) {
118             auditLogger.info("{} authorized because user has permission with * for instance: {}", 
119                   principalName, inPermission.getKey());
120             authorized = true;
121         } else if (hasRole(inPermission.getKeyAllInstanceAction())) {
122             auditLogger.info("{} authorized because user has permission with * for instance and * for action: {}", 
123                   principalName, inPermission.getKey());
124             authorized = true;
125         } else if (hasRole(inPermission.getKeyAllAction())) {
126             auditLogger.info("{} authorized because user has permission with * for action: {}",
127                   principalName, inPermission.getKey());
128             authorized = true;
129         } else {
130             throw new NotAuthorizedException("");
131         }
132         return authorized;
133     }
134
135     /**
136      * Verify whether the user has the permission.
137      *
138      * @param inPermission
139      *        The permissions to verify
140      */
141     public boolean isUserPermittedNoException(SecureServicePermission inPermission) {
142         try {
143             return isUserPermitted(inPermission);
144         } catch (NotAuthorizedException e) {
145             return false;
146         }
147     }
148
149     protected boolean hasRole(String role) {
150         Authentication authentication = PrincipalUtils.getSecurityContext().getAuthentication();
151         if (authentication == null) {
152             return false;
153         }
154         for (GrantedAuthority auth : authentication.getAuthorities()) {
155             if (role.equals(auth.getAuthority())) {
156                 return true;
157             }
158         }
159         return false;
160     }
161
162 }