Skip to content

Commit e6e8131

Browse files
committed
fix: retain HTTP status when agent response encoding is invalid
1 parent 97e5a73 commit e6e8131

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
@@ -33,6 +33,7 @@
3333
import java.util.concurrent.TimeUnit;
3434
import lombok.extern.slf4j.Slf4j;
3535
import org.apache.http.HttpEntity;
36+
import org.apache.http.ParseException;
3637
import org.apache.http.client.config.RequestConfig;
3738
import org.apache.http.client.methods.CloseableHttpResponse;
3839
import org.apache.http.client.methods.HttpPost;
@@ -140,15 +141,28 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
140141
try (CloseableHttpResponse response = client.execute(post)) {
141142
int status = response.getStatusLine().getStatusCode();
142143
observedStatus = status;
143-
Optional<String> body = readBoundedBody(response.getEntity(), maxResponseBytes);
144+
HttpEntity entity = response.getEntity();
145+
Optional<byte[]> body = readBoundedBody(entity, maxResponseBytes);
144146
if (post.isAborted() || deadline - System.nanoTime() <= 0) {
145147
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
146148
}
147-
String respBody = body.orElseThrow(
149+
byte[] responseBytes = body.orElseThrow(
148150
() -> new OpenCliRemoteResponseLimitException(status, maxResponseBytes, correlationId));
149-
if (status < 200 || status >= 300) {
150-
log.warn("Agent HTTP non-2xx correlationId={} status={} responseChars={}",
151-
correlationId, status, respBody.length());
151+
boolean successfulStatus = status >= 200 && status < 300;
152+
String respBody;
153+
try {
154+
respBody = decodeBody(entity, responseBytes);
155+
} catch (IllegalArgumentException | ParseException e) {
156+
log.warn("Agent content type invalid correlationId={} status={}", correlationId, status);
157+
if (successfulStatus) {
158+
throw new OpenCliRemoteProtocolException("Invalid agent response content type", correlationId,
159+
failureSnapshot(status, Outcome.PROTOCOL_FAILURE, null));
160+
}
161+
respBody = null;
162+
}
163+
if (!successfulStatus) {
164+
log.warn("Agent HTTP non-2xx correlationId={} status={} responseBytes={}",
165+
correlationId, status, responseBytes.length);
152166
throw new OpenCliExecutableFailureException("Agent HTTP " + status + " correlationId=" + correlationId,
153167
null, failureSnapshot(status, Outcome.HTTP_FAILURE, respBody));
154168
}
@@ -224,9 +238,9 @@ public void close() {
224238
}
225239
}
226240

227-
private static Optional<String> readBoundedBody(HttpEntity entity, int limit) throws IOException {
241+
private static Optional<byte[]> readBoundedBody(HttpEntity entity, int limit) throws IOException {
228242
if (Objects.isNull(entity)) {
229-
return Optional.of("");
243+
return Optional.of(new byte[0]);
230244
}
231245
// The response owns the stream. Closing the stream itself can drain an oversized entity.
232246
InputStream input = entity.getContent();
@@ -244,9 +258,13 @@ private static Optional<String> readBoundedBody(HttpEntity entity, int limit) th
244258
}
245259
body.write(buffer, 0, read);
246260
}
261+
return Optional.of(body.toByteArray());
262+
}
263+
264+
private static String decodeBody(HttpEntity entity, byte[] body) {
247265
ContentType type = ContentType.get(entity);
248266
Charset charset = Objects.nonNull(type) ? type.getCharset() : null;
249-
return Optional.of(body.toString(Objects.nonNull(charset) ? charset.name() : StandardCharsets.UTF_8.name()));
267+
return new String(body, Objects.nonNull(charset) ? charset : StandardCharsets.UTF_8);
250268
}
251269

252270
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)