e4a03fd38982d60452b7bbb8be094741e298e468
[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  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END============================================
22  * ===================================================================
23  *
24  */
25
26 package org.onap.clamp.authorization;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import java.util.Date;
31 import org.apache.camel.Exchange;
32 import org.onap.clamp.clds.config.ClampProperties;
33 import org.onap.clamp.clds.exception.NotAuthorizedException;
34 import org.onap.clamp.clds.model.ClampInformation;
35 import org.onap.clamp.clds.util.LoggingUtils;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.security.core.Authentication;
38 import org.springframework.security.core.GrantedAuthority;
39 import org.springframework.security.core.context.SecurityContext;
40 import org.springframework.security.core.context.SecurityContextHolder;
41 import org.springframework.security.core.userdetails.UserDetails;
42 import org.springframework.stereotype.Component;
43
44 /**
45  * Verify user has right permissions.
46  */
47 @Component
48 public class AuthorizationController {
49
50     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AuthorizationController.class);
51     protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger();
52     protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger();
53
54     // By default we'll set it to a default handler
55     @Autowired
56     private ClampProperties refProp;
57
58     private SecurityContext securityContext = SecurityContextHolder.getContext();
59
60     public static final String PERM_PREFIX = "security.permission.type.";
61     private static final String PERM_INSTANCE = "security.permission.instance";
62
63     private static String retrieveUserName(SecurityContext securityContext) {
64         if (securityContext == null || securityContext.getAuthentication() == null) {
65             return null;
66         }
67         if ((securityContext.getAuthentication().getPrincipal()) instanceof String) {
68             // anonymous case
69             return ((String)securityContext.getAuthentication().getPrincipal());
70         } else {
71             return ((UserDetails) securityContext.getAuthentication().getPrincipal()).getUsername();
72         }
73     }
74     /**
75      * Get the principal name.
76      *
77      * @return The principal name
78      */
79     public static String getPrincipalName(SecurityContext securityContext) {
80         String principal = AuthorizationController.retrieveUserName(securityContext);
81         String name = "Not found";
82         if (principal != null) {
83             name = principal;
84         }
85         return name;
86     }
87
88     /**
89      * Insert authorize the api based on the permission.
90      *
91      * @param camelExchange The Camel Exchange object containing the properties
92      * @param typeVar       The type of the permissions
93      * @param instanceVar   The instance of the permissions. e.g. dev
94      * @param action        The action of the permissions. e.g. read
95      */
96     public void authorize(Exchange camelExchange, String typeVar, String instanceVar, String action) {
97         String type = refProp.getStringValue(PERM_PREFIX + typeVar);
98         String instance = refProp.getStringValue(PERM_INSTANCE);
99
100         if (null == type || type.isEmpty()) {
101             // authorization is turned off, since the permission is not defined
102             return;
103         }
104         if (null != instanceVar && !instanceVar.isEmpty()) {
105             instance = instanceVar;
106         }
107         String principalName = AuthorizationController.getPrincipalName(this.securityContext);
108         SecureServicePermission perm = SecureServicePermission.create(type, instance, action);
109         Date startTime = new Date();
110         LoggingUtils.setTargetContext("Clamp", "authorize");
111         LoggingUtils.setTimeContext(startTime, new Date());
112         securityLogger.debug("checking if {} has permission: {}", principalName, perm);
113
114         if (!isUserPermitted(perm)) {
115             String msg = principalName + " does not have permission: " + perm;
116             LoggingUtils.setErrorContext("100", "Authorization Error");
117             securityLogger.warn(msg);
118             throw new NotAuthorizedException(msg);
119         }
120     }
121
122     /**
123      * Insert authorize the api based on the permission.
124      * 
125      * @param inPermission Security permission in input
126      * @return True if user is permitted
127      */
128     public boolean isUserPermitted(SecureServicePermission inPermission) {
129
130         String principalName = AuthorizationController.getPrincipalName(this.securityContext);
131         // check if the user has the permission key or the permission key with a
132         // combination of all instance and/or all action.
133         if (hasRole(inPermission.getKey()) || hasRole(inPermission.getKeyAllInstance())) {
134             auditLogger.info("{} authorized because user has permission with * for instance: {}", principalName,
135                     inPermission.getKey());
136             return true;
137             // the rest of these don't seem to be required - isUserInRole method
138             // appears to take * as a wildcard
139         } else if (hasRole(inPermission.getKeyAllInstanceAction())) {
140             auditLogger.info("{} authorized because user has permission with * for instance and * for action: {}",
141                     principalName, inPermission.getKey());
142             return true;
143         } else if (hasRole(inPermission.getKeyAllAction())) {
144             auditLogger.info("{} authorized because user has permission with * for action: {}", principalName,
145                     inPermission.getKey());
146             return true;
147         } else {
148             return false;
149         }
150     }
151
152     protected boolean hasRole(String role) {
153         Authentication authentication = securityContext.getAuthentication();
154         if (authentication == null) {
155             return false;
156         }
157         for (GrantedAuthority auth : authentication.getAuthorities()) {
158             if (role.equals(auth.getAuthority())) {
159                 return true;
160             }
161         }
162         return false;
163     }
164
165     /**
166      * Gets clds info. CLDS IFO service will return 3 things 1. User Name 2. CLDS
167      * code version that is currently installed from pom.xml file 3. User
168      * permissions
169      *
170      * @return the clds info
171      */
172     public ClampInformation getClampInformation() {
173         ClampInformation clampInfo = new ClampInformation();
174         Authentication authentication = securityContext.getAuthentication();
175         if (authentication == null) {
176             return new ClampInformation();
177         }
178         clampInfo.setUserName(AuthorizationController.getPrincipalName(this.securityContext));
179         for (GrantedAuthority auth : authentication.getAuthorities()) {
180             clampInfo.getAllPermissions().add(auth.getAuthority());
181         }
182         return clampInfo;
183     }
184 }