From 87416bc7cbef7dd106add66a14fe17b9ed942b6e Mon Sep 17 00:00:00 2001 From: Arsalan Khan Date: Tue, 30 May 2023 14:03:25 +0200 Subject: [PATCH] Refactor BasicAuthenticationFilter --- .../conf/HealthServerConfiguration.java | 35 +++- .../rest/BasicAuthenticationFilter.java | 168 +++++++----------- .../conf/HealthServerConfigurationTest.java | 16 ++ .../rest/BasicAuthenticationFilterTest.java | 4 +- .../HealthEndpointWithBasicAuthTest.java | 57 +++--- .../HealthEndpointWithoutBasicAuthTest.java | 22 ++- .../scheduler/util/HealthUtils.java | 21 ++- 7 files changed, 168 insertions(+), 155 deletions(-) diff --git a/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfiguration.java b/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfiguration.java index 1536af262e..5894bbe5c4 100644 --- a/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfiguration.java +++ b/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfiguration.java @@ -1,6 +1,8 @@ package org.cloudfoundry.autoscaler.scheduler.conf; import jakarta.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import java.util.Set; import lombok.AllArgsConstructor; @@ -21,10 +23,16 @@ public class HealthServerConfiguration { private Integer port; private Set unprotectedEndpoints; + final Map validProtectedEndpoints = + Map.of( + "/health/prometheus", true, + "/health/liveness", true); + @PostConstruct public void init() { validatePort(); + validateConfiguredEndpoints(); boolean basicAuthEnabled = (unprotectedEndpoints != null || ObjectUtils.isEmpty(unprotectedEndpoints)); @@ -33,7 +41,8 @@ public void init() { || this.password == null || this.username.isEmpty() || this.password.isEmpty())) { - throw new IllegalArgumentException("Heath Server Basic Auth Username or password is not set"); + throw new IllegalArgumentException( + "Health Server Basic Auth Username or password is not set"); } } @@ -41,7 +50,29 @@ private void validatePort() { Optional healthPortOptional = Optional.ofNullable(this.port); if (!healthPortOptional.isPresent() || healthPortOptional.get() == 0) { throw new IllegalArgumentException( - "Health Configuration: health server port not defined or set to unsupported port-number `0`"); + "Health Configuration: health server port not defined or set to unsupported port-number" + + " `0`"); + } + } + + private void validateConfiguredEndpoints() { + + Map invalidEndpointsMap = new HashMap<>(); + if (unprotectedEndpoints == null) { + return; + } + for (String unprotectedEndpoint : unprotectedEndpoints) { + if (!validProtectedEndpoints.containsKey(unprotectedEndpoint)) { + invalidEndpointsMap.put(unprotectedEndpoint, true); + } + } + if (!ObjectUtils.isEmpty(invalidEndpointsMap)) { + throw new IllegalArgumentException( + "Health configuration: invalid unprotectedEndpoints provided: " + + invalidEndpointsMap + + "\n" + + "validate endpoints are: " + + validProtectedEndpoints); } } } diff --git a/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilter.java b/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilter.java index e84419df88..a13fcd16c0 100644 --- a/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilter.java +++ b/src/scheduler/src/main/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilter.java @@ -8,12 +8,8 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.cloudfoundry.autoscaler.scheduler.conf.HealthServerConfiguration; @@ -27,14 +23,6 @@ @Order(2) public class BasicAuthenticationFilter implements Filter { private static final String WWW_AUTHENTICATE_VALUE = "Basic"; - private static final Map validProtectedEndpointsMap; - - static { - validProtectedEndpointsMap = - Map.of( - "/health/prometheus", true, - "/health/liveness", true); - } final HealthServerConfiguration healthServerConfiguration; @@ -55,51 +43,62 @@ public void doFilter( chain.doFilter(servletRequest, servletResponse); return; } - final boolean allEndpointsRequireAuthorization = ObjectUtils.isEmpty(unprotectedEndpointsConfig); - if (allEndpointsRequireAuthorization) { - isUserAuthenticatedOrSendError(chain, httpRequest, httpResponse); + + if (allEndpointsRequireAuthorization) { // case 1 ; config [] + allowAuthenticatedRequest(chain, httpRequest, httpResponse); + } else if (!ObjectUtils.isEmpty(unprotectedEndpointsConfig)) { - Map validateMap = checkValidEndpoints(unprotectedEndpointsConfig); - if (!ObjectUtils.isEmpty(validateMap)) { - log.warn( - "Health configuration: invalid unprotectedEndpoints provided: " - + validateMap.get("invalidEndpoints")); + /* + // case 2.1 ; config ["/health/liveness"] + here is – by configuration – one protected endpoint "/health/prometheus" and one unprotected "/health/liveness". + The user is authenticated. + The user queries on "/health/prometheus". + Expected behaviour: The request will be handled successfully. + */ + + // IMPORTANT: Match the configured health endpoints with the allowed list of endpoints to + // cover + // BasicAuthenticationFilterTest#denyHealthRequestWithWrongUnprotectedEndpoints() + // Suggestion: THe following block should be part of HealthConfiguration. + // Move this block to Health Configuration/Or adjust test + if (!healthConfigsExists()) { + log.error("Health Configuration: Invalid endpoints defined"); httpResponse.setHeader(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } - Map unprotectedConfig = getMapFromList(unprotectedEndpointsConfig); - List allowedEndpointsWithoutBasicAuth = - areEndpointsAuthorized(unprotectedConfig, httpRequest.getRequestURI()); - - if (!allowedEndpointsWithoutBasicAuth.contains(httpRequest.getRequestURI())) { - log.error( - "Health configuration: Basic auth is required to access protectedEndpoints: " - + httpRequest.getRequestURI() - + " \nValid unprotected endpoints are: " - + allowedEndpointsWithoutBasicAuth); - httpResponse.setHeader("WWW-Authenticate", WWW_AUTHENTICATE_VALUE); - httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); - return; + + boolean isEndpointRequireAuthentication = + isEndpointRequireAuthentication(httpRequest.getRequestURI()); + if (isEndpointRequireAuthentication) { + allowAuthenticatedRequest(chain, httpRequest, httpResponse); + } else { // RequestURI() does not need authentication ( + // Case 2.2 ; config ["/health/liveness", "/health/prometheus"] + chain.doFilter(servletRequest, servletResponse); } - chain.doFilter(servletRequest, servletResponse); } } - private void isUserAuthenticatedOrSendError( + private boolean healthConfigsExists() { + boolean found = false; + Map validProtectedEndpoints = + healthServerConfiguration.getValidProtectedEndpoints(); + for (String configuredEndpoint : healthServerConfiguration.getUnprotectedEndpoints()) { + found = validProtectedEndpoints.containsKey(configuredEndpoint); + } + if (!found) { + return false; + } + return true; + } + + private void allowAuthenticatedRequest( FilterChain filterChain, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { final String authorizationHeader = httpRequest.getHeader("Authorization"); - if (healthServerConfiguration.getUsername() == null - || healthServerConfiguration.getPassword() == null) { - log.error("Health configuration: username || password not set"); - httpResponse.setHeader(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE); - httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); - return; - } if (authorizationHeader == null) { log.error("Basic authentication not provided with the request"); httpResponse.setHeader(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE); @@ -107,92 +106,45 @@ private void isUserAuthenticatedOrSendError( return; } - String base64Credentials = - authorizationHeader.substring(WWW_AUTHENTICATE_VALUE.length()).trim(); - byte[] credDecoded = Base64.decodeBase64(base64Credentials); - String credentials = new String(credDecoded); - String[] tokens = credentials.split(":"); + String[] tokens = decodeAndGetAuthTokens(authorizationHeader); if (tokens.length != 2) { log.error("Malformed authorization header"); httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } - String username = tokens[0]; - String password = tokens[1]; - - if (!areBasicAuthCredentialsCorrect(username, password)) { - httpResponse.setHeader(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE); - httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); - return; - } if (isUserAuthenticated(authorizationHeader)) { // allow access to health endpoints filterChain.doFilter(httpRequest, httpResponse); } else { + log.error( + "Health configuration: Basic auth is required to access protectedEndpoints: " + + httpRequest.getRequestURI() + + " \nValid unprotected endpoints are: " + + healthServerConfiguration.getUnprotectedEndpoints()); httpResponse.setHeader(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } - private Map checkValidEndpoints(Set unprotectedEndpointsConfig) { - - Map invalidEndpointsMap = new HashMap<>(); - for (String unprotectedEndpoint : unprotectedEndpointsConfig) { - if (!validProtectedEndpointsMap.containsKey(unprotectedEndpoint)) { - invalidEndpointsMap.put(unprotectedEndpoint, true); - } - } - return invalidEndpointsMap; - } - - private static Map getMapFromList(Set unprotectedEndpointsConfig) { - return unprotectedEndpointsConfig.stream() - .collect(Collectors.toMap(endpoint -> endpoint, endpoint -> true, (a, b) -> b)); - } - - private List areEndpointsAuthorized( - Map unprotectedEndpointsConfig, String requestURI) { - Map resultUnprotectedEndpoints = new HashMap<>(); - for (Map.Entry protectedEndpoint : validProtectedEndpointsMap.entrySet()) { - if (unprotectedEndpointsConfig.containsKey(protectedEndpoint.getKey())) { - resultUnprotectedEndpoints.put(protectedEndpoint.getKey(), false); - } - } - List allowedEndpointsWithoutBasicAuth = - keys(resultUnprotectedEndpoints, false).toList(); - if (isBasicAuthRequired(requestURI, allowedEndpointsWithoutBasicAuth)) { - log.debug("Endpoints allowed without basic auth: + " + allowedEndpointsWithoutBasicAuth); - return allowedEndpointsWithoutBasicAuth; - } - return allowedEndpointsWithoutBasicAuth; - } - - private static boolean isBasicAuthRequired(String requestURI, List allowedEndpoints) { - return !ObjectUtils.isEmpty(allowedEndpoints) && allowedEndpoints.contains(requestURI); - } + private boolean isEndpointRequireAuthentication(String requestURI) { + Map protectedEndpoints = + healthServerConfiguration.getValidProtectedEndpoints(); + boolean isProtected = protectedEndpoints.containsKey(requestURI); + boolean isUnprotectedByConfiguration = + healthServerConfiguration.getUnprotectedEndpoints().contains(requestURI); - private Stream keys(Map map, V val) { - return map.entrySet().stream() - .filter(entry -> val.equals(entry.getValue())) - .map(Map.Entry::getKey); + return isProtected && !isUnprotectedByConfiguration; } private boolean isUserAuthenticated(String authorization) { - if (healthServerConfiguration.getUsername() == null - || healthServerConfiguration.getPassword() == null) { - log.error("Health configuration: username || password not set"); - return false; - } + if (authorization == null) { log.error("Basic authentication not provided with the request"); return false; } - String base64Credentials = authorization.substring("Basic".length()).trim(); - byte[] credDecoded = Base64.decodeBase64(base64Credentials); - String credentials = new String(credDecoded); - String[] tokens = credentials.split(":"); + String[] tokens = decodeAndGetAuthTokens(authorization); if (tokens.length != 2) { log.error("Malformed authorization header"); return false; @@ -202,6 +154,14 @@ private boolean isUserAuthenticated(String authorization) { return areBasicAuthCredentialsCorrect(username, password); } + private static String[] decodeAndGetAuthTokens(String authorization) { + String base64Credentials = authorization.substring(WWW_AUTHENTICATE_VALUE.length()).trim(); + byte[] credDecoded = Base64.decodeBase64(base64Credentials); + String credentials = new String(credDecoded); + String[] tokens = credentials.split(":"); + return tokens; + } + private boolean areBasicAuthCredentialsCorrect(String username, String password) { return healthServerConfiguration.getUsername().equals(username) && healthServerConfiguration.getPassword().equals(password); diff --git a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfigurationTest.java b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfigurationTest.java index 771726020e..24dfec8606 100644 --- a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfigurationTest.java +++ b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/conf/HealthServerConfigurationTest.java @@ -77,4 +77,20 @@ void givenEmptyPortThrowsException() { IllegalArgumentException.class, () -> new HealthServerConfiguration("", "", null, Set.of()).init()); } + + @Test + void givenInvalidConfiguredEndpointsThrowsException() { + assertThrows( + IllegalArgumentException.class, + () -> new HealthServerConfiguration("", "", 8888, Set.of("/info")).init()); + } + + @Test + void givenValidConfiguredEndpoints() { + assertDoesNotThrow( + () -> + new HealthServerConfiguration( + "some-user", "some-password", 8888, Set.of("/health/prometheus")) + .init()); + } } diff --git a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilterTest.java b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilterTest.java index 97f5970248..94a5db973a 100644 --- a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilterTest.java +++ b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/BasicAuthenticationFilterTest.java @@ -51,7 +51,7 @@ public void allowRequestIfPort8081andURIContainHealthWithoutUnprotectedEndpoints } @Test - public void denyHealthRequestWithoutUnprotectedEndpointsAndInvalidCredentials() + public void denyHealthRequesWithAllSecuredEndpointsAndInvalidCredentials() throws ServletException, IOException { req.setRequestURI("some/health/uri"); @@ -59,7 +59,7 @@ public void denyHealthRequestWithoutUnprotectedEndpointsAndInvalidCredentials() String auth = username + ":" + password; req.addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes())); HealthServerConfiguration healthServerConfig = - new HealthServerConfiguration(null, null, 8081, Set.of()); + new HealthServerConfiguration("", "", 8081, Set.of()); BasicAuthenticationFilter userPwNullFilter = new BasicAuthenticationFilter(healthServerConfig); userPwNullFilter.doFilter(req, res, filterChainMock); diff --git a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithBasicAuthTest.java b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithBasicAuthTest.java index 747991123e..8feddbb531 100644 --- a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithBasicAuthTest.java +++ b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithBasicAuthTest.java @@ -2,7 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.net.MalformedURLException; +import java.net.URISyntaxException; import org.cloudfoundry.autoscaler.scheduler.conf.HealthServerConfiguration; +import org.cloudfoundry.autoscaler.scheduler.util.HealthUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -29,12 +32,13 @@ public class HealthEndpointWithBasicAuthTest { @Autowired private HealthServerConfiguration healthServerConfig; @Test - public void givenCorrectCredentialsPrometheusShouldBeAvailable() { + public void givenCorrectCredentialsPrometheusShouldBeAvailable() + throws MalformedURLException, URISyntaxException { ResponseEntity response = this.restTemplate .withBasicAuth("prometheus", "someHash") - .getForEntity(prometheusMetricsUrl(), String.class); + .getForEntity(HealthUtils.prometheusMetricsUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be OK") .isEqualTo(200); @@ -65,39 +69,42 @@ public void givenRootEndpointThenMetricsShouldNotBeAvailable() { } @Test - public void givenIncorrectCredentialsShouldReturn401() { + public void givenIncorrectCredentialsShouldReturn401() + throws MalformedURLException, URISyntaxException { ResponseEntity response = this.restTemplate .withBasicAuth("bad", "auth") - .getForEntity(prometheusMetricsUrl(), String.class); + .getForEntity(HealthUtils.prometheusMetricsUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be Unauthorized") .isEqualTo(401); } @Test - public void givenNoCredentialsShouldReturn401() { + public void givenNoCredentialsShouldReturn401() throws MalformedURLException, URISyntaxException { ResponseEntity response = - this.restTemplate.getForEntity(prometheusMetricsUrl(), String.class); + this.restTemplate.getForEntity(HealthUtils.prometheusMetricsUrl().toURI(), String.class); assertThat(response.getStatusCode().value()).isEqualTo(401); } @Test - public void givenCorrectPasswordAndWrongUsernameFailsWith401() { + public void givenCorrectPasswordAndWrongUsernameFailsWith401() + throws MalformedURLException, URISyntaxException { ResponseEntity response = this.restTemplate .withBasicAuth("bad", "someHash") - .getForEntity(prometheusMetricsUrl(), String.class); + .getForEntity(HealthUtils.prometheusMetricsUrl().toURI(), String.class); assertThat(response.getStatusCode().value()).isEqualTo(401); } @Test - public void givenCorrectCredentialsLivenessShouldBeAvailable() { + public void givenCorrectCredentialsLivenessShouldBeAvailable() + throws MalformedURLException, URISyntaxException { ResponseEntity response = this.restTemplate .withBasicAuth("prometheus", "someHash") - .getForEntity(livenessUrl(), String.class); + .getForEntity(HealthUtils.livenessUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be OK") .isEqualTo(200); @@ -106,12 +113,13 @@ public void givenCorrectCredentialsLivenessShouldBeAvailable() { } @Test - public void givenCorrectCredentialsLivenessBaseUrlShouldBeAvailable() { + public void givenCorrectCredentialsLivenessBaseUrlShouldBeAvailable() + throws MalformedURLException, URISyntaxException { ResponseEntity response = this.restTemplate .withBasicAuth("prometheus", "someHash") - .getForEntity(baseLivenessUrl(), String.class); + .getForEntity(HealthUtils.baseLivenessUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be OK") .isEqualTo(200); @@ -120,32 +128,25 @@ public void givenCorrectCredentialsLivenessBaseUrlShouldBeAvailable() { } @Test - public void givenNoCredentialsLivenessShouldReturn401() { + public void givenNoCredentialsLivenessShouldReturn401() + throws MalformedURLException, URISyntaxException { - ResponseEntity response = this.restTemplate.getForEntity(livenessUrl(), String.class); + ResponseEntity response = + this.restTemplate.getForEntity(HealthUtils.livenessUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be Unauthorized") .isEqualTo(401); } @Test - public void givenIncorrectCredentialsShouldLivenessReturn401() { + public void givenIncorrectCredentialsShouldLivenessReturn401() + throws MalformedURLException, URISyntaxException { ResponseEntity response = - this.restTemplate.withBasicAuth("bad", "auth").getForEntity(livenessUrl(), String.class); + this.restTemplate + .withBasicAuth("bad", "auth") + .getForEntity(HealthUtils.livenessUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be Unauthorized") .isEqualTo(401); } - - private String prometheusMetricsUrl() { - return "http://localhost:" + healthServerConfig.getPort() + "/health/prometheus"; - } - - private String livenessUrl() { - return baseLivenessUrl() + "/liveness"; - } - - private String baseLivenessUrl() { - return "http://localhost:" + healthServerConfig.getPort() + "/health"; - } } diff --git a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithoutBasicAuthTest.java b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithoutBasicAuthTest.java index 56c0aca664..07fa4b30e5 100644 --- a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithoutBasicAuthTest.java +++ b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/rest/healthControllerTest/HealthEndpointWithoutBasicAuthTest.java @@ -2,8 +2,11 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.net.MalformedURLException; +import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import org.cloudfoundry.autoscaler.scheduler.conf.HealthServerConfiguration; +import org.cloudfoundry.autoscaler.scheduler.util.HealthUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -31,9 +34,11 @@ public class HealthEndpointWithoutBasicAuthTest { @Autowired private HealthServerConfiguration healthServerConfig; @Test - public void givenUnprotectedConfigsShouldLivenessReturn200() { + public void givenUnprotectedConfigsShouldLivenessReturn200() + throws MalformedURLException, URISyntaxException { - ResponseEntity response = this.restTemplate.getForEntity(livenessUrl(), String.class); + ResponseEntity response = + this.restTemplate.getForEntity(HealthUtils.livenessUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be OK") .isEqualTo(200); @@ -42,10 +47,11 @@ public void givenUnprotectedConfigsShouldLivenessReturn200() { } @Test - public void givenUnprotectedConfigsShouldPrometheusReturn200() { + public void givenUnprotectedConfigsShouldPrometheusReturn200() + throws MalformedURLException, URISyntaxException { ResponseEntity response = - this.restTemplate.getForEntity(prometheusMetricsUrl(), String.class); + this.restTemplate.getForEntity(HealthUtils.prometheusMetricsUrl().toURI(), String.class); assertThat(response.getStatusCode().value()) .describedAs("Http status code should be OK") .isEqualTo(200); @@ -67,12 +73,4 @@ public void givenUnprotectedConfigsShouldPrometheusReturn200() { .contains("autoscaler_scheduler_data_source") .contains("autoscaler_scheduler_policy_db_data_source"); } - - private String prometheusMetricsUrl() { - return "http://localhost:" + healthServerConfig.getPort() + "/health/prometheus"; - } - - private String livenessUrl() { - return "http://localhost:" + healthServerConfig.getPort() + "/health/liveness"; - } } diff --git a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/util/HealthUtils.java b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/util/HealthUtils.java index a0d4d3f2cc..3ddb92ba11 100644 --- a/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/util/HealthUtils.java +++ b/src/scheduler/src/test/java/org/cloudfoundry/autoscaler/scheduler/util/HealthUtils.java @@ -1,21 +1,28 @@ package org.cloudfoundry.autoscaler.scheduler.util; +import java.net.MalformedURLException; +import java.net.URL; import org.cloudfoundry.autoscaler.scheduler.conf.HealthServerConfiguration; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class HealthUtils { - @Autowired static HealthServerConfiguration healthServerConfig; + static HealthServerConfiguration healthServerConfig; - private HealthUtils() {} + private HealthUtils(HealthServerConfiguration healthServerConfig) { + this.healthServerConfig = healthServerConfig; + } + + public static URL livenessUrl() throws MalformedURLException { + return new URL("http://localhost:" + healthServerConfig.getPort() + "/health/liveness"); + } - public static String livenessUrl() { - return "http://localhost:" + healthServerConfig.getPort() + "/health/liveness"; + public static URL prometheusMetricsUrl() throws MalformedURLException { + return new URL("http://localhost:" + healthServerConfig.getPort() + "/health/prometheus"); } - public static String prometheusMetricsUrl() { - return "http://localhost:" + healthServerConfig.getPort() + "/health/prometheus"; + public static URL baseLivenessUrl() throws MalformedURLException { + return new URL("http://localhost:" + healthServerConfig.getPort() + "/health"); } }