Skip to content

Commit

Permalink
chore: fix sonar issues (#3789)
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Salac <[email protected]>
  • Loading branch information
richard-salac authored Sep 23, 2024
1 parent da3c034 commit 98b3394
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 301 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.hc.client5.http.utils.Base64;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.tomcat.util.codec.binary.Base64;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
Expand All @@ -29,6 +29,7 @@
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand Down Expand Up @@ -146,9 +147,9 @@ public FailedAuthenticationHandler failedAuthenticationHandler() {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeRequests(requests -> requests.anyRequest().authenticated())
.apply(new CustomSecurityFilters())
.and().build();
.authorizeHttpRequests(requests -> requests.anyRequest().authenticated())
.with(new CustomSecurityFilters(), Customizer.withDefaults())
.build();
}

@Bean
Expand All @@ -161,7 +162,7 @@ public SafMethodSecurityExpressionRoot safMethodSecurityExpressionRoot(

private class CustomSecurityFilters extends AbstractHttpConfigurer<CustomSecurityFilters, HttpSecurity> {
@Override
public void configure(HttpSecurity http) throws Exception {
public void configure(HttpSecurity http) {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);

http.addFilterBefore(new BasicContentFilter(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.zowe.apiml.constants.EurekaMetadataDefinition;
import org.zowe.apiml.message.core.Message;
import org.zowe.apiml.message.core.MessageService;
import org.zowe.apiml.product.gateway.GatewayClient;
import org.zowe.apiml.security.common.token.TokenAuthentication;

import java.util.*;
import java.util.regex.Matcher;
Expand Down Expand Up @@ -103,7 +105,7 @@ public class ValidateAPIController {
))
})
public ResponseEntity<String> checkConformance(@Parameter(in = ParameterIn.PATH, required = true, description = "Service ID of the service to check") @PathVariable String serviceId,
@Parameter(hidden = true) @CookieValue(value = "apimlAuthenticationToken", defaultValue = "dummy") String authenticationToken) {
Authentication authentication) {
ConformanceProblemsContainer foundNonConformanceIssues = new ConformanceProblemsContainer(serviceId);
foundNonConformanceIssues.add(CONFORMANCE_PROBLEMS, validateServiceIdFormat(serviceId));
if (!foundNonConformanceIssues.isEmpty())
Expand All @@ -121,7 +123,7 @@ public ResponseEntity<String> checkConformance(@Parameter(in = ParameterIn.PATH,
checkMetadataCanBeRetrieved(metadata);
Optional<String> swaggerUrl = verificationOnboardService.findSwaggerUrl(metadata);

validateSwaggerDocument(serviceId, foundNonConformanceIssues, metadata, swaggerUrl, authenticationToken);
validateSwaggerDocument(serviceId, foundNonConformanceIssues, metadata, swaggerUrl, getToken(authentication));
} catch (ValidationException e) {
switch (e.getKey()) {
case WRONG_SERVICE_ID_KEY:
Expand All @@ -142,6 +144,13 @@ public ResponseEntity<String> checkConformance(@Parameter(in = ParameterIn.PATH,
return new ResponseEntity<>("{\"message\":\"Service " + serviceId + " fulfills all checked conformance criteria\"}", HttpStatus.OK);
}

private String getToken(Authentication authentication) {
if (authentication instanceof TokenAuthentication tokenAuthentication) {
return tokenAuthentication.getCredentials();
}
return null;
}

private void validateSwaggerDocument(String serviceId, ConformanceProblemsContainer foundNonConformanceIssues, Map<String, String> metadata, Optional<String> swaggerUrl, String token) throws ValidationException {
if (swaggerUrl.isEmpty()) {
throw new ValidationException("Could not find Swagger Url", NON_CONFORMANT_KEY);
Expand Down Expand Up @@ -206,11 +215,11 @@ private void validateSwaggerDocument(String serviceId, ConformanceProblemsContai
}
))
})
public ResponseEntity<String> checkValidateLegacy(@RequestBody String serviceId, @Parameter(hidden = true) @CookieValue(value = "apimlAuthenticationToken", defaultValue = "dummy") String authenticationToken) {
public ResponseEntity<String> checkValidateLegacy(@RequestBody String serviceId, Authentication authentication) {
if (serviceId.startsWith("serviceID")) {
serviceId = serviceId.replace("serviceID=", "");
}
return checkConformance(serviceId, authenticationToken);
return checkConformance(serviceId, authentication);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,15 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import org.zowe.apiml.constants.EurekaMetadataDefinition;
import org.zowe.apiml.product.constants.CoreService;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.*;

/**
* Service class that offers methods for checking onboarding information and also checks availability metadata from
Expand Down Expand Up @@ -107,23 +94,23 @@ public String getSwagger(String swaggerUrl) {
*/
public List<String> testEndpointsByCalling(Set<Endpoint> endpoints, String passedAuthenticationToken) {
ArrayList<String> result = new ArrayList<>(checkEndpointsNoSSO(endpoints));
try {
result.addAll(checkEndpointsWithSSO(endpoints, passedAuthenticationToken));
} catch (ValidationException e) {
result.add(e.getMessage());
}
result.addAll(checkEndpointsWithSSO(endpoints, passedAuthenticationToken));

return result;
}

private List<String> checkEndpointsWithSSO(Set<Endpoint> endpoints, String passedAuthenticationToken) {
ArrayList<String> result = new ArrayList<>();

String ssoCookie = getAuthenticationCookie(passedAuthenticationToken);
if (passedAuthenticationToken == null) {
result.add("Authentication token is not available, serviceId '%s' endpoints SSO check skipped.".formatted(
endpoints.stream().findAny().map(Endpoint::getServiceId).orElse("unknown")));
return result;
}

HttpHeaders headersSSO = new HttpHeaders();
headersSSO.setContentType(MediaType.APPLICATION_JSON);
headersSSO.add("Cookie", "apimlAuthenticationToken=" + ssoCookie);
headersSSO.add("Cookie", "apimlAuthenticationToken=" + passedAuthenticationToken);
HttpEntity<String> requestSSO = new HttpEntity<>(headersSSO);

for (Endpoint endpoint : endpoints) {
Expand Down Expand Up @@ -201,33 +188,6 @@ public static List<String> getProblemsWithEndpointUrls(AbstractSwaggerValidator
return swaggerParser.getProblemsWithEndpointUrls();
}

private String getAuthenticationCookie(String passedAuthenticationToken) {
String errorMsg = "Error retrieving ZAAS connection details";
// FIXME This keeps the current behaviour
if (passedAuthenticationToken.equals("dummy")) {
URI uri = discoveryClient.getServices().stream()
.filter(service -> CoreService.ZAAS.getServiceId().equalsIgnoreCase(service))
.flatMap(service -> discoveryClient.getInstances(service).stream())
.findFirst()
.map(ServiceInstance::getUri)
.orElseThrow(() -> new ValidationException(errorMsg, ValidateAPIController.NO_METADATA_KEY));

String zaasAuthValidateUri = String.format("%s://%s:%d%s", uri.getScheme() == null ? "https" : uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath() + "/zaas/validate/auth");
try {
restTemplate.exchange(zaasAuthValidateUri, HttpMethod.GET, null, String.class);
} catch (HttpClientErrorException.Conflict e) {
throw new ValidationException(e.getResponseBodyAsString(), ValidateAPIController.NON_CONFORMANT_KEY);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Error getting authentication support", e);
}
throw new ValidationException("Error validating the authentication support", ValidateAPIController.NO_METADATA_KEY);
}

}
return passedAuthenticationToken;
}

public static boolean supportsSSO(Map<String, String> metadata) {
if (metadata.containsKey(EurekaMetadataDefinition.AUTHENTICATION_SSO)) {
return metadata.get(EurekaMetadataDefinition.AUTHENTICATION_SSO).equals("true");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;

Expand Down Expand Up @@ -106,7 +106,7 @@ void checkValidJson() {
void whenServiceIdTooLong_thenNonconformant() {
when(messageService.createMessage(NON_CONFORMANT_KEY, "ThisWillBeRemoved")).thenReturn(NON_CONFORMANT_MESSAGE);
String testString = "qwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiop";
result = validateAPIController.checkConformance(testString, "dummy");
result = validateAPIController.checkConformance(testString, null);
assertNotNull(result.getBody());
assertTrue(result.getBody().contains("The serviceId is longer than 64 characters"));
}
Expand All @@ -115,7 +115,7 @@ void whenServiceIdTooLong_thenNonconformant() {
void whenServiceIdTooLongAndSymbols_thenNonconformant() {
when(messageService.createMessage(NON_CONFORMANT_KEY, "ThisWillBeRemoved")).thenReturn(NON_CONFORMANT_MESSAGE);
String testString = "qwertyuiopqwertyuiop--qwertyuiopqwertyuio-pqwertyuio-pqwertyuiopqwertyuiop";
result = validateAPIController.checkConformance(testString, "dummy");
result = validateAPIController.checkConformance(testString, null);
assertNotNull(result.getBody());
assertTrue(result.getBody().contains("The serviceId is longer than 64 characters"));
assertTrue(result.getBody().contains("The serviceId contains symbols or upper case letters"));
Expand All @@ -126,7 +126,7 @@ void whenServiceIdTooLongAndSymbols_thenNonconformant() {
@ValueSource(strings = {"test-test", "TEST", "Test"})
void whenServiceIdNonAlphaNumeric_thenNonconformant(String testString) {
when(messageService.createMessage(NON_CONFORMANT_KEY, "ThisWillBeRemoved")).thenReturn(NON_CONFORMANT_MESSAGE);
result = validateAPIController.checkConformance(testString, "dummy");
result = validateAPIController.checkConformance(testString, null);
assertNotNull(result.getBody());
assertTrue(result.getBody().contains("The serviceId contains symbols or upper case letters"));
}
Expand All @@ -135,7 +135,7 @@ void whenServiceIdNonAlphaNumeric_thenNonconformant(String testString) {
void notInvalidTextFormat() {
when(messageService.createMessage(WRONG_SERVICE_ID_KEY, "ThisWillBeRemoved")).thenReturn(WRONG_SERVICE_ID_MESSAGE);
String testString = "test";
result = validateAPIController.checkConformance(testString, "dummy");
result = validateAPIController.checkConformance(testString, null);
assertNotNull(result.getBody());
assertFalse(result.getBody().contains("Message service is requested to create a message with an invalid text format"));
}
Expand All @@ -162,7 +162,7 @@ void checkValidJson() {
void whenServiceNotOboarded_thenError() {
when(messageService.createMessage(WRONG_SERVICE_ID_KEY, "ThisWillBeRemoved")).thenReturn(WRONG_SERVICE_ID_MESSAGE);
String testString = "notonboarded";
result = validateAPIController.checkConformance(testString, "dummy");
result = validateAPIController.checkConformance(testString, null);
assertNotNull(result.getBody());
assertTrue(result.getBody().contains("The service is not registered"));
}
Expand All @@ -171,7 +171,7 @@ void whenServiceNotOboarded_thenError() {
void legacyWhenServiceNotOboarded_thenError() {
when(messageService.createMessage(WRONG_SERVICE_ID_KEY, "ThisWillBeRemoved")).thenReturn(WRONG_SERVICE_ID_MESSAGE);
String testString = "notonboarded";
result = validateAPIController.checkValidateLegacy(testString, "dummy");
result = validateAPIController.checkValidateLegacy(testString, null);
assertNotNull(result.getBody());
assertTrue(result.getBody().contains("The service is not registered"));

Expand Down Expand Up @@ -203,7 +203,7 @@ void whenEmpty_thenCorrectConformanceResponse() {
when(discoveryClient.getInstances(serviceId)).thenReturn(new ArrayList<>(Collections.singleton(serviceInstance)));
when(serviceInstance.getMetadata()).thenReturn(mockMetadata);
when(messageService.createMessage(NO_METADATA_KEY, "ThisWillBeRemoved")).thenReturn(NO_METADATA_MESSAGE);
result = validateAPIController.checkConformance(serviceId, "dummy");
result = validateAPIController.checkConformance(serviceId, null);
assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode());
}

Expand Down Expand Up @@ -261,11 +261,11 @@ void whenEverythingOk_thenOkResponse(String mockSwaggerFileLocation) throws IOEx

when(verificationOnboardService.getSwagger("a")).thenReturn(new String(Files.readAllBytes(mockSwaggerFile.getAbsoluteFile().toPath())));

when(verificationOnboardService.testEndpointsByCalling(any(), eq("dummy"))).thenReturn(new ArrayList<>());
when(verificationOnboardService.testEndpointsByCalling(any(), isNull())).thenReturn(new ArrayList<>());

try (MockedStatic<ValidatorFactory> validatorFactoryMockedStatic = mockStatic(ValidatorFactory.class)) {
validatorFactoryMockedStatic.when(() -> ValidatorFactory.parseSwagger(any(), any(), any(), any())).thenReturn(swaggerValidator);
result = validateAPIController.checkConformance(serviceId, "dummy");
result = validateAPIController.checkConformance(serviceId, null);
assertEquals(HttpStatus.OK, result.getStatusCode());
}
}
Expand All @@ -281,7 +281,7 @@ void whenBadMetadata_thenBadMetadataResponse() {
when(serviceInstance.getMetadata()).thenReturn(mockMetadata);
when(messageService.createMessage(NO_METADATA_KEY, "ThisWillBeRemoved")).thenReturn(NO_METADATA_MESSAGE);

result = validateAPIController.checkConformance(serviceId, "dummy");
result = validateAPIController.checkConformance(serviceId, null);
assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode());
assertNotNull(result.getBody());
assertTrue(result.getBody().contains("Cannot Retrieve MetaData"));
Expand Down
Loading

0 comments on commit 98b3394

Please sign in to comment.