Skip to content

Commit 6894071

Browse files
committed
Sanitize OpenCLI HTTP cleanup exceptions
1 parent ddfa6c8 commit 6894071

3 files changed

Lines changed: 179 additions & 28 deletions

File tree

‎openspec/changes/harden-opencli-diagnostics-privacy/tasks.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,9 @@ Java 8 `cd1ceac`、Java 17 `0b7091c`、Java 21 `5bee58b` 是本轮修改前基
8989
| 反向 WebSocket 客户端 | 9 | 连接 UUID 或重连次数 | `OpenCliWsReverseAgentSessionTest`、`OpenCliWsReverseAgentClientTest`,七个调用点实际执行 |
9090

9191
每线当前 JaCoCo 报告均覆盖 24 个 SDK 日志调用点中的 19 个。仍缺独立驱动 HTTP 请求序列化失败、外层 JSON 映射失败、HTTP transport 关闭失败、WebSocket onError 及 WebSocket 关闭抛异常的动态证据。源码核对确认这些日志也使用固定消息或 SDK 生成的 ID,JaCoCo 缺口由 1.1 和 2.2 继续跟踪。该核对限于 SDK 自身的日志调用与实测异常。
92+
93+
## HTTP 资源关闭异常的隐私回归
94+
95+
OC-PRIV-002/006。Java 17 基线 `ddfa6c8` 的四个定向用例有两个失败。无效响应的协议异常附带了原始 HTTP 响应关闭异常,公开异常栈包含测试标记。连接池关闭的运行时异常也直接暴露了标记。响应清理现在仅传播固定消息,协议失败保留主要类别和 HTTP 200。单独发生的响应关闭 I/O 故障保留传输失败及已观察到的状态,关闭超时沿用超时分类。连接池关闭失败使用固定日志。请求序列化的独立回归确认测试标记未出现在日志或异常栈,回环服务接收请求数为 0。
96+
97+
三线分别以 Java 8 `d5799ac`、Java 17 `ddfa6c8`、Java 21 `0b4b0c8` 为基线修改,用各自 Wrapper 执行 `./mvnw -B -ntp -o clean verify`。分别通过 2,248、2,249、2,248 项,零失败、零错误、零跳过。响应和连接池的关闭异常使用注入的 Apache HTTP provider 测试,协议解析和序列化回归分别使用 JSON 夹具及回环服务。三份 JaCoCo 均命中 24 个日志调用点中的 21 个。HTTP 外层响应映射失败、WebSocket onError 和 WebSocket 关闭抛异常仍待动态证据。

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

Lines changed: 43 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import io.github.easy4j.opencli.parser.OpenCliParsedFields;
2020
import io.github.easy4j.opencli.util.OpenCliStrings;
2121
import java.io.ByteArrayOutputStream;
22+
import java.io.Closeable;
2223
import java.io.IOException;
2324
import java.io.InputStream;
2425
import java.net.SocketTimeoutException;
@@ -138,35 +139,38 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
138139

139140
ScheduledFuture<?> abort = DEADLINES.schedule(post::abort, deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
140141
int observedStatus = 0;
141-
try (CloseableHttpResponse response = client.execute(post)) {
142-
int status = response.getStatusLine().getStatusCode();
143-
observedStatus = status;
144-
HttpEntity entity = response.getEntity();
145-
Optional<byte[]> body = readBoundedBody(entity, maxResponseBytes);
146-
if (post.isAborted() || deadline - System.nanoTime() <= 0) {
147-
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
148-
}
149-
byte[] responseBytes = body.orElseThrow(
150-
() -> new OpenCliRemoteResponseLimitException(status, maxResponseBytes, correlationId));
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));
142+
try {
143+
CloseableHttpResponse response = client.execute(post);
144+
try (Closeable responseCleanup = () -> closeResponse(response)) {
145+
int status = response.getStatusLine().getStatusCode();
146+
observedStatus = status;
147+
HttpEntity entity = response.getEntity();
148+
Optional<byte[]> body = readBoundedBody(entity, maxResponseBytes);
149+
if (post.isAborted() || deadline - System.nanoTime() <= 0) {
150+
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
160151
}
161-
respBody = null;
162-
}
163-
if (!successfulStatus) {
164-
log.warn("Agent HTTP non-2xx correlationId={} status={} responseBytes={}",
165-
correlationId, status, responseBytes.length);
166-
throw new OpenCliExecutableFailureException("Agent HTTP " + status + " correlationId=" + correlationId,
167-
null, failureSnapshot(status, Outcome.HTTP_FAILURE, respBody));
152+
byte[] responseBytes = body.orElseThrow(
153+
() -> new OpenCliRemoteResponseLimitException(status, maxResponseBytes, correlationId));
154+
boolean successfulStatus = status >= 200 && status < 300;
155+
String respBody;
156+
try {
157+
respBody = decodeBody(entity, responseBytes);
158+
} catch (IllegalArgumentException | ParseException e) {
159+
log.warn("Agent content type invalid correlationId={} status={}", correlationId, status);
160+
if (successfulStatus) {
161+
throw new OpenCliRemoteProtocolException("Invalid agent response content type", correlationId,
162+
failureSnapshot(status, Outcome.PROTOCOL_FAILURE, null));
163+
}
164+
respBody = null;
165+
}
166+
if (!successfulStatus) {
167+
log.warn("Agent HTTP non-2xx correlationId={} status={} responseBytes={}",
168+
correlationId, status, responseBytes.length);
169+
throw new OpenCliExecutableFailureException("Agent HTTP " + status + " correlationId=" + correlationId,
170+
null, failureSnapshot(status, Outcome.HTTP_FAILURE, respBody));
171+
}
172+
return mapResponse(status, respBody, correlationId);
168173
}
169-
return mapResponse(status, respBody, correlationId);
170174
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
171175
log.warn("Agent response parse failed correlationId={}", correlationId);
172176
throw failure("Failed to parse agent response", correlationId);
@@ -232,12 +236,23 @@ public void close() {
232236
if (Objects.nonNull(client)) {
233237
try {
234238
client.close();
235-
} catch (IOException e) {
239+
} catch (IOException | RuntimeException e) {
236240
log.warn("Agent HTTP transport close failed");
237241
}
238242
}
239243
}
240244

245+
private static void closeResponse(CloseableHttpResponse response) throws IOException {
246+
try {
247+
response.close();
248+
} catch (SocketTimeoutException | ConnectTimeoutException e) {
249+
throw new SocketTimeoutException("Agent HTTP response close timed out");
250+
} catch (IOException | RuntimeException e) {
251+
// The cleanup exception can be suppressed onto a public protocol failure.
252+
throw new IOException("Agent HTTP response close failed");
253+
}
254+
}
255+
241256
private static Optional<byte[]> readBoundedBody(HttpEntity entity, int limit) throws IOException {
242257
if (Objects.isNull(entity)) {
243258
return Optional.of(new byte[0]);

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

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,13 @@
2828
import java.io.PrintStream;
2929
import java.io.PrintWriter;
3030
import java.io.StringWriter;
31+
import java.lang.reflect.Field;
3132
import java.net.InetSocketAddress;
3233
import java.nio.charset.StandardCharsets;
3334
import java.nio.file.Path;
3435
import java.time.Duration;
3536
import java.util.Arrays;
37+
import java.util.Map;
3638
import java.util.Objects;
3739
import java.util.Scanner;
3840
import java.util.UUID;
@@ -44,6 +46,16 @@
4446
import java.util.regex.Pattern;
4547
import java.util.zip.GZIPOutputStream;
4648
import javax.net.ssl.SSLContext;
49+
import org.apache.http.HttpHost;
50+
import org.apache.http.HttpRequest;
51+
import org.apache.http.ProtocolVersion;
52+
import org.apache.http.client.methods.CloseableHttpResponse;
53+
import org.apache.http.conn.ClientConnectionManager;
54+
import org.apache.http.entity.StringEntity;
55+
import org.apache.http.impl.client.CloseableHttpClient;
56+
import org.apache.http.message.BasicHttpResponse;
57+
import org.apache.http.params.HttpParams;
58+
import org.apache.http.protocol.HttpContext;
4759
import org.junit.jupiter.api.Assertions;
4860
import org.junit.jupiter.api.Test;
4961
import org.junit.jupiter.api.io.TempDir;
@@ -554,6 +566,124 @@ void nonSuccessHttpResponseDoesNotExposeBodyCanaryInException() throws IOExcepti
554566
}
555567
}
556568

569+
@Test
570+
void requestSerializationFailureIsPrivateAndNeverDispatched() throws IOException {
571+
String canary = "serialization-private-" + UUID.randomUUID();
572+
try (JsonCollectStub stub = JsonCollectStub.start("{\"success\":true}");
573+
OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(baseProps(stub.port()))) {
574+
OpenCliCollectRequest request = new OpenCliCollectRequest() {
575+
@Override
576+
public Map<String, Object> getArgs() {
577+
throw new IllegalStateException(canary);
578+
}
579+
};
580+
ByteArrayOutputStream diagnostics = new ByteArrayOutputStream();
581+
PrintStream previous = System.err;
582+
OpenCliExecutableFailureException failure;
583+
try (PrintStream capture = new PrintStream(diagnostics, true, StandardCharsets.UTF_8.name())) {
584+
System.setErr(capture);
585+
try {
586+
failure = Assertions.assertThrows(OpenCliExecutableFailureException.class, () -> client.collect(request));
587+
failure.printStackTrace(capture);
588+
} finally {
589+
System.setErr(previous);
590+
}
591+
}
592+
String output = diagnostics.toString(StandardCharsets.UTF_8.name());
593+
Assertions.assertTrue(failure.getMessage().contains("Failed to serialize collect request"));
594+
Assertions.assertTrue(output.contains("Agent request serialization failed correlationId="));
595+
Assertions.assertFalse(output.contains(canary));
596+
Assertions.assertEquals(0, stub.requests());
597+
}
598+
}
599+
600+
@ParameterizedTest
601+
@ValueSource(booleans = {false, true})
602+
void responseCloseFailureProtectsProviderDetailsAndPrimaryOutcome(boolean validEnvelope) throws Exception {
603+
String canary = "response-close-private-" + UUID.randomUUID();
604+
String body = validEnvelope ? "{\"success\":true}" : "null";
605+
CloseFailureResponse response = new CloseFailureResponse(body, canary);
606+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(baseProps(1))) {
607+
setTransport(client, response, null);
608+
OpenCliExecutableFailureException failure = Assertions.assertThrows(
609+
OpenCliExecutableFailureException.class, () -> client.collect(new OpenCliCollectRequest()));
610+
OpenCliRemoteExecutionDetails details = failure.getPartialResult().getRemoteExecutionDetails();
611+
Assertions.assertEquals(200, details.getHttpStatus());
612+
Assertions.assertEquals(validEnvelope ? Outcome.TRANSPORT_FAILURE : Outcome.PROTOCOL_FAILURE, details.getOutcome());
613+
Assertions.assertEquals(1, response.closeCalls);
614+
StringWriter stack = new StringWriter();
615+
failure.printStackTrace(new PrintWriter(stack));
616+
Assertions.assertFalse(stack.toString().contains(canary));
617+
}
618+
}
619+
620+
@Test
621+
void transportCloseFailureDoesNotExposeProviderDetails() throws Exception {
622+
String canary = "transport-close-private-" + UUID.randomUUID();
623+
OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(baseProps(1));
624+
setTransport(client, null, new IllegalStateException(canary));
625+
ByteArrayOutputStream diagnostics = new ByteArrayOutputStream();
626+
PrintStream previous = System.err;
627+
try (PrintStream capture = new PrintStream(diagnostics, true, StandardCharsets.UTF_8.name())) {
628+
System.setErr(capture);
629+
try {
630+
Assertions.assertDoesNotThrow(client::close);
631+
} finally {
632+
System.setErr(previous);
633+
}
634+
}
635+
String output = diagnostics.toString(StandardCharsets.UTF_8.name());
636+
Assertions.assertTrue(output.contains("Agent HTTP transport close failed"));
637+
Assertions.assertFalse(output.contains(canary));
638+
}
639+
640+
// Replace the native provider to inject close faults that a loopback server cannot reliably schedule.
641+
private static void setTransport(OpenCliRemoteAgentHttpClient client, CloseableHttpResponse response,
642+
RuntimeException shutdownFailure) throws ReflectiveOperationException {
643+
Field transport = OpenCliRemoteAgentHttpClient.class.getDeclaredField("transport");
644+
transport.setAccessible(true);
645+
transport.set(client, new CloseableHttpClient() {
646+
@Override
647+
protected CloseableHttpResponse doExecute(HttpHost host, HttpRequest request, HttpContext context) {
648+
return response;
649+
}
650+
651+
@Override
652+
public HttpParams getParams() {
653+
throw new UnsupportedOperationException();
654+
}
655+
656+
@Override
657+
public ClientConnectionManager getConnectionManager() {
658+
throw new UnsupportedOperationException();
659+
}
660+
661+
@Override
662+
public void close() {
663+
if (Objects.nonNull(shutdownFailure)) {
664+
throw shutdownFailure;
665+
}
666+
}
667+
});
668+
}
669+
670+
private static final class CloseFailureResponse extends BasicHttpResponse implements CloseableHttpResponse {
671+
private final String canary;
672+
private int closeCalls;
673+
674+
private CloseFailureResponse(String body, String canary) {
675+
super(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
676+
this.canary = canary;
677+
setEntity(new StringEntity(body, StandardCharsets.UTF_8));
678+
}
679+
680+
@Override
681+
public void close() throws IOException {
682+
closeCalls++;
683+
throw new IOException(canary);
684+
}
685+
}
686+
557687
@Test
558688
void malformedHttpEndpointDoesNotExposeCredentialsInPublicStackTrace() {
559689
String credential = "private-" + UUID.randomUUID();

0 commit comments

Comments
 (0)