Skip to content

Commit ddfa6c8

Browse files
committed
Correlate OpenCLI reverse WebSocket diagnostics safely
1 parent 0b7091c commit ddfa6c8

3 files changed

Lines changed: 53 additions & 23 deletions

File tree

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
## 2. 安全投影
1313

14-
- [ ] 2.1 将commandLine/args/bodyPreview/remote error输出改成允许表元数据与correlationId。
14+
- [x] 2.1 将commandLine/args/bodyPreview/remote error输出改成允许表元数据与correlationId。见本文日志调用点核对。
1515
- [ ] 2.2 实现安全异常摘要和cause处理,避免logger输出provider原始对象。
1616
- [x] 2.3 保留raw业务结果与默认关闭的HTTPdebugcapture,新增显式有限export策略。
1717

@@ -73,3 +73,19 @@ OC-PRIV-001/004。Java 17 基线 `58f675a` 的两项回归均失败。输出 `Op
7373
OC-PRIV-001/003/004。Java 17 基线 `c6dc643` 的两项回归均失败。HTTP 收集 DTO 和生成的构建器会将命令、选项、位置参数和 CDP 地址拼进字符串,结构化本地请求构建器也会拼入命令及参数。三个默认字符串只保留类型名称。请求值仍由原访问器和协议序列化读取,结构化命令生成相同的字面 argv。
7474

7575
Java 8 `15ef02a`、Java 17 `c6dc643`、Java 21 `d0f0205` 为回归前基线。三线各自用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,244、2,245、2,244 项,零失败、零错误、零跳过。新增用例见 `OpenCliCollectRequestTest` 和 `OpenCliAdapterCommandRequestTest` 的 Surefire XML。全量回归同时覆盖 HTTP 线上字段和本地子进程调用。
76+
77+
78+
## WebSocket 连接关联与日志调用点核对
79+
80+
OC-PRIV-001/004。Java 17 基线 `0b7091c` 的 TLS 重连用例中缺少连接关联 ID。实现为每次反向连接尝试生成独立 UUID,同一连接的建立、校验失败、回调、收集失败、投递失败和关闭失败日志复用该值。连接协议、业务结果和去重键各自沿用原值。TLS 回归注入包含测试标记的投递失败,验证原连接与失败日志共享 ID,重连使用新 ID,并保留显式重试和结果去重断言。
81+
82+
Java 8 `cd1ceac`、Java 17 `0b7091c`、Java 21 `5bee58b` 是本轮修改前基线。三线各使用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,244、2,245、2,244 项,零失败、零错误、零跳过。Java 17 修改前实际执行两个 TLS 参数用例,其中一个因缺少关联 ID 失败,修改后三线全量均通过。
83+
84+
| SDK 发出日志的位置 | 调用点数 | 允许的动态值 | 运行证据 |
85+
| --- | ---: | --- | --- |
86+
| 本地执行器、适配器、浏览器命令入口 | 3 | 随机关联 ID、终止原因、退出码、字节数或参数个数 | `OpenCliProcessPrivacyTest` 与全量浏览器调用 |
87+
| JSON 输出检测、远端 argv 转换 | 2 | 长度或参数个数 | `OpenCliStdoutJsonTest`、`OpenCliArgvToCollectParserTest` |
88+
| HTTP 客户端 | 10 | 随机关联 ID、HTTP 状态、长度 | `OpenCliRemoteAgentHttpClientTest`,七个调用点实际执行 |
89+
| 反向 WebSocket 客户端 | 9 | 连接 UUID 或重连次数 | `OpenCliWsReverseAgentSessionTest`、`OpenCliWsReverseAgentClientTest`,七个调用点实际执行 |
90+
91+
每线当前 JaCoCo 报告均覆盖 24 个 SDK 日志调用点中的 19 个。仍缺独立驱动 HTTP 请求序列化失败、外层 JSON 映射失败、HTTP transport 关闭失败、WebSocket onError 及 WebSocket 关闭抛异常的动态证据。源码核对确认这些日志也使用固定消息或 SDK 生成的 ID,JaCoCo 缺口由 1.1 和 2.2 继续跟踪。该核对限于 SDK 自身的日志调用与实测异常。

‎src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java‎

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.util.Map;
2525
import java.util.Objects;
2626
import java.util.Set;
27+
import java.util.UUID;
2728
import java.util.concurrent.BlockingQueue;
2829
import java.util.concurrent.CountDownLatch;
2930
import java.util.concurrent.LinkedBlockingQueue;
@@ -75,7 +76,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
7576

7677
private volatile boolean shutdownRequested;
7778

78-
private final AtomicReference<WebSocketClient> activeClient = new AtomicReference<>();
79+
private final AtomicReference<WorkerSession> activeClient = new AtomicReference<>();
7980

8081
private Thread runnerThread;
8182
private boolean stopping;
@@ -136,7 +137,7 @@ public synchronized void start() {
136137
*/
137138
public void stop() {
138139
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
139-
WebSocketClient client;
140+
WorkerSession client;
140141
Thread runner;
141142
synchronized (this) {
142143
if (shutdownRequested || collectPool.isShutdown()) {
@@ -171,7 +172,7 @@ public void stop() {
171172
@Override
172173
public void close() {
173174
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
174-
WebSocketClient client;
175+
WorkerSession client;
175176
Thread runner;
176177
synchronized (this) {
177178
if (collectPool.isShutdown()) {
@@ -198,10 +199,10 @@ public void close() {
198199
}
199200

200201
// The caller holds this worker's monitor while invalidating admission and the queue.
201-
private WebSocketClient stopAdmission() {
202+
private WorkerSession stopAdmission() {
202203
shutdownRequested = true;
203204
admissionEpoch++;
204-
WebSocketClient client = activeClient.getAndSet(null);
205+
WorkerSession client = activeClient.getAndSet(null);
205206
List<Runnable> pending = new ArrayList<>();
206207
collectPool.getQueue().drainTo(pending);
207208
for (Runnable waiting : pending) {
@@ -230,16 +231,17 @@ private void runLoop() {
230231
int attempt = 0;
231232
while (!shutdownRequested) {
232233
attempt++;
234+
UUID correlationId = UUID.randomUUID();
233235
try {
234-
runOneSession();
236+
runOneSession(correlationId);
235237
attempt = 0;
236238
} catch (InterruptedException e) {
237239
Thread.currentThread().interrupt();
238240
log.info("opencli ws agent runner interrupted");
239241
break;
240242
} catch (Exception e) {
241243
if (!shutdownRequested) {
242-
log.warn("opencli ws session failed attempt={}", attempt);
244+
log.warn("opencli ws session failed correlationId={} attempt={}", correlationId, attempt);
243245
}
244246
}
245247
if (shutdownRequested) {
@@ -260,15 +262,15 @@ private void runLoop() {
260262
log.info("opencli ws agent runner stopped");
261263
}
262264

263-
private void runOneSession() throws Exception {
265+
private void runOneSession(UUID correlationId) throws Exception {
264266
validateConnectionProperties();
265267
URI endpoint = URI.create(OpenCliCenterWsUrls.toAgentWebSocketUrl(
266268
connectionProperties.getCentralApiBaseUrl(), connectionProperties.getWebSocketPath()));
267269
// The default TLS client verifies the endpoint hostname. Plain WS has session-local identity.
268270
Object centerIdentity = "wss".equalsIgnoreCase(endpoint.getScheme()) ? endpoint : new Object();
269271

270-
log.info("opencli ws connecting");
271-
WorkerSession client = new WorkerSession(endpoint, centerIdentity);
272+
log.info("opencli ws connecting correlationId={}", correlationId);
273+
WorkerSession client = new WorkerSession(endpoint, centerIdentity, correlationId);
272274
if (!publishSession(client)) {
273275
return;
274276
}
@@ -299,14 +301,16 @@ private enum SessionPhase {
299301

300302
private final class WorkerSession extends WebSocketClient {
301303
private final Object centerIdentity;
304+
private final UUID correlationId;
302305
private final AtomicReference<SessionPhase> phase = new AtomicReference<>(SessionPhase.CONNECTING);
303306
private final CountDownLatch registered = new CountDownLatch(1);
304307
private final CountDownLatch sessionClosed = new CountDownLatch(1);
305308
private final AtomicReference<Throwable> handshakeFailure = new AtomicReference<>();
306309

307-
WorkerSession(URI endpoint, Object centerIdentity) {
310+
WorkerSession(URI endpoint, Object centerIdentity, UUID correlationId) {
308311
super(endpoint, new Draft_6455(Collections.emptyList(), maxInboundMessageBytes));
309312
this.centerIdentity = centerIdentity;
313+
this.correlationId = correlationId;
310314
}
311315

312316
@Override
@@ -328,7 +332,7 @@ public void onMessage(String message) {
328332
try {
329333
handleTextMessage(this, message);
330334
} catch (Exception e) {
331-
log.warn("handle ws message failed");
335+
log.warn("handle ws message failed correlationId={}", correlationId);
332336
}
333337
}
334338

@@ -339,7 +343,7 @@ public void onClose(int code, String reason, boolean remote) {
339343

340344
@Override
341345
public void onError(Exception ex) {
342-
log.warn("WebSocket error");
346+
log.warn("WebSocket error correlationId={}", correlationId);
343347
retire(ex);
344348
}
345349

@@ -364,23 +368,23 @@ void retire(Throwable cause) {
364368
}
365369
}
366370

367-
private synchronized boolean publishSession(WebSocketClient client) {
371+
private synchronized boolean publishSession(WorkerSession client) {
368372
if (shutdownRequested) {
369373
return false;
370374
}
371375
activeClient.set(client);
372376
return true;
373377
}
374378

375-
private boolean isCurrentSession(WebSocketClient client) {
379+
private boolean isCurrentSession(WorkerSession client) {
376380
return !shutdownRequested && activeClient.get() == client;
377381
}
378382

379-
private static void closeSession(WebSocketClient client) {
383+
private static void closeSession(WorkerSession client) {
380384
try {
381385
client.close();
382386
} catch (Exception e) {
383-
log.debug("ws session close failed");
387+
log.debug("ws session close failed correlationId={}", client.correlationId);
384388
}
385389
}
386390

@@ -525,7 +529,7 @@ public void run() {
525529
ObjectNode response = null;
526530
try {
527531
if (mayStartCollect(epoch)) {
528-
response = executeCollect(key.requestId(), message, cancellation);
532+
response = executeCollect(key.requestId(), message, cancellation, socket.correlationId);
529533
}
530534
} finally {
531535
finishCollect(this, response);
@@ -536,7 +540,8 @@ public void run() {
536540
}
537541
}
538542

539-
private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancellationToken cancellation) {
543+
private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancellationToken cancellation,
544+
UUID correlationId) {
540545
try {
541546
String site = msg.path("site").asText("");
542547
String command = msg.path("command").asText("");
@@ -558,7 +563,7 @@ private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancell
558563
? partial.getStderr() : e.getMessage();
559564
return result(requestId, false, Collections.emptyList(), err);
560565
} catch (Exception e) {
561-
log.warn("collect execution failed");
566+
log.warn("collect execution failed correlationId={}", correlationId);
562567
return result(requestId, false, Collections.emptyList(), "collect execution failed");
563568
}
564569
}
@@ -632,7 +637,7 @@ private void sendResult(WorkerSession ws, ObjectNode result) {
632637
try {
633638
resultSender.accept(ws, MAPPER.writeValueAsString(result));
634639
} catch (Exception e) {
635-
log.error("failed to send WS result");
640+
log.error("failed to send WS result correlationId={}", ws.correlationId);
636641
ws.retire(e);
637642
closeSession(ws);
638643
}

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,15 @@
2222
import java.util.Set;
2323
import java.util.List;
2424
import java.util.Objects;
25+
import java.util.UUID;
2526
import java.util.concurrent.BlockingQueue;
2627
import java.util.concurrent.CountDownLatch;
2728
import java.util.concurrent.LinkedBlockingQueue;
2829
import java.util.concurrent.TimeUnit;
2930
import java.util.concurrent.atomic.AtomicBoolean;
3031
import java.util.concurrent.atomic.AtomicReference;
32+
import java.util.regex.Matcher;
33+
import java.util.regex.Pattern;
3134
import java.util.stream.Collectors;
3235
import javax.net.ssl.SSLContext;
3336
import org.java_websocket.WebSocket;
@@ -613,7 +616,13 @@ private static void verifyFailedDeliveryReplay(Path temporary, SSLContext tls) t
613616
}
614617
}
615618
String logText = diagnostics.toString(StandardCharsets.UTF_8.name());
616-
assertTrue(logText.contains("failed to send WS result"));
619+
Matcher connecting = Pattern.compile("opencli ws connecting correlationId=([a-f0-9-]+)").matcher(logText);
620+
assertTrue(connecting.find(), "first connection has a safe correlation ID");
621+
UUID firstCorrelationId = UUID.fromString(connecting.group(1));
622+
assertTrue(connecting.find(), "reconnection has a safe correlation ID");
623+
UUID secondCorrelationId = UUID.fromString(connecting.group(1));
624+
assertFalse(firstCorrelationId.equals(secondCorrelationId));
625+
assertTrue(logText.contains("failed to send WS result correlationId=" + firstCorrelationId));
617626
assertFalse(logText.contains(canary));
618627
}
619628

0 commit comments

Comments
 (0)