Enhance RProxy authorization to use request method
[aaf/cadi.git] / sidecar / rproxy / src / main / java / org / onap / aaf / cadi / sidecar / rproxy / ReverseProxyAuthorizationFilter.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aaf
4  * ================================================================================
5  * Copyright © 2018 European Software Marketing Ltd.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.aaf.cadi.sidecar.rproxy;
21
22 import com.google.gson.Gson;
23 import com.google.gson.reflect.TypeToken;
24 import com.google.gson.stream.JsonReader;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.security.Principal;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.List;
36 import javax.annotation.Resource;
37 import javax.servlet.Filter;
38 import javax.servlet.FilterChain;
39 import javax.servlet.FilterConfig;
40 import javax.servlet.ServletException;
41 import javax.servlet.ServletRequest;
42 import javax.servlet.ServletResponse;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45 import org.eclipse.jetty.http.HttpStatus;
46 import org.onap.aaf.cadi.CadiWrap;
47 import org.onap.aaf.cadi.Permission;
48 import org.onap.aaf.cadi.sidecar.rproxy.config.ReverseProxyURIAuthorizationProperties;
49 import org.onap.aaf.cadi.sidecar.rproxy.utils.ReverseProxyAuthorization;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.boot.context.properties.EnableConfigurationProperties;
53 import org.springframework.core.annotation.Order;
54 import org.springframework.stereotype.Component;
55
56 @Component
57 @Order(1)
58 @EnableConfigurationProperties(ReverseProxyURIAuthorizationProperties.class)
59 public class ReverseProxyAuthorizationFilter implements Filter {
60
61     private static final Logger LOGGER = LoggerFactory.getLogger(ReverseProxyAuthorizationFilter.class);
62
63     private List<ReverseProxyAuthorization> reverseProxyAuthorizations = new ArrayList<>();
64
65     @Resource
66     private ReverseProxyURIAuthorizationProperties reverseProxyURIAuthorizationProperties;
67
68     @Override
69     public void init(FilterConfig filterConfig) throws ServletException {
70
71         // Read in the URI Authorisation configuration file
72         String authFilePath = reverseProxyURIAuthorizationProperties.getConfigurationFile();
73         if (authFilePath != null) {
74             try (InputStream inputStream =
75                     new FileInputStream(new File(reverseProxyURIAuthorizationProperties.getConfigurationFile()));
76                     JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream))) {
77                 List<ReverseProxyAuthorization> untrimmedList = new Gson().fromJson(jsonReader,
78                         new TypeToken<ArrayList<ReverseProxyAuthorization>>() {}.getType());
79                 untrimmedList.removeAll(Collections.singleton(null));
80                 reverseProxyAuthorizations = untrimmedList;
81             } catch (IOException e) {
82                 throw new ServletException("Authorizations config file not found.", e);
83             }
84         }
85     }
86
87     @Override
88     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
89             throws IOException, ServletException {
90
91         CadiWrap cadiWrap = (CadiWrap) servletRequest;
92         Principal principal = cadiWrap.getUserPrincipal();
93         List<Permission> grantedPermissions = new ArrayList<>();
94         cadiWrap.getLur().fishAll(principal, grantedPermissions);
95
96         if (LOGGER.isDebugEnabled()) {
97             logNeededPermissions();
98         }
99
100         String requestPath;
101         String requestMethod;
102         try {
103             requestPath = new URI(((HttpServletRequest) servletRequest).getRequestURI()).getPath();
104             requestMethod = ((HttpServletRequest)servletRequest).getMethod();
105         } catch (URISyntaxException e) {
106             throw new ServletException("Request URI not valid", e);
107         }
108
109         if (authorizeRequest(grantedPermissions, requestPath, requestMethod)) {
110             LOGGER.info("Authorized");
111             filterChain.doFilter(servletRequest, servletResponse);
112         } else {
113             LOGGER.info("Unauthorized");
114             ((HttpServletResponse) servletResponse).setStatus(HttpStatus.FORBIDDEN_403);
115             ((HttpServletResponse) servletResponse).setContentType("application/json");
116             ((HttpServletResponse) servletResponse).sendError(HttpStatus.FORBIDDEN_403,
117                     "Sorry, the request is not allowed");
118         }
119     }
120
121     /**
122      * Check if the granted permissions for the request path matches the configured needed permissions.
123      * 
124      * @param grantedPermissions The granted permissions for the request path
125      * @param requestPath The request path
126      * @param requestMethod The request method i.e. HTTP verb e.g. GET, PUT, POST etc
127      * @return true if permissions match
128      */
129     private boolean authorizeRequest(List<Permission> grantedPermissions, String requestPath, String requestMethod) {
130         boolean authorized = false;
131         for (ReverseProxyAuthorization reverseProxyAuthorization : reverseProxyAuthorizations) {
132             if (requestPath.matches(reverseProxyAuthorization.getUri()) &&
133                 requestMethod.matches(reverseProxyAuthorization.getMethod())) {
134                 LOGGER.debug("The URI:{}  matches:{}", requestPath, reverseProxyAuthorization.getUri());
135                 if (checkPermissionsMatch(grantedPermissions, reverseProxyAuthorization)) {
136                     authorized = true;
137                     break;
138                 }
139             } else {
140                 LOGGER.debug("The URI:{} doesn't match any in the configuration:{}", requestPath,
141                         reverseProxyAuthorization.getUri());
142             }
143         }
144         return authorized;
145     }
146
147     /**
148      * Check all needed permissions match the granted permissions.
149      * 
150      * @param grantedPermissions the granted permissions
151      * @param reverseProxyAuthorization the bean that contains the needed permissions
152      * @return true if all needed permissions match
153      */
154     private boolean checkPermissionsMatch(List<Permission> grantedPermissions,
155             ReverseProxyAuthorization reverseProxyAuthorization) {
156
157         boolean matchedAllPermissions = true;
158         for (String neededPermission : reverseProxyAuthorization.getPermissions()) {
159
160             // Check needed permission is granted
161             boolean matchedNeededPermission = false;
162             for (Permission grantedPermission : grantedPermissions) {
163                 if (checkGrantedPermission(neededPermission, grantedPermission.getKey())) {
164                     LOGGER.debug("Permission match found - needed permission:{}, granted permission:{}",
165                             neededPermission, grantedPermission.getKey());
166                     matchedNeededPermission = true;
167                     break;
168                 }
169             }
170             if (!matchedNeededPermission) {
171                 matchedAllPermissions = false;
172                 break;
173             }
174         }
175         return matchedAllPermissions;
176     }
177
178     /**
179      * Check whether an AAF style permission matches a needed permission. Wildcards (*) are supported.
180      * 
181      * @param neededPermission, the needed permission
182      * @param grantedPermission, the granted permission
183      * 
184      * @return true if the needed permission matches a granted permission
185      */
186     private boolean checkGrantedPermission(String neededPermission, String grantedPermission) {
187         boolean permissionMatch = false;
188         if (grantedPermission.matches(neededPermission)) {
189             permissionMatch = true;
190         } else if (grantedPermission.contains("*")) {
191             String[] splitNeededPermission = neededPermission.split("\\\\\\|");
192             String[] splitGrantedPermission = grantedPermission.split("\\|");
193             if ((splitGrantedPermission[0].matches(splitNeededPermission[0]))
194                     && (splitGrantedPermission[1].equals("*")
195                             || splitGrantedPermission[1].matches(splitNeededPermission[1]))
196                     && (splitGrantedPermission[2].equals("*")
197                             || splitGrantedPermission[2].matches(splitNeededPermission[2]))) {
198                 permissionMatch = true;
199             }
200         }
201         return permissionMatch;
202     }
203
204     /**
205      * Log the needed permissions for each URL configured.
206      */
207     private void logNeededPermissions() {
208         for (ReverseProxyAuthorization reverseProxyAuthorization : reverseProxyAuthorizations) {
209             LOGGER.debug("URI For authorization: {}", reverseProxyAuthorization.getUri());
210             for (String permission : reverseProxyAuthorization.getPermissions()) {
211                 LOGGER.debug("\t Needed permission:{}", permission);
212             }
213         }
214     }
215
216     @Override
217     public void destroy() {
218         // No op
219     }
220 }