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