diff --git a/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/cached/CachedProductFamilyService.java b/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/cached/CachedProductFamilyService.java index c7fdf7d7f0..ef6b1006b5 100644 --- a/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/cached/CachedProductFamilyService.java +++ b/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/cached/CachedProductFamilyService.java @@ -34,7 +34,6 @@ import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; -import static java.util.stream.Collectors.toList; import static org.zowe.apiml.constants.EurekaMetadataDefinition.*; /** @@ -113,7 +112,7 @@ public List getRecentlyUpdatedContainers() { " was updated recently"); } return isRecent; - }).collect(toList()); + }).toList(); } /** diff --git a/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/status/APIDocRetrievalService.java b/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/status/APIDocRetrievalService.java index 171b4f5e31..b26f46dcde 100644 --- a/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/status/APIDocRetrievalService.java +++ b/api-catalog-services/src/main/java/org/zowe/apiml/apicatalog/services/status/APIDocRetrievalService.java @@ -399,7 +399,7 @@ private InstanceInfo getInstanceInfo(String serviceId) { * @deprecated Added to support services which were on-boarded before 'apiml.apiInfo.swaggerUrl' parameter was * introduced. It will be removed when all services will be using the new configuration style. */ - @Deprecated + @Deprecated(forRemoval = false) private String createApiDocUrlFromRouting(InstanceInfo instanceInfo, RoutedServices routes) { String scheme; int port; diff --git a/api-catalog-ui/frontend/src/components/GraphQL/GraphQLUIApiml.jsx b/api-catalog-ui/frontend/src/components/GraphQL/GraphQLUIApiml.jsx index 401058bb39..b8f72951c2 100644 --- a/api-catalog-ui/frontend/src/components/GraphQL/GraphQLUIApiml.jsx +++ b/api-catalog-ui/frontend/src/components/GraphQL/GraphQLUIApiml.jsx @@ -78,7 +78,7 @@ export default function GraphQLUIApiml(props) { try { const introspectionQuery = getIntrospectionQuery(); const result = await fetcher({ query: introspectionQuery }); - if (result && result.data) { + if (result?.data) { const clientSchema = buildClientSchema(result.data); setSchema(clientSchema); } else { diff --git a/api-catalog-ui/frontend/src/components/ServiceTab/ServiceTab.jsx b/api-catalog-ui/frontend/src/components/ServiceTab/ServiceTab.jsx index 402f3bb9dc..3c4d05114b 100644 --- a/api-catalog-ui/frontend/src/components/ServiceTab/ServiceTab.jsx +++ b/api-catalog-ui/frontend/src/components/ServiceTab/ServiceTab.jsx @@ -7,7 +7,7 @@ * * Copyright Contributors to the Zowe Project. */ -import { Link, Typography, Tooltip, MenuItem, Select, Button } from '@material-ui/core'; +import { Button, Link, MenuItem, Select, Tooltip, Typography } from '@material-ui/core'; import { Component } from 'react'; import PropTypes from 'prop-types'; import Shield from '../ErrorBoundary/Shield/Shield'; @@ -142,7 +142,7 @@ export default class ServiceTab extends Component { if (!apis || typeof apis !== 'object') { return null; } - const apiKey = Object.keys(apis).find((key) => apis[key] && apis[key].graphqlUrl); + const apiKey = Object.keys(apis).find((key) => apis[key]?.graphqlUrl); return apiKey ? apis[apiKey].graphqlUrl : null; }; diff --git a/apiml-security-common/src/main/java/org/zowe/apiml/security/common/config/AuthConfigurationProperties.java b/apiml-security-common/src/main/java/org/zowe/apiml/security/common/config/AuthConfigurationProperties.java index 37e38ca5d2..f3bff3e7cf 100644 --- a/apiml-security-common/src/main/java/org/zowe/apiml/security/common/config/AuthConfigurationProperties.java +++ b/apiml-security-common/src/main/java/org/zowe/apiml/security/common/config/AuthConfigurationProperties.java @@ -104,8 +104,6 @@ public static class CookieProperties { private String cookieNamePAT = ApimlConstants.PAT_COOKIE_AUTH_NAME; private boolean cookieSecure = true; private String cookiePath = "/"; - @Deprecated(since = "Servlet 6.0", forRemoval = true) - private String cookieComment = "API Mediation Layer security token"; private Integer cookieMaxAge = null; private SameSiteCookies cookieSameSite = SameSiteCookies.STRICT; } diff --git a/apiml-security-common/src/main/java/org/zowe/apiml/security/common/login/SuccessfulLoginHandler.java b/apiml-security-common/src/main/java/org/zowe/apiml/security/common/login/SuccessfulLoginHandler.java index f0ff2c7ced..54618ebfc8 100644 --- a/apiml-security-common/src/main/java/org/zowe/apiml/security/common/login/SuccessfulLoginHandler.java +++ b/apiml-security-common/src/main/java/org/zowe/apiml/security/common/login/SuccessfulLoginHandler.java @@ -10,6 +10,8 @@ package org.zowe.apiml.security.common.login; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; @@ -19,9 +21,6 @@ import org.zowe.apiml.security.common.token.TokenAuthentication; import org.zowe.apiml.util.CookieUtil; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - /** * Handles the successful login */ @@ -59,7 +58,6 @@ private void setCookie(String token, HttpServletResponse response) { AuthConfigurationProperties.CookieProperties cp = authConfigurationProperties.getCookieProperties(); String cookieHeader = new CookieUtil.CookieHeaderBuilder(cp.getCookieName(), token) - .comment(cp.getCookieComment()) .path(cp.getCookiePath()) .sameSite(cp.getCookieSameSite().getValue()) .maxAge(cp.getCookieMaxAge()) diff --git a/discovery-service/src/test/java/org/zowe/apiml/discovery/staticdef/StaticApiRestControllerTest.java b/discovery-service/src/test/java/org/zowe/apiml/discovery/staticdef/StaticApiRestControllerTest.java index 5313ca9c80..aa3ffeb64e 100644 --- a/discovery-service/src/test/java/org/zowe/apiml/discovery/staticdef/StaticApiRestControllerTest.java +++ b/discovery-service/src/test/java/org/zowe/apiml/discovery/staticdef/StaticApiRestControllerTest.java @@ -20,10 +20,7 @@ import java.util.List; import static org.hamcrest.CoreMatchers.hasItem; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -55,7 +52,6 @@ public void setup() { @Test void listDefinitions() throws Exception { - String serviceName = "service"; String basicToken = "Basic " + Base64.getEncoder().encodeToString(CREDENTIALS.getBytes()); when(registrationService.getStaticInstances()).thenReturn(instancesInfo); diff --git a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/AuthEndpointConfig.java b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/AuthEndpointConfig.java index 9c03c45850..d27530195c 100644 --- a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/AuthEndpointConfig.java +++ b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/AuthEndpointConfig.java @@ -77,9 +77,9 @@ private WebClient createLoadBalanced(WebClient webClient, ReactiveLoadBalancer.F private WebClient.RequestBodySpec getWebclient(ServerRequest serverRequest, String path) { var sslInfo = serverRequest.exchange().getRequest().getSslInfo(); - var webClient = sslInfo == null ? this.webClient : this.webClientClientCert; + var client = sslInfo == null ? this.webClient : this.webClientClientCert; - var request = webClient + var request = client .method(serverRequest.method()) .uri("lb://zaas/zaas" + path) .headers(headers -> headers.addAll(serverRequest.headers().asHttpHeaders())) diff --git a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/RoutingConfig.java b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/RoutingConfig.java index 74a0630124..ca19ce5598 100644 --- a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/RoutingConfig.java +++ b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/RoutingConfig.java @@ -42,9 +42,9 @@ public List filters() { } if (!allowEncodedSlashes) { - var allowEncodedSlashes = new FilterDefinition(); - allowEncodedSlashes.setName("ForbidEncodedSlashesFilterFactory"); - filters.add(allowEncodedSlashes); + var encodedSlashesFilter = new FilterDefinition(); + encodedSlashesFilter.setName("ForbidEncodedSlashesFilterFactory"); + filters.add(encodedSlashesFilter); } var secureHeaders = new FilterDefinition(); diff --git a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/SwaggerConfig.java b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/SwaggerConfig.java index c9e834ad89..e6e4f37294 100644 --- a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/SwaggerConfig.java +++ b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/SwaggerConfig.java @@ -134,7 +134,7 @@ void updatePaths(OpenAPI openApi, String pathToMatch) { String download(URI uri) { return webClient - .get().uri(zaasUri) + .get().uri(uri) .retrieve() .bodyToMono(String.class).share().block(); } diff --git a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/oidc/ClientConfiguration.java b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/oidc/ClientConfiguration.java index 52a6d05ca4..02fed5d1dd 100644 --- a/gateway-service/src/main/java/org/zowe/apiml/gateway/config/oidc/ClientConfiguration.java +++ b/gateway-service/src/main/java/org/zowe/apiml/gateway/config/oidc/ClientConfiguration.java @@ -66,7 +66,7 @@ private void update(String id, Registration registration) { String scope = getSystemEnv(id, REGISTRATION_ENV_TYPE, "scope"); if (scope != null) { - registration.setScope(Arrays.asList(scope.split("[,]"))); + registration.setScope(Arrays.asList(scope.split(","))); } } diff --git a/gateway-service/src/main/java/org/zowe/apiml/gateway/controllers/GatewayExceptionHandler.java b/gateway-service/src/main/java/org/zowe/apiml/gateway/controllers/GatewayExceptionHandler.java index cf3e8c60c5..993a9cd8cc 100644 --- a/gateway-service/src/main/java/org/zowe/apiml/gateway/controllers/GatewayExceptionHandler.java +++ b/gateway-service/src/main/java/org/zowe/apiml/gateway/controllers/GatewayExceptionHandler.java @@ -79,7 +79,7 @@ public Mono setBodyResponse(ServerWebExchange exchange, int responseCode, return serverWebExchange.getResponse().writeWith(Flux.just(buffer)); } catch (JsonProcessingException e) { apimlLog.log("org.zowe.apiml.security.errorWritingResponse", e.getMessage()); - throw new RuntimeException(e); + return Mono.error(e); } } diff --git a/gateway-service/src/test/java/org/zowe/apiml/gateway/config/ConnectionsConfigTest.java b/gateway-service/src/test/java/org/zowe/apiml/gateway/config/ConnectionsConfigTest.java index 0971e131a9..b8b5e8eaf6 100644 --- a/gateway-service/src/test/java/org/zowe/apiml/gateway/config/ConnectionsConfigTest.java +++ b/gateway-service/src/test/java/org/zowe/apiml/gateway/config/ConnectionsConfigTest.java @@ -66,6 +66,8 @@ class KeyringFormatAndPasswordUpdate { ApplicationContext context; + ConnectionsConfig noContextConnectionsConfig = new ConnectionsConfig(null); + @BeforeEach void setup() { context = mock(ApplicationContext.class); @@ -76,30 +78,28 @@ void setup() { @Test void whenKeyringHasWrongFormatAndMissingPasswords_thenFixIt() { - ConnectionsConfig connectionsConfig = new ConnectionsConfig(null); - ReflectionTestUtils.setField(connectionsConfig, "keyStorePath", "safkeyring:///userId/ringId1"); - ReflectionTestUtils.setField(connectionsConfig, "trustStorePath", "safkeyring:////userId/ringId2"); - ReflectionTestUtils.setField(connectionsConfig, "context", context); - connectionsConfig.updateConfigParameters(); - - assertThat(ReflectionTestUtils.getField(connectionsConfig, "keyStorePath")).isEqualTo("safkeyring://userId/ringId1"); - assertThat(ReflectionTestUtils.getField(connectionsConfig, "trustStorePath")).isEqualTo("safkeyring://userId/ringId2"); - assertThat((char[]) ReflectionTestUtils.getField(connectionsConfig, "keyStorePassword")).isEqualTo("password".toCharArray()); - assertThat((char[]) ReflectionTestUtils.getField(connectionsConfig, "trustStorePassword")).isEqualTo("password".toCharArray()); + ReflectionTestUtils.setField(noContextConnectionsConfig, "keyStorePath", "safkeyring:///userId/ringId1"); + ReflectionTestUtils.setField(noContextConnectionsConfig, "trustStorePath", "safkeyring:////userId/ringId2"); + ReflectionTestUtils.setField(noContextConnectionsConfig, "context", context); + noContextConnectionsConfig.updateConfigParameters(); + + assertThat(ReflectionTestUtils.getField(noContextConnectionsConfig, "keyStorePath")).isEqualTo("safkeyring://userId/ringId1"); + assertThat(ReflectionTestUtils.getField(noContextConnectionsConfig, "trustStorePath")).isEqualTo("safkeyring://userId/ringId2"); + assertThat((char[]) ReflectionTestUtils.getField(noContextConnectionsConfig, "keyStorePassword")).isEqualTo("password".toCharArray()); + assertThat((char[]) ReflectionTestUtils.getField(noContextConnectionsConfig, "trustStorePassword")).isEqualTo("password".toCharArray()); } @Test void whenKeystore_thenDoNothing() { - ConnectionsConfig connectionsConfig = new ConnectionsConfig(null); - ReflectionTestUtils.setField(connectionsConfig, "keyStorePath", "/path1"); - ReflectionTestUtils.setField(connectionsConfig, "trustStorePath", "/path2"); - ReflectionTestUtils.setField(connectionsConfig, "context", context); - connectionsConfig.updateConfigParameters(); - - assertThat(ReflectionTestUtils.getField(connectionsConfig, "keyStorePath")).isEqualTo("/path1"); - assertThat(ReflectionTestUtils.getField(connectionsConfig, "trustStorePath")).isEqualTo("/path2"); - assertThat(ReflectionTestUtils.getField(connectionsConfig, "keyStorePassword")).isNull(); - assertThat(ReflectionTestUtils.getField(connectionsConfig, "trustStorePassword")).isNull(); + ReflectionTestUtils.setField(noContextConnectionsConfig, "keyStorePath", "/path1"); + ReflectionTestUtils.setField(noContextConnectionsConfig, "trustStorePath", "/path2"); + ReflectionTestUtils.setField(noContextConnectionsConfig, "context", context); + noContextConnectionsConfig.updateConfigParameters(); + + assertThat(ReflectionTestUtils.getField(noContextConnectionsConfig, "keyStorePath")).isEqualTo("/path1"); + assertThat(ReflectionTestUtils.getField(noContextConnectionsConfig, "trustStorePath")).isEqualTo("/path2"); + assertThat(ReflectionTestUtils.getField(noContextConnectionsConfig, "keyStorePassword")).isNull(); + assertThat(ReflectionTestUtils.getField(noContextConnectionsConfig, "trustStorePassword")).isNull(); } } } diff --git a/gateway-service/src/test/java/org/zowe/apiml/gateway/config/NettyRoutingFilterApimlTest.java b/gateway-service/src/test/java/org/zowe/apiml/gateway/config/NettyRoutingFilterApimlTest.java index 13307643f3..e8d1a8e0c5 100644 --- a/gateway-service/src/test/java/org/zowe/apiml/gateway/config/NettyRoutingFilterApimlTest.java +++ b/gateway-service/src/test/java/org/zowe/apiml/gateway/config/NettyRoutingFilterApimlTest.java @@ -82,10 +82,10 @@ class GetHttpClient { NettyRoutingFilterApiml nettyRoutingFilterApiml; private final Route ROUTE_NO_TIMEOUT = Route.async() - .id("1").uri("http://localhost/").predicate(serverWebExchange -> true) + .id("1").uri("http://localhost/").predicate(__ -> true) .build(); private final Route ROUTE_TIMEOUT = Route.async() - .id("2").uri("http://localhost/").predicate(serverWebExchange -> true).metadata(CONNECT_TIMEOUT_ATTR, "100") + .id("2").uri("http://localhost/").predicate(__ -> true).metadata(CONNECT_TIMEOUT_ATTR, "100") .build(); MockServerWebExchange serverWebExchange; diff --git a/gateway-service/src/test/java/org/zowe/apiml/gateway/controllers/CertificatesRestControllerTest.java b/gateway-service/src/test/java/org/zowe/apiml/gateway/controllers/CertificatesRestControllerTest.java index f02728d20f..ba1172a7e9 100644 --- a/gateway-service/src/test/java/org/zowe/apiml/gateway/controllers/CertificatesRestControllerTest.java +++ b/gateway-service/src/test/java/org/zowe/apiml/gateway/controllers/CertificatesRestControllerTest.java @@ -28,53 +28,57 @@ class CertificatesRestControllerTest { private static final String NO_CERTIFICATES = ""; private static final String SINGLE_CERTIFICATE = - "-----BEGIN CERTIFICATE-----\n" + - "MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL\n" + - "MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC\n" + - "VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx\n" + - "NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD\n" + - "TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu\n" + - "ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j\n" + - "V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj\n" + - "gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA\n" + - "FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE\n" + - "CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS\n" + - "BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE\n" + - "BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju\n" + - "Wm7DCfrPNGVwFWUQOmsPue9rZBgO\n" + - "-----END CERTIFICATE-----"; + """ + -----BEGIN CERTIFICATE----- + MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL + MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC + VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx + NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD + TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu + ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j + V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj + gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA + FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE + CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS + BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE + BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju + Wm7DCfrPNGVwFWUQOmsPue9rZBgO + -----END CERTIFICATE----- + """.stripIndent(); private static final String CERTIFICATE_CHAIN = - "-----BEGIN CERTIFICATE-----\n" + - "MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL\n" + - "MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC\n" + - "VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx\n" + - "NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD\n" + - "TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu\n" + - "ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j\n" + - "V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj\n" + - "gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA\n" + - "FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE\n" + - "CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS\n" + - "BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE\n" + - "BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju\n" + - "Wm7DCfrPNGVwFWUQOmsPue9rZBgO\n" + - "-----END CERTIFICATE-----\n" + - "-----BEGIN CERTIFICATE-----\n" + - "MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL\n" + - "MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC\n" + - "VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx\n" + - "NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD\n" + - "TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu\n" + - "ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j\n" + - "V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj\n" + - "gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA\n" + - "FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE\n" + - "CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS\n" + - "BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE\n" + - "BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju\n" + - "Wm7DCfrPNGVwFWUQOmsPue9rZBgO\n" + - "-----END CERTIFICATE-----"; + """ + -----BEGIN CERTIFICATE----- + MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL + MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC + VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx + NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD + TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu + ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j + V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj + gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA + FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE + CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS + BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE + BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju + Wm7DCfrPNGVwFWUQOmsPue9rZBgO + -----END CERTIFICATE----- + -----BEGIN CERTIFICATE----- + MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL + MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC + VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx + NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD + TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu + ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j + V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj + gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA + FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE + CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS + BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE + BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju + Wm7DCfrPNGVwFWUQOmsPue9rZBgO + -----END CERTIFICATE----- + """.stripIndent(); @Autowired WebTestClient webTestClient; diff --git a/gateway-service/src/test/java/org/zowe/apiml/gateway/service/CertificateChainServiceTest.java b/gateway-service/src/test/java/org/zowe/apiml/gateway/service/CertificateChainServiceTest.java index 9f0b0dc644..8765e1862f 100644 --- a/gateway-service/src/test/java/org/zowe/apiml/gateway/service/CertificateChainServiceTest.java +++ b/gateway-service/src/test/java/org/zowe/apiml/gateway/service/CertificateChainServiceTest.java @@ -35,59 +35,63 @@ class CertificateChainServiceTest { ConnectionsConfig connectionsConfig = new ConnectionsConfig(null); private static final String CERTIFICATE_1 = - "-----BEGIN CERTIFICATE-----\n" + - "MIIENzCCAx+gAwIBAgIEBUx4bjANBgkqhkiG9w0BAQsFADCBnjELMAkGA1UEBhMC\n" + - "Q1oxDzANBgNVBAgTBlByYWd1ZTEPMA0GA1UEBxMGUHJhZ3VlMRQwEgYDVQQKEwta\n" + - "b3dlIFNhbXBsZTEcMBoGA1UECxMTQVBJIE1lZGlhdGlvbiBMYXllcjE5MDcGA1UE\n" + - "AxMwWm93ZSBEZXZlbG9wbWVudCBJbnN0YW5jZXMgQ2VydGlmaWNhdGUgQXV0aG9y\n" + - "aXR5MB4XDTE5MDExMTEyMTIwN1oXDTI5MDEwODEyMTIwN1owejELMAkGA1UEBhMC\n" + - "Q1oxDzANBgNVBAgTBlByYWd1ZTEPMA0GA1UEBxMGUHJhZ3VlMRQwEgYDVQQKEwta\n" + - "b3dlIFNhbXBsZTEcMBoGA1UECxMTQVBJIE1lZGlhdGlvbiBMYXllcjEVMBMGA1UE\n" + - "AxMMWm93ZSBTZXJ2aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\n" + - "jo7rxDzO51tfSmqahMbY6lsXLO+/tXYk1ZcIufsh5L+UMs5StHlfSglbiRgWhfdJ\n" + - "DTZb9R760klXL7QRYwBcYn3yhdYTsTB0+RJddPlTQzxAx45xV7b+fCtsQqBFZk5a\n" + - "es/TduyHCHXQRl+iLos13isrl5LSB66ohKxMtflPBeqTM/ptNBbq72XqFCQIZClC\n" + - "lvMMYnxrW2FNfftxpLQbeFu3KN/8V4gcQoSUvE8YU8PYbVUnuhURActywrxHpke5\n" + - "q/tYQR8iDb6D1ZwLU8+/rTrnPbZq+O2DP7vRyBP9pHS/WNSxY1sTnz7gQ2OlUL+B\n" + - "EQLgRXRPc5ev1kwn0kVd8QIDAQABo4GfMIGcMB8GA1UdIwQYMBaAFPA6lVzMZhd6\n" + - "jkR4JClljOSWs0J1MB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAOBgNV\n" + - "HQ8BAf8EBAMCBPAwKwYDVR0RBCQwIoIVbG9jYWxob3N0LmxvY2FsZG9tYWluggls\n" + - "b2NhbGhvc3QwHQYDVR0OBBYEFJDw32hIl2AHqtLlFJtyVkrIlaGjMA0GCSqGSIb3\n" + - "DQEBCwUAA4IBAQAwO1TPIg5ebOiotTtJgj2wbyYFBfqljLrBMEfgP6h6ZOkj5fQI\n" + - "dZSLNmyY/PSk8IHUPE43QzEPV8Bd2zOwtDzbrnfvtuKLuLzPr+shih3gpUoSYGLU\n" + - "2miZZerk4AhpOrjIaUvKgcZ5QU7EQy32kQuKf9ldozxgnOzgN60G5z/qae7fYZxo\n" + - "SeV/nq8t7AkognCwHAKx8Iy418ucsfAuXQbursVWMi3KHrSENimZ+3fgCJ3ym0QT\n" + - "qwTpojppW5F9SWkJ4Q31l+oRROwIRKm44XSB8DVFnX/k8gzTPMylfQ+GwEyVHcyA\n" + - "R9zBnNhbbueFLlG9CBMeCHCyia6DUdIQlY5/\n" + - "-----END CERTIFICATE-----\n"; + """ + -----BEGIN CERTIFICATE----- + MIIENzCCAx+gAwIBAgIEBUx4bjANBgkqhkiG9w0BAQsFADCBnjELMAkGA1UEBhMC + Q1oxDzANBgNVBAgTBlByYWd1ZTEPMA0GA1UEBxMGUHJhZ3VlMRQwEgYDVQQKEwta + b3dlIFNhbXBsZTEcMBoGA1UECxMTQVBJIE1lZGlhdGlvbiBMYXllcjE5MDcGA1UE + AxMwWm93ZSBEZXZlbG9wbWVudCBJbnN0YW5jZXMgQ2VydGlmaWNhdGUgQXV0aG9y + aXR5MB4XDTE5MDExMTEyMTIwN1oXDTI5MDEwODEyMTIwN1owejELMAkGA1UEBhMC + Q1oxDzANBgNVBAgTBlByYWd1ZTEPMA0GA1UEBxMGUHJhZ3VlMRQwEgYDVQQKEwta + b3dlIFNhbXBsZTEcMBoGA1UECxMTQVBJIE1lZGlhdGlvbiBMYXllcjEVMBMGA1UE + AxMMWm93ZSBTZXJ2aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA + jo7rxDzO51tfSmqahMbY6lsXLO+/tXYk1ZcIufsh5L+UMs5StHlfSglbiRgWhfdJ + DTZb9R760klXL7QRYwBcYn3yhdYTsTB0+RJddPlTQzxAx45xV7b+fCtsQqBFZk5a + es/TduyHCHXQRl+iLos13isrl5LSB66ohKxMtflPBeqTM/ptNBbq72XqFCQIZClC + lvMMYnxrW2FNfftxpLQbeFu3KN/8V4gcQoSUvE8YU8PYbVUnuhURActywrxHpke5 + q/tYQR8iDb6D1ZwLU8+/rTrnPbZq+O2DP7vRyBP9pHS/WNSxY1sTnz7gQ2OlUL+B + EQLgRXRPc5ev1kwn0kVd8QIDAQABo4GfMIGcMB8GA1UdIwQYMBaAFPA6lVzMZhd6 + jkR4JClljOSWs0J1MB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAOBgNV + HQ8BAf8EBAMCBPAwKwYDVR0RBCQwIoIVbG9jYWxob3N0LmxvY2FsZG9tYWluggls + b2NhbGhvc3QwHQYDVR0OBBYEFJDw32hIl2AHqtLlFJtyVkrIlaGjMA0GCSqGSIb3 + DQEBCwUAA4IBAQAwO1TPIg5ebOiotTtJgj2wbyYFBfqljLrBMEfgP6h6ZOkj5fQI + dZSLNmyY/PSk8IHUPE43QzEPV8Bd2zOwtDzbrnfvtuKLuLzPr+shih3gpUoSYGLU + 2miZZerk4AhpOrjIaUvKgcZ5QU7EQy32kQuKf9ldozxgnOzgN60G5z/qae7fYZxo + SeV/nq8t7AkognCwHAKx8Iy418ucsfAuXQbursVWMi3KHrSENimZ+3fgCJ3ym0QT + qwTpojppW5F9SWkJ4Q31l+oRROwIRKm44XSB8DVFnX/k8gzTPMylfQ+GwEyVHcyA + R9zBnNhbbueFLlG9CBMeCHCyia6DUdIQlY5/ + -----END CERTIFICATE----- + """.stripIndent(); private static final String CERTIFICATE_2 = - "-----BEGIN CERTIFICATE-----\n" + - "MIID+zCCAuOgAwIBAgIEdkRICDANBgkqhkiG9w0BAQsFADCBnjELMAkGA1UEBhMC\n" + - "Q1oxDzANBgNVBAgTBlByYWd1ZTEPMA0GA1UEBxMGUHJhZ3VlMRQwEgYDVQQKEwta\n" + - "b3dlIFNhbXBsZTEcMBoGA1UECxMTQVBJIE1lZGlhdGlvbiBMYXllcjE5MDcGA1UE\n" + - "AxMwWm93ZSBEZXZlbG9wbWVudCBJbnN0YW5jZXMgQ2VydGlmaWNhdGUgQXV0aG9y\n" + - "aXR5MB4XDTE5MDExMTEyMTIwNVoXDTI5MDEwODEyMTIwNVowgZ4xCzAJBgNVBAYT\n" + - "AkNaMQ8wDQYDVQQIEwZQcmFndWUxDzANBgNVBAcTBlByYWd1ZTEUMBIGA1UEChML\n" + - "Wm93ZSBTYW1wbGUxHDAaBgNVBAsTE0FQSSBNZWRpYXRpb24gTGF5ZXIxOTA3BgNV\n" + - "BAMTMFpvd2UgRGV2ZWxvcG1lbnQgSW5zdGFuY2VzIENlcnRpZmljYXRlIEF1dGhv\n" + - "cml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALyotswfS+sLTmwO\n" + - "08ocbkNWPccRVWGWaP/LvfLe1USmhUOMO7E38ztTy8AJYBxrFTPr2lL3rXybRHCn\n" + - "Lscz0XNvkNll6Yef71ghaLbpe0V12Jygw4J9BAbYdVIsrP+brR3pijGVO/ECvJwD\n" + - "815ODsGU3Staw9HFlHO7dWss/TM2uz3Y6oVLObuhEWvAXiU3fW3PpFebRUlhLe5g\n" + - "yprGSZDFQAJpiqD7Nac5uZB53ETSPI+Cyku2E5CPx3qDJh9ueiHyaqmtbhBXjOue\n" + - "7rHU9F03zpldofqp4WDMnrl9ktzQDx+OHY5HI+gsaKV/MEX3YVrD+Rdc1GTc0JiI\n" + - "OS2VBCsCAwEAAaM/MD0wDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAgQwHQYD\n" + - "VR0OBBYEFPA6lVzMZhd6jkR4JClljOSWs0J1MA0GCSqGSIb3DQEBCwUAA4IBAQCt\n" + - "onZY1WkhTXmBxIl6EW/IDmcXZeYgucw590I7iVVXDi53oCM16AIM6pniqMP/iku5\n" + - "2MX2JqGD//eEnJDt6q+qA4htJSb7lswjbC90xLkGAKAuDsC2cKGaoQAeTh5ouP7C\n" + - "itN2+xVjZTfyAg3ZxmhXmVKVsv4rRpiAOYvX7R7ewNjpJkBeTQouind5rKtabzPD\n" + - "0nHKF0u/Y8FaEwv8zFRffsnl0/3nqfnT6l0mvekDP+LhIKZI9TwIJYkP9PGraR50\n" + - "HgUnKdoaJuPVQfbiMzISRqXygfTdmVnY9CEP9/W2S4NgaLXI6AkNLEcLNvz/CKJg\n" + - "TRqXQKkvunUCrHxi5oV+\n" + - "-----END CERTIFICATE-----\n"; - - private Certificate[] certificates = new Certificate[2]; + """ + -----BEGIN CERTIFICATE----- + MIID+zCCAuOgAwIBAgIEdkRICDANBgkqhkiG9w0BAQsFADCBnjELMAkGA1UEBhMC + Q1oxDzANBgNVBAgTBlByYWd1ZTEPMA0GA1UEBxMGUHJhZ3VlMRQwEgYDVQQKEwta + b3dlIFNhbXBsZTEcMBoGA1UECxMTQVBJIE1lZGlhdGlvbiBMYXllcjE5MDcGA1UE + AxMwWm93ZSBEZXZlbG9wbWVudCBJbnN0YW5jZXMgQ2VydGlmaWNhdGUgQXV0aG9y + aXR5MB4XDTE5MDExMTEyMTIwNVoXDTI5MDEwODEyMTIwNVowgZ4xCzAJBgNVBAYT + AkNaMQ8wDQYDVQQIEwZQcmFndWUxDzANBgNVBAcTBlByYWd1ZTEUMBIGA1UEChML + Wm93ZSBTYW1wbGUxHDAaBgNVBAsTE0FQSSBNZWRpYXRpb24gTGF5ZXIxOTA3BgNV + BAMTMFpvd2UgRGV2ZWxvcG1lbnQgSW5zdGFuY2VzIENlcnRpZmljYXRlIEF1dGhv + cml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALyotswfS+sLTmwO + 08ocbkNWPccRVWGWaP/LvfLe1USmhUOMO7E38ztTy8AJYBxrFTPr2lL3rXybRHCn + Lscz0XNvkNll6Yef71ghaLbpe0V12Jygw4J9BAbYdVIsrP+brR3pijGVO/ECvJwD + 815ODsGU3Staw9HFlHO7dWss/TM2uz3Y6oVLObuhEWvAXiU3fW3PpFebRUlhLe5g + yprGSZDFQAJpiqD7Nac5uZB53ETSPI+Cyku2E5CPx3qDJh9ueiHyaqmtbhBXjOue + 7rHU9F03zpldofqp4WDMnrl9ktzQDx+OHY5HI+gsaKV/MEX3YVrD+Rdc1GTc0JiI + OS2VBCsCAwEAAaM/MD0wDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAgQwHQYD + VR0OBBYEFPA6lVzMZhd6jkR4JClljOSWs0J1MA0GCSqGSIb3DQEBCwUAA4IBAQCt + onZY1WkhTXmBxIl6EW/IDmcXZeYgucw590I7iVVXDi53oCM16AIM6pniqMP/iku5 + 2MX2JqGD//eEnJDt6q+qA4htJSb7lswjbC90xLkGAKAuDsC2cKGaoQAeTh5ouP7C + itN2+xVjZTfyAg3ZxmhXmVKVsv4rRpiAOYvX7R7ewNjpJkBeTQouind5rKtabzPD + 0nHKF0u/Y8FaEwv8zFRffsnl0/3nqfnT6l0mvekDP+LhIKZI9TwIJYkP9PGraR50 + HgUnKdoaJuPVQfbiMzISRqXygfTdmVnY9CEP9/W2S4NgaLXI6AkNLEcLNvz/CKJg + TRqXQKkvunUCrHxi5oV+ + -----END CERTIFICATE----- + """; + + private final Certificate[] certificates = new Certificate[2]; @Nested class GivenValidCertificateChain { diff --git a/integration-tests/src/test/java/org/zowe/apiml/integration/graphql/BookControllerTest.java b/integration-tests/src/test/java/org/zowe/apiml/integration/graphql/BookControllerTest.java index 2447845040..052401db7c 100644 --- a/integration-tests/src/test/java/org/zowe/apiml/integration/graphql/BookControllerTest.java +++ b/integration-tests/src/test/java/org/zowe/apiml/integration/graphql/BookControllerTest.java @@ -46,7 +46,7 @@ private Book setUpBook() { @BeforeAll static void setUpTester() { String baseUrl = HttpRequestUtils.getUriFromGateway("/discoverableclient/api/v3/graphql").toString(); - SslContext sslContext = null; + SslContext sslContext; try { sslContext = SslContextBuilder .forClient() @@ -66,7 +66,7 @@ static void setUpTester() { } @Test - public void whenGetAllBooks_thenReturnAllBooks() throws SSLException { + public void whenGetAllBooks_thenReturnAllBooks() { String document = """ query { getAllBooks { @@ -86,7 +86,7 @@ public void whenGetAllBooks_thenReturnAllBooks() throws SSLException { } @Test - public void whenGetAllBooksWithWrongSchema_thenReturnException() throws SSLException { + public void whenGetAllBooksWithWrongSchema_thenReturnException() { String document = """ query { getAllBooks { @@ -95,18 +95,17 @@ public void whenGetAllBooksWithWrongSchema_thenReturnException() throws SSLExcep } """; - AssertionError thrown = assertThrows(AssertionError.class, () -> { + assertThrows(AssertionError.class, () -> tester.document(document) .execute() .path("getAllBooks") .entityList(Book.class) - .get(); - }); - assertNotNull(thrown); + .get() + ); } @Test - public void whenAddBook_thenReturnAddedBook() throws SSLException { + public void whenAddBook_thenReturnAddedBook() { Book expectedBook = setUpBook(); String addBookDocument = String.format(""" mutation { @@ -148,7 +147,7 @@ public void whenAddBook_thenReturnAddedBook() throws SSLException { } @Test - public void whenGetBookById_thenReturnMatchingBook() throws SSLException { + public void whenGetBookById_thenReturnMatchingBook() { Book expectedBook = setUpBook(); String addBookDocument = String.format(""" mutation { @@ -176,13 +175,11 @@ public void whenGetBookById_thenReturnMatchingBook() throws SSLException { .execute() .path("getBookById") .entity(Book.class) - .satisfies(book -> { - assertEquals(addedBookId, book.bookId); - }); + .satisfies(book -> assertEquals(addedBookId, book.bookId)); } @Test - public void whenGetBookByIdWithWrongId_thenBookNotFound() throws SSLException { + public void whenGetBookByIdWithWrongId_thenBookNotFound() { String id = "UnexistingId"; String getBookByIdDocument = String.format(""" query { @@ -201,7 +198,7 @@ public void whenGetBookByIdWithWrongId_thenBookNotFound() throws SSLException { } @Test - public void whenAddBookWithNullParameter_thenReturnException() throws SSLException { + public void whenAddBookWithNullParameter_thenReturnException() { Book expectedBook = setUpBook(); String addBookDocument = String.format(""" mutation { @@ -213,18 +210,17 @@ public void whenAddBookWithNullParameter_thenReturnException() throws SSLExcepti } """, expectedBook.pageCount, expectedBook.authorId ); - AssertionError thrown = assertThrows(AssertionError.class, () -> { + assertThrows(AssertionError.class, () -> tester.document(addBookDocument) .execute() .path("addBook") .entity(Book.class) - .get(); - }); - assertNotNull(thrown); + .get() + ); } @Test - public void whenUpdateBook_thenReturnUpdatedBook() throws SSLException { + public void whenUpdateBook_thenReturnUpdatedBook() { Book expectedBook = setUpBook(); String addBookDocument = String.format(""" mutation { @@ -262,7 +258,7 @@ public void whenUpdateBook_thenReturnUpdatedBook() throws SSLException { } @Test - public void whenUpdateUnknownBook_thenReturnException() throws SSLException { + public void whenUpdateUnknownBook_thenReturnException() { Book bookToUpdateBook = setUpBook(); bookToUpdateBook.bookId = "unknown-id"; String updateBookDocument = String.format(""" @@ -275,18 +271,17 @@ public void whenUpdateUnknownBook_thenReturnException() throws SSLException { } """, bookToUpdateBook.bookId, bookToUpdateBook.name, bookToUpdateBook.pageCount, bookToUpdateBook.authorId); - AssertionError thrown = assertThrows(AssertionError.class, () -> { + assertThrows(AssertionError.class, () -> tester.document(updateBookDocument) .execute() .path("updateBook") .entity(Book.class) - .get(); - }); - assertNotNull(thrown); + .get() + ); } @Test - public void whenDeleteBook_thenReturnDeletedBook() throws SSLException { + public void whenDeleteBook_thenReturnDeletedBook() { // add book which will be later deleted Book bookToDelete = setUpBook(); String addBookDocument = String.format(""" @@ -341,7 +336,7 @@ public void whenDeleteBook_thenReturnDeletedBook() throws SSLException { } @Test - public void whenDeleteUnknownBook_thenReturnException() throws SSLException { + public void whenDeleteUnknownBook_thenReturnException() { String unknownId = "unknown-id"; String deleteBookDocument = String.format(""" mutation { @@ -353,14 +348,13 @@ public void whenDeleteUnknownBook_thenReturnException() throws SSLException { } """, unknownId); - AssertionError thrown = assertThrows(AssertionError.class, () -> { + assertThrows(AssertionError.class, () -> tester.document(deleteBookDocument) .execute() .path("deleteBook") .entity(Book.class) - .get(); - }); - assertNotNull(thrown); + .get() + ); } @Data diff --git a/onboarding-enabler-micronaut/src/main/java/org/zowe/apiml/config/SslTypeConverter.java b/onboarding-enabler-micronaut/src/main/java/org/zowe/apiml/config/SslTypeConverter.java index 3503c8213c..7a05952ce3 100644 --- a/onboarding-enabler-micronaut/src/main/java/org/zowe/apiml/config/SslTypeConverter.java +++ b/onboarding-enabler-micronaut/src/main/java/org/zowe/apiml/config/SslTypeConverter.java @@ -13,7 +13,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.micronaut.core.convert.ConversionContext; import io.micronaut.core.convert.TypeConverter; -import jakarta.inject.Inject; import jakarta.inject.Singleton; import org.zowe.apiml.eurekaservice.client.config.Ssl; @@ -27,8 +26,11 @@ @Singleton public class SslTypeConverter implements TypeConverter, Ssl> { - @Inject - private ObjectMapper mapper; + private final ObjectMapper mapper; + + SslTypeConverter(ObjectMapper mapper) { + this.mapper = mapper; + } @Override public Optional convert(LinkedHashMap object, Class targetType, ConversionContext context) { diff --git a/security-service-client-spring/src/test/java/org/zowe/apiml/security/client/service/GatewaySecurityServiceTest.java b/security-service-client-spring/src/test/java/org/zowe/apiml/security/client/service/GatewaySecurityServiceTest.java index 458ab60679..2d3f69e269 100644 --- a/security-service-client-spring/src/test/java/org/zowe/apiml/security/client/service/GatewaySecurityServiceTest.java +++ b/security-service-client-spring/src/test/java/org/zowe/apiml/security/client/service/GatewaySecurityServiceTest.java @@ -67,7 +67,7 @@ class GatewaySecurityServiceTest { private AuthConfigurationProperties authConfigurationProperties; private GatewaySecurityService securityService; private String cookie; - private ObjectMapper objectMapper = new ObjectMapper(); + private final ObjectMapper objectMapper = new ObjectMapper(); private static final String MESSAGE_KEY_STRING = "messageKey\":\""; @BeforeEach @@ -139,7 +139,7 @@ void givenValidAuth_thenSuccessfulResponse() throws IOException { } @Test - void givenGatewayUnauthorized_thenThrowException() throws IOException { + void givenGatewayUnauthorized_thenThrowException() { String responseBody = MESSAGE_KEY_STRING + "org.zowe.apiml.security.query.invalidToken\""; HttpClientMockHelper.mockResponse(response, HttpStatus.SC_UNAUTHORIZED, responseBody); Exception exception = assertThrows(TokenNotValidException.class, () -> securityService.query("token")); @@ -160,14 +160,13 @@ class WhenHandleBadResponse { void setup() { uri = String.format("%s://%s%s", gatewayConfigProperties.getScheme(), gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayLoginEndpoint()); - //when(response.getCode()).thenReturn(HttpStatus.UNAUTHORIZED.value()); } @Nested class ThenHandleAuthGeneralError { @Test - void givenInvalidMessageKey() throws IOException { + void givenInvalidMessageKey() { String errorMessage = MESSAGE_KEY_STRING + "badKey\""; HttpClientMockHelper.mockResponse(response, HttpStatus.SC_UNAUTHORIZED, errorMessage); assertThrows(BadCredentialsException.class, () -> securityService.login(USERNAME, PASSWORD, null)); @@ -175,14 +174,14 @@ void givenInvalidMessageKey() throws IOException { } @Test - void givenGatewayUnauthorized_thenThrowException() throws IOException { + void givenGatewayUnauthorized_thenThrowException() { HttpClientMockHelper.mockResponse(response, HttpStatus.SC_UNAUTHORIZED, "message"); Exception exception = assertThrows(BadCredentialsException.class, () -> securityService.login(USERNAME, PASSWORD, null)); assertEquals("Invalid Credentials", exception.getMessage()); } @Test - void givenValidMessageKey_thenHandleErrorTypeForThatMessageKey() throws IOException { + void givenValidMessageKey_thenHandleErrorTypeForThatMessageKey() { String errorMessage = MESSAGE_KEY_STRING + "org.zowe.apiml.security.login.invalidCredentials\""; HttpClientMockHelper.mockResponse(response, HttpStatus.SC_UNAUTHORIZED, errorMessage); assertThrows(BadCredentialsException.class, () -> securityService.login(USERNAME, PASSWORD, null)); diff --git a/zaas-client/src/main/java/org/zowe/apiml/zaasclient/service/ZaasClient.java b/zaas-client/src/main/java/org/zowe/apiml/zaasclient/service/ZaasClient.java index e4d59aa536..3aaa3fb669 100644 --- a/zaas-client/src/main/java/org/zowe/apiml/zaasclient/service/ZaasClient.java +++ b/zaas-client/src/main/java/org/zowe/apiml/zaasclient/service/ZaasClient.java @@ -33,7 +33,7 @@ public interface ZaasClient { * * @deprecated recommended to switch to {@link #login(String, char[], char[])} to handle cleaning up of passwords in memory */ - @Deprecated + @Deprecated(forRemoval = false) String login(String userId, String password, String newPassword) throws ZaasClientException; /** @@ -47,7 +47,7 @@ public interface ZaasClient { * * @deprecated recommended to switch to {@link #login(String, char[])} to handle cleaning up of passwords in memory */ - @Deprecated + @Deprecated(forRemoval = false) String login(String userId, String password) throws ZaasClientException; /** diff --git a/zaas-client/src/test/java/org/zowe/apiml/zaasclient/service/internal/ZaasClientImplHttpsTests.java b/zaas-client/src/test/java/org/zowe/apiml/zaasclient/service/internal/ZaasClientImplHttpsTests.java index 3034260942..7beebec85a 100644 --- a/zaas-client/src/test/java/org/zowe/apiml/zaasclient/service/internal/ZaasClientImplHttpsTests.java +++ b/zaas-client/src/test/java/org/zowe/apiml/zaasclient/service/internal/ZaasClientImplHttpsTests.java @@ -191,10 +191,10 @@ private void assertThatExceptionContainValidCode(ZaasClientException zce, ZaasCl void testLoginWithCredentials_ValidUserName_ValidPassword() throws ZaasClientException { prepareResponse(HttpStatus.SC_NO_CONTENT, true); - String token = tokenService.login(VALID_USER, VALID_PASSWORD); - assertNotNull(token, "null Token obtained"); - assertNotEquals(EMPTY_STRING, token, "Empty Token obtained"); - assertEquals("token", token, "Token Mismatch"); + String authToken = tokenService.login(VALID_USER, VALID_PASSWORD); + assertNotNull(authToken, "null Token obtained"); + assertNotEquals(EMPTY_STRING, authToken, "Empty Token obtained"); + assertEquals("token", authToken, "Token Mismatch"); } @Test @@ -206,10 +206,10 @@ void testLoginWithCredentials_ValidUserName_ValidPassword_multipleResponseCookie when(header.getValue()).thenReturn("someCookie=cookieValue"); when(tokenCookieHeader.getValue()).thenReturn("apimlAuthenticationToken=token"); - String token = tokenService.login(VALID_USER, VALID_PASSWORD); - assertNotNull(token, "null Token obtained"); - assertNotEquals(EMPTY_STRING, token, "Empty Token obtained"); - assertEquals("token", token, "Token Mismatch"); + String authToken = tokenService.login(VALID_USER, VALID_PASSWORD); + assertNotNull(authToken, "null Token obtained"); + assertNotEquals(EMPTY_STRING, authToken, "Empty Token obtained"); + assertEquals("token", authToken, "Token Mismatch"); } private static Stream provideInvalidUsernamePassword() { @@ -255,10 +255,10 @@ void testLoginWithCredentials_UnexpectedException() { @Test void testLoginWithAuthHeader_ValidUserName_ValidPassword() throws ZaasClientException { prepareResponse(HttpStatus.SC_NO_CONTENT, true); - String token = tokenService.login(getAuthHeader(VALID_USER, VALID_PASSWORD)); - assertNotNull(token, "null Token obtained"); - assertNotEquals(EMPTY_STRING, token, "Empty Token obtained"); - assertEquals("token", token, "Token Mismatch"); + String authToken = tokenService.login(getAuthHeader(VALID_USER, VALID_PASSWORD)); + assertNotNull(authToken, "null Token obtained"); + assertNotEquals(EMPTY_STRING, authToken, "Empty Token obtained"); + assertEquals("token", authToken, "Token Mismatch"); } private static Stream provideInvalidAuthHeaders() { @@ -352,8 +352,8 @@ void testPassTicketWithToken_ValidToken_ValidPassTicket() throws Exception { @Test void givenValidToken_whenLogout_thenSuccess() throws ZaasClientException { prepareResponse(HttpStatus.SC_NO_CONTENT, true); - String token = tokenService.login(getAuthHeader(VALID_USER, VALID_PASSWORD)); - assertDoesNotThrow(() -> tokenService.logout(token)); + String authToken = tokenService.login(getAuthHeader(VALID_USER, VALID_PASSWORD)); + assertDoesNotThrow(() -> tokenService.logout(authToken)); } @Test @@ -368,9 +368,9 @@ void givenInvalidToken_whenLogout_thenThrowException() { @Test void givenValidTokenInBearer_whenLogout_thenSuccess() throws ZaasClientException { prepareResponse(HttpStatus.SC_NO_CONTENT, true); - String token = tokenService.login(getAuthHeader(VALID_USER, VALID_PASSWORD)); - token = "Bearer " + token; - String finalToken = token; + String authToken = tokenService.login(getAuthHeader(VALID_USER, VALID_PASSWORD)); + authToken = "Bearer " + authToken; + String finalToken = authToken; assertDoesNotThrow(() -> tokenService.logout(finalToken)); } diff --git a/zaas-service/src/main/java/org/zowe/apiml/zaas/cache/CachingServiceClient.java b/zaas-service/src/main/java/org/zowe/apiml/zaas/cache/CachingServiceClient.java index 818ad2247d..effa6f0fa9 100644 --- a/zaas-service/src/main/java/org/zowe/apiml/zaas/cache/CachingServiceClient.java +++ b/zaas-service/src/main/java/org/zowe/apiml/zaas/cache/CachingServiceClient.java @@ -106,7 +106,7 @@ public Map> readAllMaps() throws CachingServiceClien if (response.getBody() != null && !response.getBody().isEmpty()) { //NOSONAR tests return null return response.getBody(); } - return null; + return Map.of(); } else { throw new CachingServiceClientException("Unable to read all key-value maps from cache list, caused by response from caching service is null or has no body"); } diff --git a/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/InternalServerErrorController.java b/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/InternalServerErrorController.java index 8c77342c2a..0568bfd3e9 100644 --- a/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/InternalServerErrorController.java +++ b/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/InternalServerErrorController.java @@ -17,9 +17,8 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; import org.zowe.apiml.message.api.ApiMessageView; import org.zowe.apiml.message.core.Message; import org.zowe.apiml.message.core.MessageService; @@ -34,7 +33,7 @@ /** * Handles errors in REST API processing. */ -@Controller +@RestController @Order(Ordered.HIGHEST_PRECEDENCE) @Primary public class InternalServerErrorController implements ApimlErrorController { @@ -64,7 +63,6 @@ public String getErrorPath() { */ @SuppressWarnings("squid:S3752") @RequestMapping(value = ERROR_ENDPOINT, produces = "application/json") - @ResponseBody public ResponseEntity error(HttpServletRequest request) { final Throwable exc = (Throwable) request.getAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION); diff --git a/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/NotFoundErrorController.java b/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/NotFoundErrorController.java index 453d940a26..63919e86d4 100644 --- a/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/NotFoundErrorController.java +++ b/zaas-service/src/main/java/org/zowe/apiml/zaas/error/controllers/NotFoundErrorController.java @@ -16,9 +16,8 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; import org.zowe.apiml.message.api.ApiMessageView; import org.zowe.apiml.message.core.Message; import org.zowe.apiml.message.core.MessageService; @@ -28,7 +27,7 @@ /** * Not found endpoint controller */ -@Controller +@RestController @RequiredArgsConstructor @Order(Ordered.HIGHEST_PRECEDENCE) public class NotFoundErrorController implements ApimlErrorController { @@ -48,7 +47,6 @@ public String getErrorPath() { * @return Http response entity */ @GetMapping(value = NOT_FOUND_ENDPOINT, produces = "application/json") - @ResponseBody public ResponseEntity notFound400HttpResponse(HttpServletRequest request) { Message message = messageService.createMessage("org.zowe.apiml.common.endPointNotFound", ErrorUtils.getForwardUri(request)); diff --git a/zaas-service/src/main/java/org/zowe/apiml/zaas/security/mapping/ExternalMapper.java b/zaas-service/src/main/java/org/zowe/apiml/zaas/security/mapping/ExternalMapper.java index 9cc5f36edf..937ad55885 100644 --- a/zaas-service/src/main/java/org/zowe/apiml/zaas/security/mapping/ExternalMapper.java +++ b/zaas-service/src/main/java/org/zowe/apiml/zaas/security/mapping/ExternalMapper.java @@ -20,7 +20,6 @@ import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.message.BasicHeader; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -45,7 +44,7 @@ public abstract class ExternalMapper { private final String mapperUrl; private final String mapperUser; - @Autowired + @Qualifier("secureHttpClientWithoutKeystore") private final CloseableHttpClient secureHttpClientWithoutKeystore; private final TokenCreationService tokenCreationService; diff --git a/zaas-service/src/main/java/org/zowe/apiml/zaas/security/refresh/SuccessfulRefreshHandler.java b/zaas-service/src/main/java/org/zowe/apiml/zaas/security/refresh/SuccessfulRefreshHandler.java index 1a34d81853..30cadee83c 100644 --- a/zaas-service/src/main/java/org/zowe/apiml/zaas/security/refresh/SuccessfulRefreshHandler.java +++ b/zaas-service/src/main/java/org/zowe/apiml/zaas/security/refresh/SuccessfulRefreshHandler.java @@ -10,20 +10,20 @@ package org.zowe.apiml.zaas.security.refresh; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; -import org.zowe.apiml.zaas.security.service.AuthenticationService; -import org.zowe.apiml.zaas.security.service.TokenCreationService; import org.zowe.apiml.security.common.config.AuthConfigurationProperties; import org.zowe.apiml.security.common.token.TokenAuthentication; import org.zowe.apiml.util.CookieUtil; +import org.zowe.apiml.zaas.security.service.AuthenticationService; +import org.zowe.apiml.zaas.security.service.TokenCreationService; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; @@ -55,7 +55,6 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo private void setCookie(String token, HttpServletResponse response) { AuthConfigurationProperties.CookieProperties cp = authConfigurationProperties.getCookieProperties(); String cookieHeader = new CookieUtil.CookieHeaderBuilder(cp.getCookieName(), token) - .comment(cp.getCookieComment()) .path(cp.getCookiePath()) .sameSite(cp.getCookieSameSite().getValue()) .maxAge(cp.getCookieMaxAge()) diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/cache/CachingServiceClientTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/cache/CachingServiceClientTest.java index 656025c819..9bcaa1f7d3 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/cache/CachingServiceClientTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/cache/CachingServiceClientTest.java @@ -162,7 +162,7 @@ void whenClientReturnsEmptyBody_thenReturnNull() throws CachingServiceClientExce when(response.getBody()).thenReturn(responseBody); when(response.getStatusCode()).thenReturn(HttpStatus.OK); Map> parsedResponseBody = underTest.readAllMaps(); - assertNull(parsedResponseBody); + assertTrue(parsedResponseBody.isEmpty()); } @Test @@ -176,7 +176,7 @@ void whenResponseBodyIsNull_thenReturnNull() throws CachingServiceClientExceptio when(response.getBody()).thenReturn(null); when(response.getStatusCode()).thenReturn(HttpStatus.OK); Map> parsedResponseBody = underTest.readAllMaps(); - assertNull(parsedResponseBody); + assertTrue(parsedResponseBody.isEmpty()); } } diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/controllers/SafResourceAccessControllerTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/controllers/SafResourceAccessControllerTest.java index dd0c87719d..f14492c918 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/controllers/SafResourceAccessControllerTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/controllers/SafResourceAccessControllerTest.java @@ -36,20 +36,27 @@ class SafResourceAccessControllerTest { private MockMvc mockMvc; - private SafResourceAccessVerifying safResourceAccessVerifying = mock(SafResourceAccessVerifying.class); + private final SafResourceAccessVerifying safResourceAccessVerifying = mock(SafResourceAccessVerifying.class); MessageService messageService = new YamlMessageService("/zaas-messages.yml"); - private final String validRequestBody = "{\n" + - "\t\"resourceClass\": \"ZOWE\",\n" + - "\t\"resourceName\": \"APIML.SERVICES\",\n" + - "\t\"accessLevel\": \"READ\"\n" + - "}"; + private final String validRequestBody = + """ + { + "resourceClass": "ZOWE", + "resourceName": "APIML.SERVICES", + "accessLevel": "READ" + } + """; - private final String invalidRequestBody = "{\n" + - "\t\"resourceClass\": \"ZOWE\",\n" + - "\t\"resourceName\": \"APIML.SERVICES\",\n" + - "\t\"accessLevel\": \"WIPE\"\n" + - "}"; + private final String invalidRequestBody = + """ + { + "resourceClass": "ZOWE", + "resourceClass": "ZOWE" + "resourceName": "APIML.SERVICES" + "accessLevel": "WIPE" + } + """; @BeforeEach void setUp() { diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/mapping/NativeMapperTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/mapping/NativeMapperTest.java index 267a26beec..5a71cc5e03 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/mapping/NativeMapperTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/mapping/NativeMapperTest.java @@ -59,10 +59,12 @@ static class MockUserMapper extends UserMapper { public MockUserMapper() { } + @Override public CertificateResponse getUserIDForCertificate(byte[] var1) { return new CertificateResponse(MF_USER, 0, 0, 0); } + @Override public MapperResponse getUserIDForDN(String var1, String var2) { return new MapperResponse(MF_USER, 0, 0, 0, 0); } diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/query/SuccessfulQueryHandlerTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/query/SuccessfulQueryHandlerTest.java index 2e5972814e..00bf4bda41 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/query/SuccessfulQueryHandlerTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/query/SuccessfulQueryHandlerTest.java @@ -98,17 +98,17 @@ void setup() { authenticationService, tokenCreationService, new ArrayList<>()); - AuthenticationService authenticationService = new AuthenticationService( + AuthenticationService authService = new AuthenticationService( applicationContext, authConfigurationProperties, jwtSecurityInitializer, zosmfService, eurekaClient, restTemplate, cacheManager, new CacheUtils() ); when(jwtSecurityInitializer.getSignatureAlgorithm()).thenReturn(algorithm); when(jwtSecurityInitializer.getJwtSecret()).thenReturn(privateKey); - jwtToken = authenticationService.createJwtToken(USER, DOMAIN, LTPA); + jwtToken = authService.createJwtToken(USER, DOMAIN, LTPA); ObjectMapper mapper = new ObjectMapper(); - successfulQueryHandler = new SuccessfulQueryHandler(mapper, authenticationService); + successfulQueryHandler = new SuccessfulQueryHandler(mapper, authService); } @Test diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/JwtAuthSourceServiceTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/JwtAuthSourceServiceTest.java index 5a82af24df..9e51393fe6 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/JwtAuthSourceServiceTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/JwtAuthSourceServiceTest.java @@ -10,21 +10,21 @@ package org.zowe.apiml.zaas.security.service.schema.source; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.zowe.apiml.zaas.security.service.AuthenticationService; -import org.zowe.apiml.zaas.security.service.schema.source.AuthSource.Origin; -import org.zowe.apiml.zaas.security.service.schema.source.AuthSource.Parsed; import org.zowe.apiml.security.common.token.QueryResponse; import org.zowe.apiml.security.common.token.QueryResponse.Source; import org.zowe.apiml.security.common.token.TokenAuthentication; import org.zowe.apiml.security.common.token.TokenExpireException; import org.zowe.apiml.security.common.token.TokenNotValidException; +import org.zowe.apiml.zaas.security.service.AuthenticationService; +import org.zowe.apiml.zaas.security.service.schema.source.AuthSource.Origin; +import org.zowe.apiml.zaas.security.service.schema.source.AuthSource.Parsed; -import jakarta.servlet.http.HttpServletRequest; import java.util.Collections; import java.util.Date; import java.util.Optional; @@ -45,13 +45,13 @@ class JwtAuthSourceServiceTest { private JwtAuthSourceService serviceUnderTest; private final String token = "jwtToken"; - private JwtAuthSource authSource; + private JwtAuthSource jwtAuthSource; private TokenAuthentication tokenAuthentication; private Parsed expectedParsedSource; @BeforeEach public void setup() { - authSource = new JwtAuthSource("jwtToken"); + jwtAuthSource = new JwtAuthSource("jwtToken"); tokenAuthentication = TokenAuthentication.createAuthenticated("user", token); expectedParsedSource = new ParsedTokenAuthSource("user", new Date(111), new Date(222), Origin.ZOSMF); } @@ -65,7 +65,7 @@ void givenZosmfTokenInRequest_thenAuthSourceIsPresent() { verify(authenticationService, times(1)).getJwtTokenFromRequest(request); Assertions.assertTrue(authSource.isPresent()); - Assertions.assertTrue(authSource.get() instanceof JwtAuthSource); + Assertions.assertInstanceOf(JwtAuthSource.class, authSource.get()); Assertions.assertEquals(token, authSource.get().getRawSource()); } @@ -78,7 +78,7 @@ void givenZoweTokenInRequest_thenAuthSourceIsPresent() { verify(authenticationService, times(1)).getJwtTokenFromRequest(request); Assertions.assertTrue(authSource.isPresent()); - Assertions.assertTrue(authSource.get() instanceof JwtAuthSource); + Assertions.assertInstanceOf(JwtAuthSource.class, authSource.get()); Assertions.assertEquals(token, authSource.get().getRawSource()); } @@ -105,11 +105,11 @@ void givenNoTokenInRequest_thenAuthSourceIsPresent() { @Test void givenInvalidAuthSource_thenAuthSourceIsInvalid() { - TokenAuthentication tokenAuthentication = new TokenAuthentication("user"); - tokenAuthentication.setAuthenticated(false); - when(authenticationService.validateJwtToken(anyString())).thenReturn(tokenAuthentication); + TokenAuthentication tokenAuth = new TokenAuthentication("user"); + tokenAuth.setAuthenticated(false); + when(authenticationService.validateJwtToken(anyString())).thenReturn(tokenAuth); - Assertions.assertFalse(serviceUnderTest.isValid(authSource)); + Assertions.assertFalse(serviceUnderTest.isValid(jwtAuthSource)); verify(authenticationService, times(1)).validateJwtToken(token); } @@ -190,7 +190,7 @@ class GivenValidAuthSource { void thenIsValid() { when(authenticationService.validateJwtToken(anyString())).thenReturn(tokenAuthentication); - Assertions.assertTrue(serviceUnderTest.isValid(authSource)); + Assertions.assertTrue(serviceUnderTest.isValid(jwtAuthSource)); verify(authenticationService, times(1)).validateJwtToken(token); } @@ -198,7 +198,7 @@ void thenIsValid() { void thenParseCorrectly() { when(authenticationService.parseJwtToken(anyString())).thenReturn(new QueryResponse("domain", "user", new Date(111), new Date(222), "issuer", Collections.emptyList(), Source.ZOSMF)); - Parsed parsedSource = serviceUnderTest.parse(authSource); + Parsed parsedSource = serviceUnderTest.parse(jwtAuthSource); verify(authenticationService, times(1)).parseJwtToken(token); Assertions.assertNotNull(parsedSource); @@ -210,7 +210,7 @@ void thenLtpaGenerated() { String ltpa = "ltpaToken"; when(authenticationService.getLtpaTokenWithValidation(anyString())).thenReturn(ltpa); - Assertions.assertEquals(ltpa, serviceUnderTest.getLtpaToken(authSource)); + Assertions.assertEquals(ltpa, serviceUnderTest.getLtpaToken(jwtAuthSource)); verify(authenticationService, times(1)).getLtpaTokenWithValidation(token); } } @@ -223,7 +223,7 @@ class GivenTokenNotValidException { void whenIsValid_thenThrow() { when(authenticationService.validateJwtToken(anyString())).thenThrow(exception); - assertThrows(TokenNotValidException.class, () -> serviceUnderTest.isValid(authSource)); + assertThrows(TokenNotValidException.class, () -> serviceUnderTest.isValid(jwtAuthSource)); verify(authenticationService, times(1)).validateJwtToken(token); } @@ -231,7 +231,7 @@ void whenIsValid_thenThrow() { void whenParse_thenThrow() { when(authenticationService.parseJwtToken(anyString())).thenThrow(exception); - assertThrows(TokenNotValidException.class, () -> serviceUnderTest.parse(authSource)); + assertThrows(TokenNotValidException.class, () -> serviceUnderTest.parse(jwtAuthSource)); verify(authenticationService, times(1)).parseJwtToken(token); } @@ -239,7 +239,7 @@ void whenParse_thenThrow() { void whenGetLtpa_thenThrow() { when(authenticationService.getLtpaTokenWithValidation(anyString())).thenThrow(exception); - assertThrows(TokenNotValidException.class, () -> serviceUnderTest.getLtpaToken(authSource)); + assertThrows(TokenNotValidException.class, () -> serviceUnderTest.getLtpaToken(jwtAuthSource)); verify(authenticationService, times(1)).getLtpaTokenWithValidation(token); } @@ -261,7 +261,7 @@ class GivenTokenExpireException { void whenIsValid_thenThrow() { when(authenticationService.validateJwtToken(anyString())).thenThrow(exception); - assertThrows(TokenExpireException.class, () -> serviceUnderTest.isValid(authSource)); + assertThrows(TokenExpireException.class, () -> serviceUnderTest.isValid(jwtAuthSource)); verify(authenticationService, times(1)).validateJwtToken("jwtToken"); } @@ -269,7 +269,7 @@ void whenIsValid_thenThrow() { void whenParse_thenThrow() { when(authenticationService.parseJwtToken(anyString())).thenThrow(exception); - assertThrows(TokenExpireException.class, () -> serviceUnderTest.parse(authSource)); + assertThrows(TokenExpireException.class, () -> serviceUnderTest.parse(jwtAuthSource)); verify(authenticationService, times(1)).parseJwtToken(token); } @@ -277,7 +277,7 @@ void whenParse_thenThrow() { void whenGetLtpa_thenThrow() { when(authenticationService.getLtpaTokenWithValidation(anyString())).thenThrow(exception); - assertThrows(TokenExpireException.class, () -> serviceUnderTest.getLtpaToken(authSource)); + assertThrows(TokenExpireException.class, () -> serviceUnderTest.getLtpaToken(jwtAuthSource)); verify(authenticationService, times(1)).getLtpaTokenWithValidation(token); } diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/PATAuthSourceServiceTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/PATAuthSourceServiceTest.java index 8e4da12463..f4dfb878a4 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/PATAuthSourceServiceTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/schema/source/PATAuthSourceServiceTest.java @@ -55,7 +55,7 @@ void setUp() { @Test void returnPATSourceMapper() { - assertTrue(patAuthSourceService.getMapper().apply("token") instanceof PATAuthSource); + assertInstanceOf(PATAuthSource.class, patAuthSourceService.getMapper().apply("token")); } @Nested @@ -115,7 +115,6 @@ class GivenInvalidTokenTest { @Test void whenExceptionIsThrown_thenReturnTokenInvalid() { String serviceId = "service3"; - //when(context.get(SERVICE_ID_KEY)).thenReturn(serviceId); when(tokenProvider.isValidForScopes(TOKEN, serviceId)).thenThrow(new RuntimeException()); PATAuthSource authSource = new PATAuthSource(TOKEN); diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/token/ApimlAccessTokenProviderTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/token/ApimlAccessTokenProviderTest.java index 51da646481..3ee1a4e086 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/token/ApimlAccessTokenProviderTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/token/ApimlAccessTokenProviderTest.java @@ -22,11 +22,11 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.zowe.apiml.models.AccessTokenContainer; +import org.zowe.apiml.security.common.token.QueryResponse; import org.zowe.apiml.zaas.cache.CachingServiceClient; import org.zowe.apiml.zaas.cache.CachingServiceClientException; import org.zowe.apiml.zaas.security.service.AuthenticationService; -import org.zowe.apiml.models.AccessTokenContainer; -import org.zowe.apiml.security.common.token.QueryResponse; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; @@ -34,9 +34,7 @@ import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; class ApimlAccessTokenProviderTest { @@ -47,9 +45,9 @@ class ApimlAccessTokenProviderTest { private static String SCOPED_TOKEN; private static String TOKEN_WITHOUT_SCOPES; - Date issued = new Date(System.currentTimeMillis() - 100000L); - QueryResponse queryResponseTokenWithScopes = new QueryResponse(null, "user", issued, new Date(), "issuer", Arrays.asList("gateway", "discovery"), QueryResponse.Source.ZOWE_PAT); - QueryResponse queryResponseWithoutScopes = new QueryResponse(null, "user", issued, new Date(), "issuer", Collections.emptyList(), QueryResponse.Source.ZOWE_PAT); + Date issuedDate = new Date(System.currentTimeMillis() - 100000L); + QueryResponse queryResponseTokenWithScopes = new QueryResponse(null, "user", issuedDate, new Date(), "issuer", Arrays.asList("gateway", "discovery"), QueryResponse.Source.ZOWE_PAT); + QueryResponse queryResponseWithoutScopes = new QueryResponse(null, "user", issuedDate, new Date(), "issuer", Collections.emptyList(), QueryResponse.Source.ZOWE_PAT); @BeforeEach void setup() throws CachingServiceClientException,SecureTokenInitializationException { @@ -188,6 +186,7 @@ void givenTokenWithUserIdMatchingRule_returnInvalidated() { when(cachingServiceClient.readAllMaps()).thenReturn(cacheMap); assertTrue(accessTokenProvider.isInvalidated(TOKEN_WITHOUT_SCOPES)); } + @Test void givenTokenWithScopeMatchingRule_returnInvalidated() { String serviceId = accessTokenProvider.getHash("service"); diff --git a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/zosmf/ZosmfServiceTest.java b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/zosmf/ZosmfServiceTest.java index 1edf7081cf..2b068692f6 100644 --- a/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/zosmf/ZosmfServiceTest.java +++ b/zaas-service/src/test/java/org/zowe/apiml/zaas/security/service/zosmf/ZosmfServiceTest.java @@ -16,7 +16,6 @@ import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.Appender; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.cloud.client.discovery.DiscoveryClient; import com.nimbusds.jose.jwk.JWKSet; import org.hamcrest.collection.IsMapContaining; import org.json.JSONException; @@ -26,35 +25,19 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.Mockito; +import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; import org.skyscreamer.jsonassert.JSONAssert; import org.slf4j.LoggerFactory; +import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.context.ApplicationContext; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import org.springframework.http.*; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; -import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.client.RestClientException; -import org.springframework.web.client.RestTemplate; -import org.zowe.apiml.zaas.security.service.AuthenticationService; -import org.zowe.apiml.zaas.security.service.TokenCreationService; -import org.zowe.apiml.zaas.security.service.schema.source.AuthSource; -import org.zowe.apiml.zaas.security.service.schema.source.ParsedTokenAuthSource; +import org.springframework.web.client.*; import org.zowe.apiml.message.log.ApimlLogger; import org.zowe.apiml.security.common.config.AuthConfigurationProperties; import org.zowe.apiml.security.common.error.ServiceNotAccessibleException; @@ -62,6 +45,10 @@ import org.zowe.apiml.security.common.login.LoginRequest; import org.zowe.apiml.security.common.token.TokenNotValidException; import org.zowe.apiml.zaas.ZaasTokenResponse; +import org.zowe.apiml.zaas.security.service.AuthenticationService; +import org.zowe.apiml.zaas.security.service.TokenCreationService; +import org.zowe.apiml.zaas.security.service.schema.source.AuthSource; +import org.zowe.apiml.zaas.security.service.schema.source.ParsedTokenAuthSource; import javax.management.ServiceNotFoundException; import javax.net.ssl.SSLHandshakeException; @@ -69,23 +56,12 @@ import java.net.URL; import java.nio.charset.Charset; import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import static org.zowe.apiml.zaas.security.service.zosmf.ZosmfService.TokenType.JWT; import static org.zowe.apiml.zaas.security.service.zosmf.ZosmfService.TokenType.LTPA; @@ -304,12 +280,11 @@ class WhenChangingPassword { @BeforeEach void setUp() { this.zosmfService = getZosmfServiceSpy(); + when(authentication.getCredentials()).thenReturn(loginRequest); } @Test void thenChangePasswordWithSuccess() { - Authentication authentication = mock(UsernamePasswordAuthenticationToken.class); - ResponseEntity responseEntity = new ResponseEntity<>("{}", null, HttpStatus.OK); doReturn(responseEntity).when(zosmfService).issueChangePasswordRequest(any(), any(), any()); ResponseEntity response = zosmfService.changePassword(authentication); @@ -322,8 +297,6 @@ class WhenClientError { @Test void thenChangePasswordWithClientError() { - when(authentication.getCredentials()).thenReturn(loginRequest); - when(restTemplate.exchange("http://zosmf:1433/zosmf/services/authenticate", HttpMethod.PUT, new HttpEntity<>(new ChangePasswordRequest(loginRequest), requiredHeaders), @@ -335,8 +308,6 @@ void thenChangePasswordWithClientError() { @Test void thenChangePasswordWithUnsupportedZosmf() { - when(authentication.getCredentials()).thenReturn(loginRequest); - when(restTemplate.exchange("http://zosmf:1433/zosmf/services/authenticate", HttpMethod.PUT, new HttpEntity<>(new ChangePasswordRequest(loginRequest), requiredHeaders), @@ -351,8 +322,6 @@ void thenChangePasswordWithUnsupportedZosmf() { class WhenServerError { @Test void thenChangePasswordWithServerError() { - when(authentication.getCredentials()).thenReturn(loginRequest); - when(restTemplate.exchange("http://zosmf:1433/zosmf/services/authenticate", HttpMethod.PUT, new HttpEntity<>(new ChangePasswordRequest(loginRequest), requiredHeaders), @@ -364,8 +333,6 @@ void thenChangePasswordWithServerError() { @Test void thenChangePasswordWithZosmfInternalError() { - when(authentication.getCredentials()).thenReturn(loginRequest); - when(restTemplate.exchange("http://zosmf:1433/zosmf/services/authenticate", HttpMethod.PUT, new HttpEntity<>(new ChangePasswordRequest(loginRequest), requiredHeaders), @@ -377,8 +344,6 @@ void thenChangePasswordWithZosmfInternalError() { @Test void thenChangePasswordWithZosmfValidationError() { - when(authentication.getCredentials()).thenReturn(loginRequest); - when(restTemplate.exchange("http://zosmf:1433/zosmf/services/authenticate", HttpMethod.PUT, new HttpEntity<>(new ChangePasswordRequest(loginRequest), requiredHeaders), @@ -704,18 +669,21 @@ void thenTestInvalidateRuntimeException() { @Nested class WhenReadTokenFromCookie { - private static final String ZOSMF_PUBLIC_KEY_JSON = "{\n" + - " \"keys\": [\n" + - " {\n" + - " \"kty\": \"RSA\",\n" + - " \"e\": \"AQAB\",\n" + - " \"use\": \"sig\",\n" + - " \"kid\": \"ozG_ySMHRsVQFmN1mVBeS-WtCupY1r-K7ewben09IBg\",\n" + - " \"alg\": \"RS256\",\n" + - " \"n\": \"wRdwksGIAR2A4cHsoOsYcGp5AmQl5ZjF5xIPXeyjkaLHmNTMvjixdWso1ecVlVeg_6pIXzMRhmOvmjXjz1PLfI2GD3drmeqsStjISWdDfH_rIQCYc9wYbWIZ3bQ0wFRDaVpZ6iOZ2iNcIevvZQKNw9frJthKSMM52JtsgwrgN--Ub2cKWioU_d52SC2SfDzOdnChqlU7xkqXwKXSUqcGM92A35dJJXkwbZhAHnDy5FST1HqYq27MOLzBkChw1bJQHZtlSqkxcHPxphnnbFKQmwRVUvyC5kfBemX-7Mzp1wDogt5lGvBAf3Eq8rFxaevAke327rM7q2KqO_LDMN2J-Q\"\n" + - " }\n" + - " ]\n" + - "}"; + private static final String ZOSMF_PUBLIC_KEY_JSON = + """ + { + "keys": [ + { + "kty": "RSA", + "e": "AQAB", + "use": "sig", + "kid": "ozG_ySMHRsVQFmN1mVBeS-WtCupY1r-K7ewben09IBg", + "alg": "RS256", + "n": "wRdwksGIAR2A4cHsoOsYcGp5AmQl5ZjF5xIPXeyjkaLHmNTMvjixdWso1ecVlVeg_6pIXzMRhmOvmjXjz1PLfI2GD3drmeqsStjISWdDfH_rIQCYc9wYbWIZ3bQ0wFRDaVpZ6iOZ2iNcIevvZQKNw9frJthKSMM52JtsgwrgN--Ub2cKWioU_d52SC2SfDzOdnChqlU7xkqXwKXSUqcGM92A35dJJXkwbZhAHnDy5FST1HqYq27MOLzBkChw1bJQHZtlSqkxcHPxphnnbFKQmwRVUvyC5kfBemX-7Mzp1wDogt5lGvBAf3Eq8rFxaevAke327rM7q2KqO_LDMN2J-Q" + } + ] + } + """; @Test void thenSuccess() throws JSONException, ParseException { @@ -979,7 +947,7 @@ void givenZoweAuthSourceWithLtpa_thenSameLtpaTokenIsReturned() throws ServiceNot void givenZoweAuthSourceWithoutLtpa_thenNewJwtTokenIsReturned() throws ServiceNotFoundException { AuthSource.Parsed authParsedSource = new ParsedTokenAuthSource(USER, new Date(), new Date(), AuthSource.Origin.ZOWE); - Map tokens = new HashMap() {{ + Map tokens = new HashMap<>() {{ put(JWT, ZOSMF_JWT_TOKEN); }}; when(authenticationService.getLtpaToken(ZOWE_JWT_TOKEN)).thenReturn(null); @@ -995,7 +963,7 @@ void givenZoweAuthSourceWithoutLtpa_thenNewJwtTokenIsReturned() throws ServiceNo void givenOtherAuthSourceAndZosmfProducesJwt_thenNewJwtTokenIsReturned() throws ServiceNotFoundException { AuthSource.Parsed authParsedSource = new ParsedTokenAuthSource(USER, new Date(), new Date(), AuthSource.Origin.OIDC); - Map tokens = new HashMap() {{ + Map tokens = new HashMap<>() {{ put(LTPA, LTPA_TOKEN); put(JWT, ZOSMF_JWT_TOKEN); }}; @@ -1011,7 +979,7 @@ void givenOtherAuthSourceAndZosmfProducesJwt_thenNewJwtTokenIsReturned() throws void givenOtherAuthSourceAndZosmfProducesOnlyLtpa_thenNewLtpaTokenIsReturned() throws ServiceNotFoundException { AuthSource.Parsed authParsedSource = new ParsedTokenAuthSource(USER, new Date(), new Date(), AuthSource.Origin.OIDC); - Map tokens = new HashMap() {{ + Map tokens = new HashMap<>() {{ put(LTPA, LTPA_TOKEN); }}; when(tokenCreationService.createZosmfTokensWithoutCredentials(USER)).thenReturn(tokens);