Skip to content

Commit a0ba264

Browse files
committed
Sanitize OpenCLI HTTP cleanup exceptions
1 parent 0b4b0c8 commit a0ba264

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
@@ -73,3 +73,9 @@ Java 8 `cd1ceac`、Java 17 `0b7091c`、Java 21 `5bee58b` 是本轮修改前基
7373
| 反向 WebSocket 客户端 | 9 | 连接 UUID 或重连次数 | `OpenCliWsReverseAgentSessionTest`、`OpenCliWsReverseAgentClientTest`,七个调用点实际执行 |
7474

7575
每线当前 JaCoCo 报告均覆盖 24 个 SDK 日志调用点中的 19 个。仍缺独立驱动 HTTP 请求序列化失败、外层 JSON 映射失败、HTTP transport 关闭失败、WebSocket onError 及 WebSocket 关闭抛异常的动态证据。源码核对确认这些日志也使用固定消息或 SDK 生成的 ID,JaCoCo 缺口由 1.1 和 2.2 继续跟踪。该核对限于 SDK 自身的日志调用与实测异常。
76+
77+
## HTTP 资源关闭异常的隐私回归
78+
79+
OC-PRIV-002/006。Java 17 基线 `ddfa6c8` 的四个定向用例有两个失败。无效响应的协议异常附带了原始 HTTP 响应关闭异常,公开异常栈包含测试标记。连接池关闭的运行时异常也直接暴露了标记。响应清理现在仅传播固定消息,协议失败保留主要类别和 HTTP 200。单独发生的响应关闭 I/O 故障保留传输失败及已观察到的状态,关闭超时沿用超时分类。连接池关闭失败使用固定日志。请求序列化的独立回归确认测试标记未出现在日志或异常栈,回环服务接收请求数为 0。
80+
81+
三线分别以 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
@@ -20,6 +20,7 @@
2020
import io.github.easy4j.opencli.parser.OpenCliParsedFields;
2121
import io.github.easy4j.opencli.util.OpenCliStrings;
2222
import java.io.ByteArrayOutputStream;
23+
import java.io.Closeable;
2324
import java.io.IOException;
2425
import java.io.InputStream;
2526
import java.net.SocketTimeoutException;
@@ -139,35 +140,38 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
139140

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

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