Skip to content

Commit 89da70e

Browse files
committed
Complete OpenCLI provider diagnostic verification
1 parent a0ba264 commit 89da70e

5 files changed

Lines changed: 160 additions & 7 deletions

File tree

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@
66

77
## 1. 泄露负例
88

9-
- [ ] 1.1 对Executor、AdapterChannel、HTTP、WS、JSON/YAML parser所有日志/异常点建立canary矩阵。
9+
- [x] 1.1 对Executor、AdapterChannel、HTTP、WS、JSON/YAML parser所有日志/异常点建立canary矩阵。见本页失败场景与 24 个日志调用点的证据。
1010
- [x] 1.2 新增完整日志捕获与nested cause测试,先证明当前泄露可被测试检测。
1111

1212
## 2. 安全投影
1313

1414
- [x] 2.1 将commandLine/args/bodyPreview/remote error输出改成允许表元数据与correlationId。见本文日志调用点核对。
15-
- [ ] 2.2 实现安全异常摘要和cause处理,避免logger输出provider原始对象。
15+
- [x] 2.2 实现安全异常摘要和cause处理,避免logger输出provider原始对象。见本页的异常链、HTTP 清理及响应映射、WebSocket 故障注入回归。
1616
- [ ] 2.3 保留raw业务结果与默认关闭的HTTPdebugcapture,新增显式有限export策略。
1717

1818
## 3. 验证
@@ -79,3 +79,12 @@ Java 8 `cd1ceac`、Java 17 `0b7091c`、Java 21 `5bee58b` 是本轮修改前基
7979
OC-PRIV-002/006。Java 17 基线 `ddfa6c8` 的四个定向用例有两个失败。无效响应的协议异常附带了原始 HTTP 响应关闭异常,公开异常栈包含测试标记。连接池关闭的运行时异常也直接暴露了标记。响应清理现在仅传播固定消息,协议失败保留主要类别和 HTTP 200。单独发生的响应关闭 I/O 故障保留传输失败及已观察到的状态,关闭超时沿用超时分类。连接池关闭失败使用固定日志。请求序列化的独立回归确认测试标记未出现在日志或异常栈,回环服务接收请求数为 0。
8080

8181
三线分别以 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 关闭抛异常仍待动态证据。
82+
83+
84+
## HTTP 响应映射与 WebSocket provider 异常
85+
86+
OC-PRIV-001/002/003/006。HTTP 夹具返回合法响应并使用 Jackson 的实际写入深度约束触发 items 映射失败。Java 17 在原分类逻辑下抛出没有状态证据的通用异常。修复后保留 HTTP 200、`PROTOCOL_FAILURE`、显式捕获的原响应及空退出码。公开异常栈和 SDK 日志只使用固定诊断和关联 ID。数组和其他有效 `items` 使用同一 Jackson writer,普通协议回归仍通过。
87+
88+
真实回环 WebSocket 连接收到注入的 provider error 回调后,旧连接退出,新连接完成注册与 ping/pong。错误日志保留旧连接关联 ID,隐藏 provider 测试标记。另一用例在无网络连接的 Java-WebSocket 1.6.0 夹具上注入底层 close 异常。SDK 清空接单连接,只调用一次关闭,关闭后拒绝重启,DEBUG 日志保留关联 ID。该用例验证 SDK 的错误处理,实际套接字关闭由其他回环测试验证。
89+
90+
Java 8 `f4c6677`、Java 17 `6894071`、Java 21 `a0ba264` 是修改前基线。三线各使用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,251、2,252、2,251 项,零失败、零错误、零跳过。三份报告均执行了新增的三项回归,JaCoCo 显示每线 24 个 SDK 日志调用点均被执行。此前各节保留供应商原文、异常链、日志与应用显式读取原始结果的证据边界。

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

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import tools.jackson.databind.DeserializationFeature;
55
import tools.jackson.databind.JsonNode;
66
import tools.jackson.databind.ObjectReader;
7+
import tools.jackson.databind.ObjectWriter;
78
import tools.jackson.databind.json.JsonMapper;
89
import io.github.easy4j.opencli.OpenCliProperties;
910
import io.github.easy4j.opencli.OpenCliRemoteAuthentication;
@@ -65,6 +66,7 @@ public final class OpenCliRemoteAgentHttpClient implements AutoCloseable {
6566
}
6667

6768
private final OpenCliProperties properties;
69+
private final ObjectWriter responseItemsWriter = MAPPER.writerWithDefaultPrettyPrinter();
6870

6971
private final Object transportLock = new Object();
7072
private CloseableHttpClient transport;
@@ -172,9 +174,6 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
172174
}
173175
return mapResponse(status, respBody, correlationId);
174176
}
175-
} catch (JacksonException e) {
176-
log.warn("Agent response parse failed correlationId={}", correlationId);
177-
throw failure("Failed to parse agent response", correlationId);
178177
} catch (SocketTimeoutException | ConnectTimeoutException e) {
179178
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
180179
} catch (IOException e) {
@@ -328,8 +327,13 @@ private OpenCliResult mapResponse(int status, String respBody, String correlatio
328327
stdout = "[]";
329328
itemsSource = items.isMissingNode() ? ItemsSource.ABSENT_DEFAULT : ItemsSource.NULL_DEFAULT;
330329
} else {
331-
stdout = items.isArray() ? MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(items)
332-
: items.toPrettyString();
330+
try {
331+
stdout = responseItemsWriter.writeValueAsString(items);
332+
} catch (JacksonException e) {
333+
log.warn("Agent response items mapping failed correlationId={} status={}", correlationId, status);
334+
throw new OpenCliRemoteProtocolException("Failed to map agent response items", correlationId,
335+
failureSnapshot(status, Outcome.PROTOCOL_FAILURE, respBody));
336+
}
333337
itemsSource = ItemsSource.RESPONSE;
334338
}
335339
OpenCliParsedFields parsed = OpenCliOutputParser.parseBestEffort(stdout, err);

‎src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,12 @@
1010
import java.io.ByteArrayOutputStream;
1111
import java.io.PrintStream;
1212
import java.io.File;
13+
import java.io.IOException;
1314
import tools.jackson.core.JacksonException;
15+
import java.lang.reflect.Constructor;
16+
import java.lang.reflect.Field;
1417
import java.net.InetSocketAddress;
18+
import java.net.URI;
1519
import java.nio.ByteBuffer;
1620
import java.nio.charset.StandardCharsets;
1721
import java.nio.file.Files;
@@ -28,12 +32,16 @@
2832
import java.util.concurrent.LinkedBlockingQueue;
2933
import java.util.concurrent.TimeUnit;
3034
import java.util.concurrent.atomic.AtomicBoolean;
35+
import java.util.concurrent.atomic.AtomicInteger;
3136
import java.util.concurrent.atomic.AtomicReference;
3237
import java.util.regex.Matcher;
3338
import java.util.regex.Pattern;
3439
import java.util.stream.Collectors;
3540
import javax.net.ssl.SSLContext;
3641
import org.java_websocket.WebSocket;
42+
import org.java_websocket.WebSocketImpl;
43+
import org.java_websocket.client.WebSocketClient;
44+
import org.java_websocket.drafts.Draft_6455;
3745
import org.java_websocket.enums.Opcode;
3846
import org.java_websocket.handshake.ClientHandshake;
3947
import org.java_websocket.server.DefaultSSLWebSocketServerFactory;
@@ -59,6 +67,105 @@ class OpenCliWsReverseAgentSessionTest {
5967
private static final JsonMapper MAPPER = new JsonMapper();
6068
private static final String AGENT_URL = "http://127.0.0.1:19823";
6169

70+
@Test
71+
void providerErrorRetiresConnectionWithoutLoggingItsCause() throws Exception {
72+
String canary = "websocket-error-private-" + UUID.randomUUID();
73+
ByteArrayOutputStream diagnostics = new ByteArrayOutputStream();
74+
PrintStream previous = System.err;
75+
try (LocalCenter center = new LocalCenter();
76+
OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
77+
probe(ContractProbe.class.getName()), center.agentProperties());
78+
PrintStream capture = new PrintStream(diagnostics, true, StandardCharsets.UTF_8.name())) {
79+
System.setErr(capture);
80+
try {
81+
agent.start();
82+
WebSocket first = center.receive("register").socket;
83+
first.send("{\"type\":\"registered\"}");
84+
first.send("{\"type\":\"ping\"}");
85+
center.receive("pong");
86+
WebSocketClient provider = activeSession(agent).get();
87+
assertNotNull(provider);
88+
provider.onWebsocketError(provider.getConnection(), new IOException(canary));
89+
90+
WebSocket second = center.receive("register").socket;
91+
assertNotSame(first, second);
92+
second.send("{\"type\":\"registered\"}");
93+
second.send("{\"type\":\"ping\"}");
94+
center.receive("pong");
95+
} finally {
96+
System.setErr(previous);
97+
}
98+
}
99+
String logText = diagnostics.toString(StandardCharsets.UTF_8.name());
100+
Matcher connecting = Pattern.compile("opencli ws connecting correlationId=([a-f0-9-]+)").matcher(logText);
101+
assertTrue(connecting.find());
102+
UUID firstId = UUID.fromString(connecting.group(1));
103+
assertTrue(connecting.find());
104+
assertFalse(firstId.equals(UUID.fromString(connecting.group(1))));
105+
assertTrue(logText.contains("WebSocket error correlationId=" + firstId));
106+
assertFalse(logText.contains(canary));
107+
}
108+
109+
@Test
110+
void providerCloseFailureClearsAdmissionWithoutLoggingItsCause() throws Exception {
111+
String canary = "websocket-close-private-" + UUID.randomUUID();
112+
UUID correlationId = UUID.randomUUID();
113+
AtomicInteger closes = new AtomicInteger();
114+
ByteArrayOutputStream diagnostics = new ByteArrayOutputStream();
115+
PrintStream previous = System.err;
116+
try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
117+
probe(ContractProbe.class.getName()), new OpenCliWsAgentConnectionProperties());
118+
PrintStream capture = new PrintStream(diagnostics, true, StandardCharsets.UTF_8.name())) {
119+
WebSocketClient provider = closeFailureProvider(agent, correlationId, canary, closes);
120+
activeSession(agent).set(provider);
121+
System.setErr(capture);
122+
try {
123+
agent.close();
124+
agent.close();
125+
assertNull(activeSession(agent).get());
126+
assertEquals(1, closes.get());
127+
assertThrows(IllegalStateException.class, agent::start);
128+
} finally {
129+
System.setErr(previous);
130+
}
131+
}
132+
String logText = diagnostics.toString(StandardCharsets.UTF_8.name());
133+
assertTrue(logText.contains("ws session close failed correlationId=" + correlationId));
134+
assertFalse(logText.contains(canary));
135+
}
136+
137+
@SuppressWarnings("unchecked")
138+
private static AtomicReference<WebSocketClient> activeSession(OpenCliWsReverseAgentClient agent)
139+
throws ReflectiveOperationException {
140+
Field active = OpenCliWsReverseAgentClient.class.getDeclaredField("activeClient");
141+
active.setAccessible(true);
142+
return (AtomicReference<WebSocketClient>) active.get(agent);
143+
}
144+
145+
// Fail Java-WebSocket's close hook without replacing the SDK's session lifecycle or opening a socket.
146+
private static WebSocketClient closeFailureProvider(OpenCliWsReverseAgentClient agent, UUID correlationId,
147+
String canary, AtomicInteger closes) throws ReflectiveOperationException {
148+
Class<?> worker = Class.forName(OpenCliWsReverseAgentClient.class.getName() + "$WorkerSession");
149+
Constructor<?> constructor = worker.getDeclaredConstructor(
150+
OpenCliWsReverseAgentClient.class, URI.class, Object.class, UUID.class);
151+
constructor.setAccessible(true);
152+
WebSocketClient provider = (WebSocketClient) constructor.newInstance(
153+
agent, URI.create("ws://127.0.0.1:1"), new Object(), correlationId);
154+
Field engine = WebSocketClient.class.getDeclaredField("engine");
155+
engine.setAccessible(true);
156+
engine.set(provider, new WebSocketImpl(provider, new Draft_6455()) {
157+
@Override
158+
public void close(int code) {
159+
closes.incrementAndGet();
160+
throw new IllegalStateException(canary);
161+
}
162+
});
163+
Field writer = WebSocketClient.class.getDeclaredField("writeThread");
164+
writer.setAccessible(true);
165+
writer.set(provider, new Thread());
166+
return provider;
167+
}
168+
62169
@Test
63170
void stopDuringConnectionSetupDoesNotPublishAnotherGeneration() throws Exception {
64171
CountDownLatch resolving = new CountDownLatch(1);

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@
4646
import java.util.regex.Pattern;
4747
import java.util.zip.GZIPOutputStream;
4848
import javax.net.ssl.SSLContext;
49+
import tools.jackson.core.StreamWriteConstraints;
50+
import tools.jackson.core.json.JsonFactory;
51+
import tools.jackson.databind.json.JsonMapper;
4952
import org.apache.http.HttpHost;
5053
import org.apache.http.HttpRequest;
5154
import org.apache.http.ProtocolVersion;
@@ -617,6 +620,35 @@ void responseCloseFailureProtectsProviderDetailsAndPrimaryOutcome(boolean validE
617620
}
618621
}
619622

623+
@Test
624+
void responseItemsMappingFailureKeepsStatusAndProtectsDiagnostic() throws Exception {
625+
String body = "{\"success\":true,\"items\":[[\"mapping-private-canary\"]]}";
626+
try (JsonCollectStub stub = JsonCollectStub.start(body)) {
627+
OpenCliProperties properties = baseProps(stub.port());
628+
properties.setRemoteCaptureRawHttpResponse(true);
629+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(properties)) {
630+
JsonFactory factory = JsonFactory.builder()
631+
.streamWriteConstraints(StreamWriteConstraints.builder().maxNestingDepth(1).build()).build();
632+
Field writer = OpenCliRemoteAgentHttpClient.class.getDeclaredField("responseItemsWriter");
633+
writer.setAccessible(true);
634+
writer.set(client, JsonMapper.builder(factory).build().writerWithDefaultPrettyPrinter());
635+
636+
OpenCliRemoteProtocolException failure = Assertions.assertThrows(
637+
OpenCliRemoteProtocolException.class,
638+
() -> client.collect(new OpenCliCollectRequest()));
639+
OpenCliResult partial = failure.getPartialResult();
640+
Assertions.assertEquals(200, partial.getRemoteExecutionDetails().getHttpStatus());
641+
Assertions.assertEquals(Outcome.PROTOCOL_FAILURE, partial.getRemoteExecutionDetails().getOutcome());
642+
Assertions.assertNull(partial.getExitCode());
643+
Assertions.assertEquals(body, partial.getRemoteRawHttpBody());
644+
StringWriter stack = new StringWriter();
645+
failure.printStackTrace(new PrintWriter(stack));
646+
Assertions.assertFalse(stack.toString().contains("mapping-private-canary"));
647+
Assertions.assertEquals(1, stub.requests());
648+
}
649+
}
650+
}
651+
620652
@Test
621653
void transportCloseFailureDoesNotExposeProviderDetails() throws Exception {
622654
String canary = "transport-close-private-" + UUID.randomUUID();

‎src/test/resources/simplelogger.properties‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ org.slf4j.simpleLogger.log.io.github.easy4j.opencli.remote.OpenCliArgvToCollectP
33
org.slf4j.simpleLogger.log.io.github.easy4j.opencli.parser.OpenCliStdoutJson=debug
44
org.slf4j.simpleLogger.log.io.github.easy4j.opencli.core.OpenCliAdapterChannel=debug
55
org.slf4j.simpleLogger.log.io.github.easy4j.opencli.core.OpenCliExecutor=debug
6+
org.slf4j.simpleLogger.log.io.github.easy4j.opencli.center.ws.OpenCliWsReverseAgentClient=debug

0 commit comments

Comments
 (0)