summaryrefslogtreecommitdiffstats
path: root/security-util-lib/src/main/java/org/onap/sdc/security/filters/RestrictionAccessFilter.java
blob: 0bfaaaf937433a456a39e6f8e6c1366ae1a2aaa9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.sdc.security.filters;

import static org.onap.sdc.security.utils.SecurityLogsUtils.PORTAL_TARGET_ENTITY;
import static org.onap.sdc.security.utils.SecurityLogsUtils.fullOptionalData;

import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.onap.sdc.security.AuthenticationCookie;
import org.onap.sdc.security.CipherUtil;
import org.onap.sdc.security.CipherUtilException;
import org.onap.sdc.security.ISessionValidationFilterConfiguration;
import org.onap.sdc.security.IUsersThreadLocalHolder;
import org.onap.sdc.security.PortalClient;
import org.onap.sdc.security.RedirectException;
import org.onap.sdc.security.RepresentationUtils;
import org.onap.sdc.security.RestrictionAccessFilterException;
import org.onap.sdc.security.logging.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("restrictionAccessFilter")
public class RestrictionAccessFilter extends SessionValidationFilter {

    private final ISessionValidationFilterConfiguration filterConfiguration;

    private static final Logger log = Logger.getLogger(RestrictionAccessFilter.class.getName());
    private static final String LOCATION_HEADER = "RedirectLocation";

    private static final String SESSION_IS_EXPIRED_MSG = "Session is expired for user %s";
    protected static final String CSP_USER_ID = "HTTP_CSP_ID";

    private PortalClient portalClient;
    private IUsersThreadLocalHolder threadLocalUtils;

    @Autowired
    public RestrictionAccessFilter(ISessionValidationFilterConfiguration configuration,
        IUsersThreadLocalHolder threadLocalUtils, PortalClient portalClient) {
        this.filterConfiguration = configuration;
        this.threadLocalUtils = threadLocalUtils;
        this.portalClient = portalClient;
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        super.doFilter(servletRequest, servletResponse, filterChain);
    }

    @Override
    protected Cookie addRoleToCookie(Cookie cookie) throws RedirectException {
        AuthenticationCookie authenticationCookie;
        Set<String> updatedRolesSet = new HashSet<>();
        try {
            log.debug("Adding the role to the cookie.");
            authenticationCookie = getAuthenticationCookie(cookie);
            if (!CollectionUtils.isEmpty(authenticationCookie.getRoles())) {
                log.debug("Cookie already contains a role in its set of roles authenticationCookie Roles: {}",
                    authenticationCookie.getRoles());
                threadLocalUtils.setUserContext(authenticationCookie);
                return cookie;
            }
            Optional<String> fetchedRole = portalClient.fetchUserRolesFromPortal(authenticationCookie.getUserID());
            log.debug("addRoleToCookie: Finished fetching user role from Portal. Adding it to the cookie");
            if (fetchedRole.isPresent()) {
                updatedRolesSet.add(fetchedRole.get());
            }
            authenticationCookie.setRoles(updatedRolesSet);
            String changedCookieJson = RepresentationUtils.toRepresentation(authenticationCookie);
            log.debug("addRoleToCookie: Changed cookie Json: {}", changedCookieJson);
            cookie.setValue(CipherUtil.encryptPKC(changedCookieJson, getFilterConfiguration().getSecurityKey()));
            threadLocalUtils.setUserContext(authenticationCookie);
        } catch (IOException e) {
            throw new RestrictionAccessFilterException(e);
        } catch (CipherUtilException e) {
            throw new RedirectException(e);
        }
        return cookie;
    }

    private AuthenticationCookie getAuthenticationCookie(Cookie cookie) throws CipherUtilException {
        AuthenticationCookie authenticationCookie;
        String originalCookieJson = retrieveOriginalCookieJson(cookie);
        authenticationCookie = getAuthenticationCookie(originalCookieJson);
        return authenticationCookie;
    }

    @Override
    public void authorizeUserOnSessionExpiration(AuthenticationCookie authenticationCookie, Cookie[] cookies)
        throws RedirectException {
        log.debug("Portal fetch user role is enabled");
        if (!isAuthenticatedUserSimilarToCspUser(authenticationCookie, cookies) ||
            areUserRolesChanged(authenticationCookie)) {
            String msg = String.format(SESSION_IS_EXPIRED_MSG, authenticationCookie.getUserID());
            log.debug(msg);
            throw new RedirectException(msg);
        }
    }

    @Override
    protected void handleRedirectException(HttpServletResponse httpServletResponse) throws IOException {

        httpServletResponse.setHeader(LOCATION_HEADER, filterConfiguration.getRedirectURL());
        httpServletResponse.setStatus(403);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.getWriter().write(RepresentationUtils.toRepresentation
            ("Your session has expired. Please close the SDC tab and re-enter the SDC application."));
    }

    private boolean areUserRolesChanged(AuthenticationCookie authenticationCookie) {
        String cookieRole = "";
        if (!CollectionUtils.isEmpty(authenticationCookie.getRoles())) {
            log.debug("Cookie contains a role in its set of roles: {}", authenticationCookie.getRoles().toString());
            cookieRole = (String) authenticationCookie.getRoles().iterator().next();
        }
        // TODO: For future reference, when multi roles exist replace to something like:
        // TODO: authenticationCookie.getRoles().stream().forEach((role) -> areRolesEqual = areRolesEqual(user.getRole(), role));
        log.debug("Fetching roles from portal for user {}", authenticationCookie.getUserID());
        Optional<String> portalRole = portalClient.fetchUserRolesFromPortal(authenticationCookie.getUserID());
        log.debug("{} user role on portal is {}, in the cookie is {}", portalRole, cookieRole);
        boolean isCookieRoleEmpty = StringUtils.isEmpty(cookieRole);
        //If the cookieRole is empty or if portalRole is different than cookieRole or if cookieRole is not empty and
        //portalRole is not empty then return true otherwise false.
        return isCookieRoleEmpty ||
            (portalRole.isPresent() ? !cookieRole.equalsIgnoreCase(portalRole.get()) : !isCookieRoleEmpty);
    }

    private boolean isAuthenticatedUserSimilarToCspUser(AuthenticationCookie cookie, Cookie[] cookies)
        throws RedirectException {
        String cspUserId = getCookieValue(cookies, CSP_USER_ID);
        if (cspUserId != null && cspUserId.equals(cookie.getUserID())) {
            log.debug("Auth and CSP user IDs are same: {}", cookie.getUserID());
            return true;
        }
        return false;
    }

    @VisibleForTesting
    public String getCookieValue(Cookie[] cookies, String name) throws RedirectException {
        if (ArrayUtils.isNotEmpty(cookies)) {
            List<Cookie> foundCookies = Arrays.stream(cookies)
                .filter(c -> c.getName().endsWith(name))
                .collect(Collectors.toList());
            if (foundCookies.size() > 0) {
                log.debug("getCookieValue: Found {} cookies with name: {}", foundCookies.size(), name);
                return foundCookies.get(0).getValue();
            }
        }
        throw new RedirectException("No cookies found with name " + name);
    }

    @Override
    public ISessionValidationFilterConfiguration getFilterConfiguration() {
        return filterConfiguration;
    }

    private boolean areRolesEqual(String role, String roleFromDB) {
        return !StringUtils.isEmpty(role) && role.equalsIgnoreCase(roleFromDB);
    }

    private String retrieveOriginalCookieJson(Cookie cookie) throws CipherUtilException {
        return CipherUtil.decryptPKC(cookie.getValue(), filterConfiguration.getSecurityKey());
    }

    private AuthenticationCookie getAuthenticationCookie(String originalCookieJson) {
        return RepresentationUtils.fromRepresentation(originalCookieJson, AuthenticationCookie.class);
    }

}