Tests: Ensure HTTPClient does not follow redirects after post

Relates elastic/x-pack-elasticsearch#470

Original commit: elastic/x-pack-elasticsearch@5333a65c0e
This commit is contained in:
Alexander Reelsen 2017-05-24 23:32:57 +02:00
parent 9a7c28786a
commit 463c337d62
2 changed files with 40 additions and 2 deletions

View File

@ -113,8 +113,10 @@ public class MockWebServer implements Closeable {
byte[] responseAsBytes = response.getBody().getBytes(StandardCharsets.UTF_8);
s.sendResponseHeaders(response.getStatusCode(), responseAsBytes.length);
sleepIfNeeded(response.getBodyDelay());
try (OutputStream responseBody = s.getResponseBody()) {
responseBody.write(responseAsBytes);
if ("HEAD".equals(request.getMethod()) == false) {
try (OutputStream responseBody = s.getResponseBody()) {
responseBody.write(responseAsBytes);
}
}
}
} catch (Exception e) {

View File

@ -447,4 +447,40 @@ public class HttpClientTests extends ESTestCase {
IOException e = expectThrows(IOException.class, () -> httpClient.execute(requestBuilder.build()));
assertThat(e.getMessage(), startsWith("Maximum limit of"));
}
public void testThatGetRedirectIsFollowed() throws Exception {
String redirectUrl = "http://" + webServer.getHostName() + ":" + webServer.getPort() + "/foo";
webServer.enqueue(new MockResponse().setResponseCode(302).addHeader("Location", redirectUrl));
HttpMethod method = randomFrom(HttpMethod.GET, HttpMethod.HEAD);
if (method == HttpMethod.GET) {
webServer.enqueue(new MockResponse().setResponseCode(200).setBody("shouldBeRead"));
} else if (method == HttpMethod.HEAD) {
webServer.enqueue(new MockResponse().setResponseCode(200));
}
HttpRequest request = HttpRequest.builder("localhost", webServer.getPort()).path("/")
.method(method)
.build();
HttpResponse response = httpClient.execute(request);
assertThat(webServer.requests(), hasSize(2));
if (method == HttpMethod.GET) {
assertThat(response.body().utf8ToString(), is("shouldBeRead"));
} else if (method == HttpMethod.HEAD) {
assertThat(response.body(), is(nullValue()));
}
}
// not allowed by RFC, only allowed for GET or HEAD
public void testThatPostRedirectIsNotFollowed() throws Exception {
String redirectUrl = "http://" + webServer.getHostName() + ":" + webServer.getPort() + "/foo";
webServer.enqueue(new MockResponse().setResponseCode(302).addHeader("Location", redirectUrl));
webServer.enqueue(new MockResponse().setResponseCode(200).setBody("shouldNeverBeRead"));
HttpRequest request = HttpRequest.builder("localhost", webServer.getPort()).path("/").method(HttpMethod.POST).build();
HttpResponse response = httpClient.execute(request);
assertThat(response.body(), is(nullValue()));
assertThat(webServer.requests(), hasSize(1));
}
}