Skip to content

Commit 36da01e

Browse files
committed
fix: retain HTTP status when agent response encoding is invalid
1 parent 1a326a6 commit 36da01e

2 files changed

Lines changed: 58 additions & 8 deletions

File tree

‎src/main/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClient.java‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import java.util.concurrent.TimeUnit;
3535
import lombok.extern.slf4j.Slf4j;
3636
import org.apache.http.HttpEntity;
37+
import org.apache.http.ParseException;
3738
import org.apache.http.client.config.RequestConfig;
3839
import org.apache.http.client.methods.CloseableHttpResponse;
3940
import org.apache.http.client.methods.HttpPost;
@@ -141,15 +142,28 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
141142
try (CloseableHttpResponse response = client.execute(post)) {
142143
int status = response.getStatusLine().getStatusCode();
143144
observedStatus = status;
144-
Optional<String> body = readBoundedBody(response.getEntity(), maxResponseBytes);
145+
HttpEntity entity = response.getEntity();
146+
Optional<byte[]> body = readBoundedBody(entity, maxResponseBytes);
145147
if (post.isAborted() || deadline - System.nanoTime() <= 0) {
146148
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
147149
}
148-
String respBody = body.orElseThrow(
150+
byte[] responseBytes = body.orElseThrow(
149151
() -> new OpenCliRemoteResponseLimitException(status, maxResponseBytes, correlationId));
150-
if (status < 200 || status >= 300) {
151-
log.warn("Agent HTTP non-2xx correlationId={} status={} responseChars={}",
152-
correlationId, status, respBody.length());
152+
boolean successfulStatus = status >= 200 && status < 300;
153+
String respBody;
154+
try {
155+
respBody = decodeBody(entity, responseBytes);
156+
} catch (IllegalArgumentException | ParseException e) {
157+
log.warn("Agent content type invalid correlationId={} status={}", correlationId, status);
158+
if (successfulStatus) {
159+
throw new OpenCliRemoteProtocolException("Invalid agent response content type", correlationId,
160+
failureSnapshot(status, Outcome.PROTOCOL_FAILURE, null));
161+
}
162+
respBody = null;
163+
}
164+
if (!successfulStatus) {
165+
log.warn("Agent HTTP non-2xx correlationId={} status={} responseBytes={}",
166+
correlationId, status, responseBytes.length);
153167
throw new OpenCliExecutableFailureException("Agent HTTP " + status + " correlationId=" + correlationId,
154168
null, failureSnapshot(status, Outcome.HTTP_FAILURE, respBody));
155169
}
@@ -225,9 +239,9 @@ public void close() {
225239
}
226240
}
227241

228-
private static Optional<String> readBoundedBody(HttpEntity entity, int limit) throws IOException {
242+
private static Optional<byte[]> readBoundedBody(HttpEntity entity, int limit) throws IOException {
229243
if (Objects.isNull(entity)) {
230-
return Optional.of("");
244+
return Optional.of(new byte[0]);
231245
}
232246
// The response owns the stream. Closing the stream itself can drain an oversized entity.
233247
InputStream input = entity.getContent();
@@ -245,9 +259,13 @@ private static Optional<String> readBoundedBody(HttpEntity entity, int limit) th
245259
}
246260
body.write(buffer, 0, read);
247261
}
262+
return Optional.of(body.toByteArray());
263+
}
264+
265+
private static String decodeBody(HttpEntity entity, byte[] body) {
248266
ContentType type = ContentType.get(entity);
249267
Charset charset = Objects.nonNull(type) ? type.getCharset() : null;
250-
return Optional.of(body.toString(Objects.nonNull(charset) ? charset.name() : StandardCharsets.UTF_8.name()));
268+
return new String(body, Objects.nonNull(charset) ? charset : StandardCharsets.UTF_8);
251269
}
252270

253271
private int resolveTimeoutMillis() {

‎src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,38 @@ void keepsDeclaredCharsetWithinTheResponseLimit() throws IOException {
335335
}
336336
}
337337

338+
@ParameterizedTest
339+
@ValueSource(ints = {200, 503})
340+
void invalidResponseCharsetRetainsTheObservedHttpStatus(int status) throws IOException {
341+
String canary = "unexpected-charset-body";
342+
try (JsonCollectStub stub = JsonCollectStub.start(exchange -> {
343+
byte[] body = canary.getBytes(StandardCharsets.UTF_8);
344+
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=no-such-charset");
345+
exchange.sendResponseHeaders(status, body.length);
346+
try (OutputStream output = exchange.getResponseBody()) {
347+
output.write(body);
348+
}
349+
})) {
350+
OpenCliProperties props = baseProps(stub.port());
351+
props.setRemoteCaptureRawHttpResponse(true);
352+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(props)) {
353+
OpenCliExecutableFailureException failure = Assertions.assertThrows(
354+
OpenCliExecutableFailureException.class,
355+
() -> client.collect(OpenCliCollectRequest.builder().site("x").command("y").build()));
356+
Assertions.assertEquals(status == 200 ? OpenCliRemoteProtocolException.class
357+
: OpenCliExecutableFailureException.class, failure.getClass());
358+
OpenCliResult partial = failure.getPartialResult();
359+
Assertions.assertNotNull(partial);
360+
Assertions.assertEquals(status, partial.getRemoteExecutionDetails().getHttpStatus());
361+
Assertions.assertEquals(status == 200 ? Outcome.PROTOCOL_FAILURE : Outcome.HTTP_FAILURE,
362+
partial.getRemoteExecutionDetails().getOutcome());
363+
Assertions.assertEquals(ExitCodeSource.UNAVAILABLE, partial.getRemoteExecutionDetails().getExitCodeSource());
364+
Assertions.assertNull(partial.getRemoteRawHttpBody());
365+
Assertions.assertFalse(failure.toString().contains(canary));
366+
}
367+
}
368+
}
369+
338370
@Test
339371
void httpFailureRetainsItsStatusWithoutCreatingAProcessExit() throws IOException {
340372
String body = "<html>fixture-proxy-error</html>";

0 commit comments

Comments
 (0)