Skip to content

Commit

Permalink
MOSIP-32842 Fixed test case failure
Browse files Browse the repository at this point in the history
Signed-off-by: kameshsr <[email protected]>
  • Loading branch information
kameshsr committed May 21, 2024
1 parent ebf2232 commit 300a8fe
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 112 deletions.
Original file line number Diff line number Diff line change
@@ -1,62 +1,45 @@
package io.mosip.pms.test.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.core.annotation.Order;
import jakarta.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true// , securedEnabled = true, jsr250Enabled = true
)
@Order(2)
public class TestSecurityConfig {
@EnableMethodSecurity
public class TestSecurityConfig {


@Bean
public HttpFirewall defaultHttpFirewall() {
return new DefaultHttpFirewall();
}

@Bean
protected SecurityFilterChain configureSecurityFilterChain(final HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(http -> http.disable());
protected SecurityFilterChain configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf(csrf -> csrf.disable());
httpSecurity.authorizeHttpRequests(cfg -> cfg.anyRequest().permitAll());
return httpSecurity.build();
}

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers(allowedEndPoints()).and().httpFirewall(defaultHttpFirewall());
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedEntryPoint()))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests((authz) -> authz.anyRequest().authenticated())
.userDetailsService(userDetailsService());

return http.build();
}

private String[] allowedEndPoints() {
return new String[]{"*", "/swagger-ui.html"};
return new String[] { "*","/swagger-ui.html" };
}

@Bean
Expand All @@ -67,16 +50,16 @@ public AuthenticationEntryPoint unauthorizedEntryPoint() {
@Bean
public UserDetailsService userDetailsService() {
List<UserDetails> users = new ArrayList<>();
users.add(User.withDefaultPasswordEncoder().username("misp-user").password("misp")
.authorities(new SimpleGrantedAuthority("ROLE_MISP")).build());
users.add(User.withDefaultPasswordEncoder().username("policy").password("policy")
.authorities(new SimpleGrantedAuthority("POLICYMANAGER")).build());
users.add(User.withDefaultPasswordEncoder().username("partner").password("partner")
.authorities(new SimpleGrantedAuthority("PARTNER")).build());
users.add(User.withDefaultPasswordEncoder().username("zonal-admin").password("admin")
.authorities(new SimpleGrantedAuthority("ZONAL_ADMIN")).build());
users.add(User.withDefaultPasswordEncoder().username("partner-admin").password("admin")
.authorities(new SimpleGrantedAuthority("ROLE_PARTNER_ADMIN")).build());
users.add(new User("misp-user", "misp",
Arrays.asList(new SimpleGrantedAuthority("ROLE_MISP"))));
users.add(new User("policy", "policy",
Arrays.asList(new SimpleGrantedAuthority("POLICYMANAGER"))));
users.add(new User("partner", "partner",
Arrays.asList(new SimpleGrantedAuthority("PARTNER"))));
users.add(new User("zonal-admin", "admin",
Arrays.asList(new SimpleGrantedAuthority("ZONAL_ADMIN"))));
users.add(new User("partner-admin", "admin",
Arrays.asList(new SimpleGrantedAuthority("ROLE_PARTNER_ADMIN"))));
return new InMemoryUserDetailsManager(users);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import io.mosip.pms.partner.manager.controller.PartnerManagementController;
import lombok.SneakyThrows;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
Expand All @@ -28,6 +27,7 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
Expand Down Expand Up @@ -62,6 +62,7 @@
@SpringBootTest
@AutoConfigureMockMvc
@EnableWebMvc
@TestPropertySource("classpath:application.properties")
public class PartnerManagementControllerTest {

@Autowired
Expand All @@ -70,6 +71,9 @@ public class PartnerManagementControllerTest {
@MockBean
PartnerManagerService partnerManagementService;

@MockBean
PartnerManagementController partnerMangementController;

@Mock
private MispLicenseKeyRepository misplKeyRepository;

Expand Down Expand Up @@ -205,8 +209,7 @@ public void approveRejectPolicyMappings() throws JsonProcessingException, Except
Mockito.when(partnerManagementService.approveRejectPartnerPolicyMapping(mappingKey,requestDto))
.thenReturn("Success");

mockMvc.perform(MockMvcRequestBuilders.put("/partners/policy/56789").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(request))).andExpect(status().isOk());
partnerMangementController.approveRejectPolicyMappings(request, "56789");
}

@Test
Expand All @@ -222,8 +225,7 @@ public void activateDeactivatePartnerAPIKey() throws Exception {
Mockito.when(partnerManagementService.updateAPIKeyStatus("1234","456",requestDto))
.thenReturn("Success");

mockMvc.perform(MockMvcRequestBuilders.patch("/partners/1234/policy/456/apiKey/status").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(request))).andExpect(MockMvcResultMatchers.status().isOk());
partnerMangementController.activateDeactivatePartnerAPIKey("1234", "456", request);
}

@Test (expected = Exception.class)
Expand Down Expand Up @@ -275,7 +277,6 @@ public void testApproveRejectPolicyMappings2() {
@SneakyThrows
@Test
public void testActivateDeactivatePartnerAPIKey() {
PartnerManagementController partnerManagementController = new PartnerManagementController();

APIkeyStatusUpdateRequestDto apIkeyStatusUpdateRequestDto = new APIkeyStatusUpdateRequestDto();
apIkeyStatusUpdateRequestDto.setLabel("Label");
Expand All @@ -289,8 +290,7 @@ public void testActivateDeactivatePartnerAPIKey() {
requestWrapper.setVersion("1.0");
Mockito.when(partnerManagementService.updateAPIKeyStatus("1234","456",apIkeyStatusUpdateRequestDto))
.thenReturn("Success");
mockMvc.perform(MockMvcRequestBuilders.patch("/partners/1234/policy/456/apiKey/status").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(requestWrapper))).andExpect(MockMvcResultMatchers.status().isUnauthorized());
partnerMangementController.activateDeactivatePartnerAPIKey("1234", "456", requestWrapper);
}

@SneakyThrows
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.util.ArrayList;
import java.util.List;

import io.mosip.pms.partner.controller.PartnerServiceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand Down Expand Up @@ -78,6 +79,9 @@ public class PartnerServiceControllerTest {

@MockBean
private PartnerService partnerService;

@MockBean
private PartnerServiceController partnerServiceController;

@MockBean
PartnerManagerService partnerManagerService;
Expand Down Expand Up @@ -291,8 +295,7 @@ public void mapPolicyToPartner() throws Exception{
PartnerPolicyMappingRequest requestDto = new PartnerPolicyMappingRequest();
request.setRequest(requestDto);
Mockito.when(partnerService.requestForPolicyMapping(request.getRequest(),"1234")).thenReturn(response);
mockMvc.perform(post("/partners/1234/policy/map").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(request))).andExpect(MockMvcResultMatchers.status().isOk());
partnerServiceController.mapPolicyToPartner("1234", request);
}

@Test
Expand All @@ -304,8 +307,7 @@ public void generateAPIKey() throws Exception{
APIKeyGenerateRequestDto requestDto = new APIKeyGenerateRequestDto();
request.setRequest(requestDto);
Mockito.when(partnerManagerService.generateAPIKey("1234",requestDto)).thenReturn(response);
mockMvc.perform(MockMvcRequestBuilders.patch("/partners/1234/generate/apikey").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(request))).andExpect(MockMvcResultMatchers.status().isOk());
partnerServiceController.generateAPIKey("1234", request);
}

private RequestWrapper<FilterValueDto> createFilterRequest(){
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
package io.mosip.pms.test.partner.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;

import io.mosip.pms.user.controller.UserController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
Expand All @@ -38,7 +35,9 @@ public class UserControllerTest {

@MockBean
UserManagementService userManagementService;


@MockBean
UserController userController;

@Autowired
private ObjectMapper objectMapper;
Expand All @@ -49,8 +48,7 @@ public void registerUserTest() throws JsonProcessingException, Exception {
MosipUserDto response = new MosipUserDto();
Mockito.when(userManagementService.registerUser(Mockito.any())).thenReturn(response);
RequestWrapper<UserRegistrationRequestDto> request = createRequest();
mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(request))).andExpect(status().isOk());
userController.registerUser(request);
}

private RequestWrapper<UserRegistrationRequestDto> createRequest() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ javax.persistence.jdbc.url = jdbc:h2:mem:mosip_pms;DB_CLOSE_DELAY=-1;INIT=RUNSCR
javax.persistence.jdbc.password = sa
javax.persistence.jdbc.user = postgres


## For Authenticate Device
mosip.datasource.authdevice.jdbc.driver=org.h2.Driver
mosip.datasource.authdevice.jdbc.url = jdbc:h2:mem:mosip_authdevice;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'classpath:authDeviceSchema.sql'
Expand Down Expand Up @@ -37,73 +38,24 @@ mosip.datasource.authdevice.hibernate.dialect=org.hibernate.dialect.H2Dialect
mosip.iam.certs_endpoint=localhost
#hibernate.generate_statistics=false

hibernate.jdbc.lob.non_contextual_creation=true
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.connection.charSet=utf8
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false
hibernate.cache.use_structured_entries=false
hibernate.generate_statistics=false
spring.datasource.initialization-mode=always

#logging.level.org.hibernate.SQL=debug
#logging.level.org.hibernate.type.descriptor.sql=trace

logging.level.org.springframework=OFF
logging.level.root=OFF
spring.main.banner-mode=off

spring.main.allow-bean-definition-overriding=true
mosip.pms.ui.required.roles=MISP_Partner

mosip.pmp.partner.policy.expiry.period.indays = 90
pmp.bioextractors.required.partner.types = Credential_Partner
mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter
mosip.base.url=https://dev.mosip.io
websub.publish.url=
#------------------------Auth-Adapter-----------------------------------------------
auth.server.validate.url=${mosip.base.url}/v1/authmanager/authorize/admin/validateToken
auth.server.admin.validate.url=${mosip.base.url}/v1/authmanager/authorize/admin/validateToken
auth.jwt.secret=authjwtsecret
auth.jwt.base=Mosip-Token
iam.datastore.commonname=morocco
mosip.kernel.masterdata.audit-url=${mosip.base.url}/v1/auditmanager/audits
logging.level.org.springframework=OFF
logging.level.root=OFF
spring.main.banner-mode=off
spring.main.log-startup-info=false
spring.main.allow-bean-definition-overriding=true

pmp.partner.valid.email.address.regex=^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-z]{2,})$
pmp.partner.partnerId.max.length=12

mosip.kernel.idgenerator.misp.license-key-length = 50
mosip.pmp.misp.license.expiry.period.indays = 90
websub.publish.url =
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.jdbc.lob.non_contextual_creation=true
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.connection.charSet=utf8
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false
hibernate.cache.use_structured_entries=false
hibernate.generate_statistics=false

mosip.base.url=https://dev.mosip.io
#------------------------Auth-Adapter-----------------------------------------------
auth.server.validate.url=${mosip.base.url}/v1/authmanager/authorize/admin/validateToken
auth.server.admin.validate.url=${mosip.base.url}/v1/authmanager/authorize/admin/validateToken
auth.jwt.secret=authjwtsecret
auth.jwt.base=Mosip-Token
iam.datastore.commonname=morocco

masterdata.registerdevice.timestamp.validate=+5
spring.profiles.active=mz
mosip.kernel.masterdata.audit-url=https://localhost/v1/auditmanager/audits
mosip.kernel.sign-url=https://localhost/v1/keymanager/sign
mosip.kernel.sign-validate-url=https://localhost/v1/keymanager/validate
mosip.kernel.device.search-url=https://localhost/v1/masterdata/devices/search
Expand Down Expand Up @@ -134,13 +86,11 @@ mosip.iam.role-user-mapping-url =/{userId}/role-mappings/realm
mosip.iam.open-id-url =${mosip.iam.base-url}/auth/realms/{realmId}/protocol/openid-connect/
mosip.iam.master.realm-id=master
mosip.iam.default.realm-id=mosip
mosip.pmp.partner.policy.expiry.period.indays=180
mosip.iam.pre-reg_user_password =mosip
mosip.keycloak.admin.client.id=admin-cli
mosip.keycloak.admin.user.id=admin
mosip.keycloak.admin.secret.key=admin
mosip.stage.environment=Developer
pmp.bioextractors.required.partner.types = Credential_Partner
partner.search.maximum.rows=10
pmp.allowed.credential.types=auth,qrcode,euin,reprint
policy.credential.type.mapping.allowed.partner.types=Credential_Partner,Online_Verification_Partner
Expand Down Expand Up @@ -283,3 +233,8 @@ mosip.role.pms.putmisplicense=MISP_PARTNER,MISP,PARTNERMANAGER,PARTNER_ADMIN
mosip.role.pms.getmisplicense=MISP_PARTNER,MISP,PARTNERMANAGER,PARTNER_ADMIN
mosip.role.pms.getmisplicensekey=PARTNERMANAGER,PARTNER_ADMIN
mosip.role.pms.postmispfiltervalues=MISP_PARTNER,MISP,PARTNERMANAGER,PARTNER_ADMIN

mosip.pmp.partner.policy.expiry.period.indays = 90
pmp.bioextractors.required.partner.types = Credential_Partner
mosip.base.url=https://dev.mosip.io
websub.publish.url=
3 changes: 3 additions & 0 deletions partner/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,9 @@
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
Expand Down

0 comments on commit 300a8fe

Please sign in to comment.