From 9425432f2ca5eaf8e999944dc35c16f85d65c693 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Fri, 9 Jun 2023 18:27:57 +0200 Subject: [PATCH] Handle HTTP response codes when retrieving data from remote endpoints Closes #20895 --- .../connections/httpclient/HttpClientProvider.java | 2 +- .../connections/httpclient/DefaultHttpClientFactory.java | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/server-spi-private/src/main/java/org/keycloak/connections/httpclient/HttpClientProvider.java b/server-spi-private/src/main/java/org/keycloak/connections/httpclient/HttpClientProvider.java index 0764c8d1a0..0ddc131d34 100755 --- a/server-spi-private/src/main/java/org/keycloak/connections/httpclient/HttpClientProvider.java +++ b/server-spi-private/src/main/java/org/keycloak/connections/httpclient/HttpClientProvider.java @@ -54,7 +54,7 @@ public interface HttpClientProvider extends Provider { * * @param uri * @return response stream, you must close this stream or leaks will happen - * @throws IOException + * @throws IOException On network errors, no content being returned or a non-2xx HTTP status code */ public InputStream get(String uri) throws IOException; } diff --git a/services/src/main/java/org/keycloak/connections/httpclient/DefaultHttpClientFactory.java b/services/src/main/java/org/keycloak/connections/httpclient/DefaultHttpClientFactory.java index b645f08524..d1395faa00 100755 --- a/services/src/main/java/org/keycloak/connections/httpclient/DefaultHttpClientFactory.java +++ b/services/src/main/java/org/keycloak/connections/httpclient/DefaultHttpClientFactory.java @@ -110,8 +110,15 @@ public class DefaultHttpClientFactory implements HttpClientFactory { public InputStream get(String uri) throws IOException { HttpGet request = new HttpGet(uri); HttpResponse response = httpClient.execute(request); + int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); - if (entity == null) return null; + if (statusCode < 200 || statusCode >= 300) { + EntityUtils.consumeQuietly(entity); + throw new IOException("Unexpected HTTP status code " + response.getStatusLine().getStatusCode() + " when expecting 2xx"); + } + if (entity == null) { + throw new IOException("No content returned from HTTP call"); + } return entity.getContent(); }