50f5b8942c80c3cff3bd101ad33e7972ebd7da6f
[portal/ric-dashboard.git] / webapp-backend / src / main / java / org / oransc / ric / portal / dashboard / portalapi / PortalAuthenticationFilter.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 AT&T Intellectual Property and Nokia
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.oransc.ric.portal.dashboard.portalapi;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.UnsupportedEncodingException;
25 import java.lang.invoke.MethodHandles;
26 import java.net.URLEncoder;
27 import java.util.HashSet;
28
29 import javax.servlet.Filter;
30 import javax.servlet.FilterChain;
31 import javax.servlet.FilterConfig;
32 import javax.servlet.ServletException;
33 import javax.servlet.ServletRequest;
34 import javax.servlet.ServletResponse;
35 import javax.servlet.http.Cookie;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38
39 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
40 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
41 import org.onap.portalsdk.core.restful.domain.EcompRole;
42 import org.onap.portalsdk.core.restful.domain.EcompUser;
43 import org.oransc.ric.portal.dashboard.DashboardConstants;
44 import org.oransc.ric.portal.dashboard.model.EcompUserDetails;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.http.MediaType;
48 import org.springframework.security.core.Authentication;
49 import org.springframework.security.core.context.SecurityContextHolder;
50 import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
51
52 /**
53  * This filter checks every request for the cookie set by the ONAP Portal single
54  * sign on process. The possible paths and actions:
55  * <OL>
56  * <LI>User starts at an app page via a bookmark. No Portal cookie is set.
57  * Redirect there to get one; then continue as below.
58  * <LI>User starts at Portal and goes to app. Alternately, the user's session
59  * times out and the user hits refresh. The Portal cookie is set, but there is
60  * no valid session. Create one and publish info.
61  * <LI>User has valid Portal cookie and session. Reset the max idle in that
62  * session.
63  * </OL>
64  * <P>
65  * Notes:
66  * <UL>
67  * <LI>While redirecting, the cookie "redirectUrl" should also be set so that
68  * Portal knows where to forward the request to once the Portal Session is
69  * created and EPService cookie is set.
70  * </UL>
71  * 
72  * TODO: What about sessions? Will this be stateless?
73  * 
74  * This filter uses no annotations to avoid Spring's automatic registration,
75  * which add this filter in the chain in the wrong order.
76  */
77 public class PortalAuthenticationFilter implements Filter {
78
79         private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
80
81         // Unfortunately these names are not available as constants
82         private static final String[] securityPropertyFiles = { "ESAPI.properties", "key.properties", "portal.properties",
83                         "validation.properties" };
84
85         public static final String REDIRECT_URL_KEY = "redirectUrl";
86
87         private final boolean enforcePortalSecurity;
88         private final PortalAuthManager authManager;
89
90         private final DashboardUserManager userManager;
91
92         public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager,
93                         DashboardUserManager userManager) {
94                 this.enforcePortalSecurity = portalSecurity;
95                 this.authManager = authManager;
96                 this.userManager = userManager;
97                 if (portalSecurity) {
98                         // Throw if security is requested and prerequisites are not met
99                         for (String pf : securityPropertyFiles) {
100                                 InputStream in = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(pf);
101                                 if (in == null) {
102                                         String msg = "Failed to find property file on classpath: " + pf;
103                                         logger.error(msg);
104                                         throw new RuntimeException(msg);
105                                 } else {
106                                         try {
107                                                 in.close();
108                                         } catch (IOException ex) {
109                                                 logger.warn("Failed to close stream", ex);
110                                         }
111                                 }
112                         }
113                 }
114         }
115
116         @Override
117         public void init(FilterConfig filterConfig) throws ServletException {
118                 // complain loudly if this key property is missing
119                 String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
120                 logger.debug("init: Portal redirect URL {}", url);
121                 if (url == null)
122                         logger.error(
123                                         "init: Failed to find property in portal.properties: " + PortalApiConstants.ECOMP_REDIRECT_URL);
124         }
125
126         @Override
127         public void destroy() {
128                 // No resources to release
129         }
130
131         /**
132          * Requests for pages ignored in the web security config do not hit this filter.
133          */
134         @Override
135         public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
136                         throws IOException, ServletException {
137                 if (enforcePortalSecurity)
138                         doFilterEPSDKFW(req, res, chain);
139                 else
140                         doFilterMockUserAdminRole(req, res, chain);
141         }
142
143         /*
144          * Populates security context with a mock user in the admin role.
145          * 
146          */
147         private void doFilterMockUserAdminRole(ServletRequest req, ServletResponse res, FilterChain chain)
148                         throws IOException, ServletException {
149                 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
150                 if (auth == null || auth.getAuthorities().isEmpty()) {
151                         if (logger.isDebugEnabled()) {
152                                 logger.debug("doFilter adding auth to request URI {}",
153                                                 (req instanceof HttpServletRequest) ? ((HttpServletRequest) req).getRequestURL() : req);
154                         }
155                         EcompRole admin = new EcompRole();
156                         admin.setId(1L);
157                         admin.setName(DashboardConstants.ROLE_ADMIN);
158                         HashSet<EcompRole> roles = new HashSet<>();
159                         roles.add(admin);
160                         EcompUser user = new EcompUser();
161                         user.setLoginId("fakeLoginId");
162                         user.setRoles(roles);
163                         user.setActive(true);
164                         EcompUserDetails userDetails = new EcompUserDetails(user);
165                         PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
166                                         "fakeCredentials", userDetails.getAuthorities());
167                         SecurityContextHolder.getContext().setAuthentication(authToken);
168                 } else {
169                         logger.debug("doFilter: authorities {}", auth.getAuthorities());
170                 }
171                 chain.doFilter(req, res);
172         }
173
174         /*
175          * Checks for valid cookies and allows request to be served if found; redirects
176          * to Portal otherwise.
177          */
178         private void doFilterEPSDKFW(ServletRequest req, ServletResponse res, FilterChain chain)
179                         throws IOException, ServletException {
180                 HttpServletRequest request = (HttpServletRequest) req;
181                 HttpServletResponse response = (HttpServletResponse) res;
182                 if (logger.isTraceEnabled())
183                         logger.trace("doFilter: req {}", request.getRequestURI());
184                 // Need to authenticate the request
185                 final String userId = authManager.valdiateEcompSso(request);
186                 final EcompUser ecompUser = (userId == null ? null : userManager.getUser(userId));
187                 if (userId == null || ecompUser == null) {
188                         logger.debug("doFilter: unauthorized user requests URI {}, serving login page", request.getRequestURI());
189                         StringBuffer sb = request.getRequestURL();
190                         sb.append(request.getQueryString() == null ? "" : "?" + request.getQueryString());
191                         String body = generateLoginRedirectPage(sb.toString());
192                         response.setContentType(MediaType.TEXT_HTML_VALUE);
193                         response.getWriter().print(body);
194                         response.getWriter().flush();
195                 } else {
196                         EcompUserDetails userDetails = new EcompUserDetails(ecompUser);
197                         // Using portal session as credentials is a hack
198                         PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
199                                         getPortalSessionId(request), userDetails.getAuthorities());
200                         SecurityContextHolder.getContext().setAuthentication(authToken);
201                         // Pass request back down the filter chain
202                         chain.doFilter(request, response);
203                 }
204         }
205
206         /**
207          * Generates a page with text only, absolutely no references to any webapp
208          * resources, so this can be served to an unauthenticated user without
209          * triggering a new authentication attempt. The page has a link to the Portal
210          * URL from configuration, with a return URL that is the original request.
211          * 
212          * @param appUrl
213          *                   Original requested URL
214          * @return HTML
215          * @throws UnsupportedEncodingException
216          *                                          On error
217          */
218         private static String generateLoginRedirectPage(String appUrl) throws UnsupportedEncodingException {
219                 String encodedAppUrl = URLEncoder.encode(appUrl, "UTF-8");
220                 String portalBaseUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
221                 String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl;
222                 String aHref = "<a href=\"" + redirectUrl + "\">";
223                 // If only Java had "here" documents.
224                 String body = String.join(//
225                                 System.getProperty("line.separator"), //
226                                 "<html>", //
227                                 "<head>", //
228                                 "<title>RIC Dashboard</title>", //
229                                 "<style>", //
230                                 "html, body { ", //
231                                 "  font-family: Helvetica, Arial, sans-serif;", //
232                                 "}", //
233                                 "</style>", //
234                                 "</head>", //
235                                 "<body>", //
236                                 "<h2>RIC Dashboard</h2>", //
237                                 "<h4>Please log in.</h4>", //
238                                 "<p>", //
239                                 aHref, "Click here to authenticate at the ONAP Portal</a>", //
240                                 "</p>", //
241                                 "</body>", //
242                                 "</html>");
243                 return body;
244         }
245
246         /**
247          * Searches the request for a cookie with the specified name.
248          *
249          * @param request
250          *                       HttpServletRequest
251          * @param cookieName
252          *                       Cookie name
253          * @return Cookie, or null if not found.
254          */
255         private Cookie getCookie(HttpServletRequest request, String cookieName) {
256                 Cookie[] cookies = request.getCookies();
257                 if (cookies != null)
258                         for (Cookie cookie : cookies)
259                                 if (cookie.getName().equals(cookieName))
260                                         return cookie;
261                 return null;
262         }
263
264         /**
265          * Gets the ECOMP Portal service cookie value.
266          * 
267          * @param request
268          * @return Cookie value, or null if not found.
269          */
270         private String getPortalSessionId(HttpServletRequest request) {
271                 Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE);
272                 if (ep == null)
273                         return null;
274                 return ep.getValue();
275         }
276
277 }