Integrate EPSDK-FW library for auth and users
[portal/ric-dashboard.git] / webapp-backend / src / test / java / org / oransc / ric / portal / dashboard / config / WebSecurityMockConfiguration.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.config;
21
22 import static org.mockito.ArgumentMatchers.any;
23 import static org.mockito.Mockito.doAnswer;
24 import static org.mockito.Mockito.mock;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.lang.invoke.MethodHandles;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Map;
32 import java.util.Set;
33
34 import javax.servlet.http.HttpServletRequest;
35
36 import org.onap.portalsdk.core.onboarding.crossapi.PortalRestAPIProxy;
37 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
38 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
39 import org.onap.portalsdk.core.restful.domain.EcompRole;
40 import org.onap.portalsdk.core.restful.domain.EcompUser;
41 import org.oransc.ric.portal.dashboard.DashboardConstants;
42 import org.oransc.ric.portal.dashboard.LoginServlet;
43 import org.oransc.ric.portal.dashboard.portalapi.DashboardUserManager;
44 import org.oransc.ric.portal.dashboard.portalapi.PortalAuthManager;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Value;
48 import org.springframework.boot.web.servlet.ServletRegistrationBean;
49 import org.springframework.context.annotation.Bean;
50 import org.springframework.context.annotation.Configuration;
51 import org.springframework.context.annotation.Profile;
52 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
53 import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
54 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
55 import org.springframework.security.config.annotation.web.builders.WebSecurity;
56 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
57 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
58 import org.springframework.security.crypto.factory.PasswordEncoderFactories;
59 import org.springframework.security.crypto.password.PasswordEncoder;
60
61 @Configuration
62 @EnableWebSecurity
63 @EnableGlobalMethodSecurity(securedEnabled = true)
64 @Profile("test")
65 public class WebSecurityMockConfiguration extends WebSecurityConfigurerAdapter {
66
67         public static final String TEST_CRED_ADMIN = "admin";
68         public static final String TEST_CRED_STANDARD = "standard";
69
70         // Unfortunately EPSDK-FW does not define these as constants
71         public static final String PORTAL_USERNAME_HEADER_KEY = "username";
72         public static final String PORTAL_PASSWORD_HEADER_KEY = "password";
73
74         private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
75
76         public WebSecurityMockConfiguration(@Value("${userfile}") final String userFilePath) {
77                 logger.debug("ctor: user file path {}", userFilePath);
78         }
79
80         @Override
81         protected void configure(AuthenticationManagerBuilder auth) throws Exception {
82                 PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
83                 auth.inMemoryAuthentication() //
84                                 .passwordEncoder(encoder) //
85                                 // The admin user has the admin AND standard roles
86                                 .withUser(TEST_CRED_ADMIN) //
87                                 .password(encoder.encode(TEST_CRED_ADMIN))
88                                 .roles(DashboardConstants.ROLE_NAME_ADMIN, DashboardConstants.ROLE_NAME_STANDARD)//
89                                 .and()//
90                                 // The standard user has only the standard role
91                                 .withUser(TEST_CRED_STANDARD) //
92                                 .password(encoder.encode(TEST_CRED_STANDARD)) //
93                                 .roles(DashboardConstants.ROLE_NAME_STANDARD);
94         }
95
96         @Override
97         protected void configure(HttpSecurity http) throws Exception {
98                 http.authorizeRequests().anyRequest().authenticated()//
99                                 .and().httpBasic() //
100                                 .and().csrf().disable();
101         }
102
103         @Override
104         public void configure(WebSecurity web) throws Exception {
105                 // This disables Spring security, but not the app's filter.
106                 web.ignoring().antMatchers(WebSecurityConfiguration.OPEN_PATHS);
107         }
108
109         @Bean
110         public ServletRegistrationBean<LoginServlet> loginServlet() {
111                 LoginServlet servlet = new LoginServlet();
112                 final ServletRegistrationBean<LoginServlet> servletBean = new ServletRegistrationBean<>(servlet,
113                                 DashboardConstants.LOGIN_PAGE);
114                 servletBean.setName("LoginServlet");
115                 return servletBean;
116         }
117
118         @Bean
119         public ServletRegistrationBean<PortalRestAPIProxy> portalApiProxyServlet() {
120                 PortalRestAPIProxy servlet = new PortalRestAPIProxy();
121                 final ServletRegistrationBean<PortalRestAPIProxy> servletBean = new ServletRegistrationBean<>(servlet,
122                                 PortalApiConstants.API_PREFIX + "/*");
123                 servletBean.setName("PortalRestApiProxyServlet");
124                 return servletBean;
125         }
126
127         @Bean
128         public PortalAuthManager portalAuthManager() throws Exception {
129                 PortalAuthManager mockManager = mock(PortalAuthManager.class);
130                 final Map<String, String> credentialsMap = new HashMap<>();
131                 credentialsMap.put("appName", "appName");
132                 credentialsMap.put(PORTAL_USERNAME_HEADER_KEY, PORTAL_USERNAME_HEADER_KEY);
133                 credentialsMap.put(PORTAL_PASSWORD_HEADER_KEY, PORTAL_PASSWORD_HEADER_KEY);
134                 doAnswer(inv -> {
135                         logger.debug("getAppCredentials");
136                         return credentialsMap;
137                 }).when(mockManager).getAppCredentials();
138                 doAnswer(inv -> {
139                         logger.debug("getUserId");
140                         return "userId";
141                 }).when(mockManager).valdiateEcompSso(any(HttpServletRequest.class));
142                 doAnswer(inv -> {
143                         logger.debug("getAppCredentials");
144                         return credentialsMap;
145                 }).when(mockManager).getAppCredentials();
146                 return mockManager;
147         }
148
149         // This implementation is so light it can be used during tests.
150         @Bean
151         public DashboardUserManager dashboardUserManager() throws IOException, PortalAPIException {
152                 File f = new File("/tmp/users.json");
153                 if (f.exists())
154                         f.delete();
155                 DashboardUserManager um = new DashboardUserManager(f.getAbsolutePath());
156                 // Mock user for convenience in testing
157                 EcompUser demo = new EcompUser();
158                 demo.setLoginId("demo");
159                 demo.setFirstName("Demo");
160                 demo.setLastName("User");
161                 demo.setActive(true);
162                 EcompRole role = new EcompRole();
163                 role.setName("view");
164                 Set<EcompRole> roles = new HashSet<>();
165                 roles.add(role);
166                 demo.setRoles(roles);
167                 um.createUser(demo);
168                 return um;
169         }
170
171 }