Skip to content

Commit

Permalink
update JWT tests to use correct mock
Browse files Browse the repository at this point in the history
  • Loading branch information
swaroopar committed Dec 30, 2023
1 parent 60f451f commit 6f64d2f
Show file tree
Hide file tree
Showing 17 changed files with 191 additions and 130 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package org.eclipse.xpanse.runtime;

import static org.mockito.Mockito.when;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.test.context.TestSecurityContextHolder;

/**
* Class to configure the JWT token mock.
*/
public abstract class AbstractJwtTestConfiguration {

public void updateJwtInSecurityContext(Map<String, Object> claims, List<String> roles) {
Map<String, Object> updatedClaims = claims.isEmpty() ? Collections.singletonMap("sub", "userId") : claims;
final JwtAuthenticationToken
auth =
(JwtAuthenticationToken) TestSecurityContextHolder.getContext().getAuthentication();
final Jwt
jwt = new Jwt("test", Instant.now(), Instant.now(),
Collections.singletonMap("alg", "none"),
updatedClaims);
when(auth.getPrincipal()).thenReturn(jwt);
when(auth.getCredentials()).thenReturn(jwt);
when(auth.getToken()).thenReturn(jwt);
when(auth.getTokenAttributes()).thenReturn(updatedClaims);
Collection<GrantedAuthority> authorities = new ArrayList<>();
roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
when(auth.getAuthorities()).thenReturn(authorities);
}

public void updateJwtInSecurityContextWithSpecificUser(Map<String, Object> claims, List<String> roles, String userId) {
Map<String, Object> updatedClaims = new HashMap<>();
if (claims.isEmpty()) {
updatedClaims.put("sub", userId);
} else {
claims.put("sub", userId);
updatedClaims = claims;

}
updateJwtInSecurityContext(updatedClaims, roles);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@

package org.eclipse.xpanse.runtime;

import static org.eclipse.xpanse.modules.models.security.constant.RoleConstants.ROLE_ADMIN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.xpanse.modules.database.DatabaseManager;
import org.eclipse.xpanse.modules.deployment.deployers.terraform.TerraformBootManager;
import org.eclipse.xpanse.modules.models.security.constant.RoleConstants;
import org.eclipse.xpanse.modules.models.service.common.enums.Csp;
import org.eclipse.xpanse.modules.models.system.BackendSystemStatus;
import org.eclipse.xpanse.modules.models.system.SystemStatus;
Expand All @@ -38,6 +38,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.CollectionUtils;
Expand All @@ -49,7 +50,7 @@
@ExtendWith(SpringExtension.class)
@SpringBootTest(properties = {"spring.profiles.active=zitadel,zitadel-testbed"})
@AutoConfigureMockMvc
class AdminServicesApiTest {
class AdminServicesApiTest extends AbstractJwtTestConfiguration {

private final ObjectMapper objectMapper = new ObjectMapper();

Expand All @@ -67,10 +68,10 @@ class AdminServicesApiTest {
private PolicyManager policyManager;

@Test
@WithMockJwtAuth(authorities = RoleConstants.ROLE_ADMIN,
claims = @OpenIdClaims(sub = "adminId", preferredUsername = "adminName"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testHealthCheck() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_ADMIN));
SystemStatus systemStatus = new SystemStatus();
systemStatus.setHealthStatus(HealthStatus.OK);
List<BackendSystemStatus> backendSystemStatuses = setUpBackendSystemStatusList(true);
Expand All @@ -93,10 +94,10 @@ void testHealthCheck() throws Exception {
}

@Test
@WithMockJwtAuth(authorities = {"isv", "user"},
claims = @OpenIdClaims(sub = "userId", preferredUsername = "userName"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testHealthCheckWithRoleNotAdmin() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList("user"));
SystemStatus systemStatus = new SystemStatus();
systemStatus.setHealthStatus(HealthStatus.OK);
List<BackendSystemStatus> backendSystemStatuses = setUpBackendSystemStatusList(false);
Expand All @@ -119,10 +120,10 @@ void testHealthCheckWithRoleNotAdmin() throws Exception {
}

@Test
@WithMockJwtAuth(authorities = RoleConstants.ROLE_ADMIN,
claims = @OpenIdClaims(sub = "adminId", preferredUsername = "adminName"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testGetCsps() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_ADMIN));
List<Csp> cspList = Arrays.asList(Csp.values());
String resultBody = objectMapper.writeValueAsString(cspList);

Expand All @@ -139,10 +140,10 @@ void testGetCsps() throws Exception {
}

@Test
@WithMockJwtAuth(authorities = RoleConstants.ROLE_ADMIN,
claims = @OpenIdClaims(sub = "adminId", preferredUsername = "adminName"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testGetCspsWithActive() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_ADMIN));
List<Csp> cspList = pluginManager.getPluginsMap().keySet().stream().sorted().toList();
String resultBody = objectMapper.writeValueAsString(cspList);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@

package org.eclipse.xpanse.runtime;

import static org.eclipse.xpanse.modules.models.security.constant.RoleConstants.ROLE_ADMIN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import java.util.ArrayList;
Expand All @@ -37,6 +37,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

Expand All @@ -47,7 +48,7 @@
@ExtendWith(SpringExtension.class)
@SpringBootTest(properties = {"spring.profiles.active=zitadel,zitadel-testbed,terraform-boot"})
@AutoConfigureMockMvc
class AdminServicesApiWithTerraformBootTest {
class AdminServicesApiWithTerraformBootTest extends AbstractJwtTestConfiguration {

private final ObjectMapper objectMapper = new ObjectMapper();
@Resource
Expand Down Expand Up @@ -82,10 +83,10 @@ void testHealthCheckUnauthorized() throws Exception {


@Test
@WithMockJwtAuth(authorities = {"admin"},
claims = @OpenIdClaims(sub = "admin-id", preferredUsername = "xpanse-admin"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testHealthCheckWithRoleAdmin() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_ADMIN));
SystemStatus systemStatus = new SystemStatus();
systemStatus.setHealthStatus(HealthStatus.OK);
systemStatus.setBackendSystemStatuses(setUpBackendSystemStatusList(true));
Expand All @@ -105,10 +106,10 @@ void testHealthCheckWithRoleAdmin() throws Exception {


@Test
@WithMockJwtAuth(authorities = {"user", "csp"},
claims = @OpenIdClaims(sub = "user-id", preferredUsername = "xpanse-user"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testHealthCheckWithRoleNotAdmin() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList("user"));
SystemStatus systemStatus = new SystemStatus();
systemStatus.setHealthStatus(HealthStatus.OK);
systemStatus.setBackendSystemStatuses(setUpBackendSystemStatusList(false));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@

package org.eclipse.xpanse.runtime;

import static org.eclipse.xpanse.modules.models.security.constant.RoleConstants.ROLE_ADMIN;
import static org.eclipse.xpanse.modules.models.security.constant.RoleConstants.ROLE_USER;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import java.util.ArrayList;
Expand All @@ -38,6 +39,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

Expand Down Expand Up @@ -83,10 +85,10 @@ void testHealthCheckUnauthorized() throws Exception {


@Test
@WithMockJwtAuth(authorities = {"admin"},
claims = @OpenIdClaims(sub = "admin-id", preferredUsername = "xpanse-admin"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testHealthCheckWithRoleAdmin() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_ADMIN));
SystemStatus systemStatus = new SystemStatus();
systemStatus.setHealthStatus(HealthStatus.OK);
systemStatus.setBackendSystemStatuses(setUpBackendSystemStatusList(true));
Expand All @@ -106,10 +108,10 @@ void testHealthCheckWithRoleAdmin() throws Exception {


@Test
@WithMockJwtAuth(authorities = {"user", "csp"},
claims = @OpenIdClaims(sub = "user-id", preferredUsername = "xpanse-user"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testHealthCheckWithRoleNotAdmin() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_USER));
SystemStatus systemStatus = new SystemStatus();
systemStatus.setHealthStatus(HealthStatus.OK);
systemStatus.setBackendSystemStatuses(setUpBackendSystemStatusList(false));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.eclipse.xpanse.runtime;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.eclipse.xpanse.modules.models.security.constant.RoleConstants.ROLE_USER;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
Expand All @@ -9,9 +10,7 @@
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockBearerTokenAuthentication;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.common.ClasspathFileSource;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
Expand All @@ -37,14 +36,15 @@
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;

@ExtendWith(SpringExtension.class)
@SpringBootTest(properties = {"spring.profiles.active=zitadel,zitadel-testbed"})
@AutoConfigureMockMvc
class AuthorizationApiTest {
class AuthorizationApiTest extends AbstractJwtTestConfiguration {

@RegisterExtension
static WireMockExtension wireMockExtension = WireMockExtension.newInstance()
Expand Down Expand Up @@ -136,10 +136,10 @@ void testCallApiUnauthorized() throws Exception {
}

@Test
@WithMockBearerTokenAuthentication(authorities = {"csp"},
attributes = @OpenIdClaims(sub = "csp-id", preferredUsername = "xpanse-csp"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testCallApiAccessDenied() throws Exception {
// SetUp
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.emptyList());
Response responseModel = Response.errorResponse(ResultType.ACCESS_DENIED,
Collections.singletonList(ResultType.ACCESS_DENIED.toValue()));
String resBody = objectMapper.writeValueAsString(responseModel);
Expand All @@ -155,9 +155,10 @@ void testCallApiAccessDenied() throws Exception {
}

@Test
@WithMockJwtAuth(authorities = {"user"},
claims = @OpenIdClaims(sub = "user-id", preferredUsername = "xpanse-user"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testCallApiWell() throws Exception {
// SetUp
super.updateJwtInSecurityContextWithSpecificUser(Collections.emptyMap(), Collections.singletonList(ROLE_USER), "dummy");
// Run the test
final MockHttpServletResponse response = mockMvc.perform(get("/xpanse/services")
.accept(MediaType.APPLICATION_JSON))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@

package org.eclipse.xpanse.runtime;

import static org.eclipse.xpanse.modules.models.security.constant.RoleConstants.ROLE_ADMIN;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
Expand All @@ -29,7 +29,6 @@
import lombok.extern.slf4j.Slf4j;
import org.eclipse.xpanse.modules.models.response.Response;
import org.eclipse.xpanse.modules.models.response.ResultType;
import org.eclipse.xpanse.modules.models.security.constant.RoleConstants;
import org.eclipse.xpanse.modules.models.servicetemplate.FlavorBasic;
import org.eclipse.xpanse.modules.models.servicetemplate.Ocl;
import org.eclipse.xpanse.modules.models.servicetemplate.utils.OclLoader;
Expand All @@ -46,6 +45,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

Expand All @@ -57,7 +57,7 @@
@ExtendWith(SpringExtension.class)
@SpringBootTest(properties = {"spring.profiles.active=zitadel,zitadel-testbed"})
@AutoConfigureMockMvc
class ServiceCatalogApiTest {
class ServiceCatalogApiTest extends AbstractJwtTestConfiguration {

private final static ObjectMapper objectMapper = new ObjectMapper();
private static String id;
Expand All @@ -77,9 +77,9 @@ static void configureObjectMapper() {
}

@Test
@WithMockJwtAuth(authorities = RoleConstants.ROLE_ADMIN,
claims = @OpenIdClaims(sub = "adminId", preferredUsername = "adminName"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testOrderableServices() throws Exception {
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_ADMIN));
registerService();
Thread.sleep(3000);
testOpenApi();
Expand All @@ -89,9 +89,9 @@ void testOrderableServices() throws Exception {
}

@Test
@WithMockJwtAuth(authorities = RoleConstants.ROLE_ADMIN,
claims = @OpenIdClaims(sub = "adminId", preferredUsername = "adminName"))
@WithMockAuthentication(authType = JwtAuthenticationToken.class)
void testOrderableServicesThrowsException() throws Exception {
super.updateJwtInSecurityContext(Collections.emptyMap(), Collections.singletonList(ROLE_ADMIN));
testOrderableServiceDetailsThrowsException();
testListOrderableServicesThrowsException();
testOpenApiThrowsException();
Expand Down

0 comments on commit 6f64d2f

Please sign in to comment.