Skip to content

Commit 0b4b0c8

Browse files
committed
Correlate OpenCLI reverse WebSocket diagnostics safely
1 parent 5bee58b commit 0b4b0c8

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
- [ ] 2.3 保留raw业务结果与默认关闭的HTTPdebugcapture,新增显式有限export策略。
1717

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

5959
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 线上字段和本地子进程调用。
60+
61+
62+
## WebSocket 连接关联与日志调用点核对
63+
64+
OC-PRIV-001/004。Java 17 基线 `0b7091c` 的 TLS 重连用例中缺少连接关联 ID。实现为每次反向连接尝试生成独立 UUID,同一连接的建立、校验失败、回调、收集失败、投递失败和关闭失败日志复用该值。连接协议、业务结果和去重键各自沿用原值。TLS 回归注入包含测试标记的投递失败,验证原连接与失败日志共享 ID,重连使用新 ID,并保留显式重试和结果去重断言。
65+
66+
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 失败,修改后三线全量均通过。
67+
68+
| SDK 发出日志的位置 | 调用点数 | 允许的动态值 | 运行证据 |
69+
| --- | ---: | --- | --- |
70+
| 本地执行器、适配器、浏览器命令入口 | 3 | 随机关联 ID、终止原因、退出码、字节数或参数个数 | `OpenCliProcessPrivacyTest` 与全量浏览器调用 |
71+
| JSON 输出检测、远端 argv 转换 | 2 | 长度或参数个数 | `OpenCliStdoutJsonTest`、`OpenCliArgvToCollectParserTest` |
72+
| HTTP 客户端 | 10 | 随机关联 ID、HTTP 状态、长度 | `OpenCliRemoteAgentHttpClientTest`,七个调用点实际执行 |
73+
| 反向 WebSocket 客户端 | 9 | 连接 UUID 或重连次数 | `OpenCliWsReverseAgentSessionTest`、`OpenCliWsReverseAgentClientTest`,七个调用点实际执行 |
74+
75+
每线当前 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
@@ -23,6 +23,7 @@
2323
import java.util.Map;
2424
import java.util.Objects;
2525
import java.util.Set;
26+
import java.util.UUID;
2627
import java.util.concurrent.BlockingQueue;
2728
import java.util.concurrent.CountDownLatch;
2829
import java.util.concurrent.LinkedBlockingQueue;
@@ -74,7 +75,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
7475

7576
private volatile boolean shutdownRequested;
7677

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

7980
private Thread runnerThread;
8081
private boolean stopping;
@@ -135,7 +136,7 @@ public synchronized void start() {
135136
*/
136137
public void stop() {
137138
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
138-
WebSocketClient client;
139+
WorkerSession client;
139140
Thread runner;
140141
synchronized (this) {
141142
if (shutdownRequested || collectPool.isShutdown()) {
@@ -170,7 +171,7 @@ public void stop() {
170171
@Override
171172
public void close() {
172173
long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
173-
WebSocketClient client;
174+
WorkerSession client;
174175
Thread runner;
175176
synchronized (this) {
176177
if (collectPool.isShutdown()) {
@@ -197,10 +198,10 @@ public void close() {
197198
}
198199

199200
// The caller holds this worker's monitor while invalidating admission and the queue.
200-
private WebSocketClient stopAdmission() {
201+
private WorkerSession stopAdmission() {
201202
shutdownRequested = true;
202203
admissionEpoch++;
203-
WebSocketClient client = activeClient.getAndSet(null);
204+
WorkerSession client = activeClient.getAndSet(null);
204205
List<Runnable> pending = new ArrayList<>();
205206
collectPool.getQueue().drainTo(pending);
206207
for (Runnable waiting : pending) {
@@ -229,16 +230,17 @@ private void runLoop() {
229230
int attempt = 0;
230231
while (!shutdownRequested) {
231232
attempt++;
233+
UUID correlationId = UUID.randomUUID();
232234
try {
233-
runOneSession();
235+
runOneSession(correlationId);
234236
attempt = 0;
235237
} catch (InterruptedException e) {
236238
Thread.currentThread().interrupt();
237239
log.info("opencli ws agent runner interrupted");
238240
break;
239241
} catch (Exception e) {
240242
if (!shutdownRequested) {
241-
log.warn("opencli ws session failed attempt={}", attempt);
243+
log.warn("opencli ws session failed correlationId={} attempt={}", correlationId, attempt);
242244
}
243245
}
244246
if (shutdownRequested) {
@@ -259,15 +261,15 @@ private void runLoop() {
259261
log.info("opencli ws agent runner stopped");
260262
}
261263

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

269-
log.info("opencli ws connecting");
270-
WorkerSession client = new WorkerSession(endpoint, centerIdentity);
271+
log.info("opencli ws connecting correlationId={}", correlationId);
272+
WorkerSession client = new WorkerSession(endpoint, centerIdentity, correlationId);
271273
if (!publishSession(client)) {
272274
return;
273275
}
@@ -298,14 +300,16 @@ private enum SessionPhase {
298300

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

306-
WorkerSession(URI endpoint, Object centerIdentity) {
309+
WorkerSession(URI endpoint, Object centerIdentity, UUID correlationId) {
307310
super(endpoint, new Draft_6455(Collections.emptyList(), maxInboundMessageBytes));
308311
this.centerIdentity = centerIdentity;
312+
this.correlationId = correlationId;
309313
}
310314

311315
@Override
@@ -327,7 +331,7 @@ public void onMessage(String message) {
327331
try {
328332
handleTextMessage(this, message);
329333
} catch (Exception e) {
330-
log.warn("handle ws message failed");
334+
log.warn("handle ws message failed correlationId={}", correlationId);
331335
}
332336
}
333337

@@ -338,7 +342,7 @@ public void onClose(int code, String reason, boolean remote) {
338342

339343
@Override
340344
public void onError(Exception ex) {
341-
log.warn("WebSocket error");
345+
log.warn("WebSocket error correlationId={}", correlationId);
342346
retire(ex);
343347
}
344348

@@ -363,23 +367,23 @@ void retire(Throwable cause) {
363367
}
364368
}
365369

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

374-
private boolean isCurrentSession(WebSocketClient client) {
378+
private boolean isCurrentSession(WorkerSession client) {
375379
return !shutdownRequested && activeClient.get() == client;
376380
}
377381

378-
private static void closeSession(WebSocketClient client) {
382+
private static void closeSession(WorkerSession client) {
379383
try {
380384
client.close();
381385
} catch (Exception e) {
382-
log.debug("ws session close failed");
386+
log.debug("ws session close failed correlationId={}", client.correlationId);
383387
}
384388
}
385389

@@ -524,7 +528,7 @@ public void run() {
524528
ObjectNode response = null;
525529
try {
526530
if (mayStartCollect(epoch)) {
527-
response = executeCollect(key.requestId(), message, cancellation);
531+
response = executeCollect(key.requestId(), message, cancellation, socket.correlationId);
528532
}
529533
} finally {
530534
finishCollect(this, response);
@@ -535,7 +539,8 @@ public void run() {
535539
}
536540
}
537541

538-
private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancellationToken cancellation) {
542+
private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancellationToken cancellation,
543+
UUID correlationId) {
539544
try {
540545
String site = msg.path("site").asText("");
541546
String command = msg.path("command").asText("");
@@ -557,7 +562,7 @@ private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancell
557562
? partial.getStderr() : e.getMessage();
558563
return result(requestId, false, Collections.emptyList(), err);
559564
} catch (Exception e) {
560-
log.warn("collect execution failed");
565+
log.warn("collect execution failed correlationId={}", correlationId);
561566
return result(requestId, false, Collections.emptyList(), "collect execution failed");
562567
}
563568
}
@@ -629,7 +634,7 @@ private void sendResult(WorkerSession ws, ObjectNode result) {
629634
try {
630635
resultSender.accept(ws, MAPPER.writeValueAsString(result));
631636
} catch (Exception e) {
632-
log.error("failed to send WS result");
637+
log.error("failed to send WS result correlationId={}", ws.correlationId);
633638
ws.retire(e);
634639
closeSession(ws);
635640
}

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