Skip to content

Commit f0f880b

Browse files
committed
Reject malformed legacy collect response envelopes
Refs #5 (cherry picked from commit cf9360e)
1 parent 2c4ddeb commit f0f880b

6 files changed

Lines changed: 86 additions & 24 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ Configuration is object-based via `OpenCliProperties`:
190190
Notes:
191191

192192
- In remote mode the `stdout` is the JSON `items` the agent returned (parsed into line items per `format`), which may differ from local raw subprocess text; `leadingArguments` are local-only and are not injected on the remote path.
193+
- A legacy HTTP `/collect` reply must contain a JSON boolean `success`. Invalid envelopes raise `OpenCliRemoteProtocolException`, which extends `OpenCliExecutableFailureException`. A valid reply with `success: true` and omitted or null `items` still returns `[]`.
193194
- `execution-target=REMOTE_AGENT_HTTP` makes the availability probe report `SKIPPED_REMOTE_MODE` (treated as startable).
194195

195196
<a id="8-core-usage"></a>

‎README.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ cli.gemini().deepResearch("topic",
189189
注意事项:
190190

191191
- 远程模式下 `stdout` 为 Agent 返回的 `items` 的 JSON(已按 `format` 解析为行列表),与本地原始子进程文本可能不同;`leadingArguments` 等仅影响本地进程拼装,**远程路径不注入**。
192+
- 旧版 HTTP `/collect` 响应须包含 JSON 布尔字段 `success`。无效响应抛出 `OpenCliRemoteProtocolException`,它继承 `OpenCliExecutableFailureException`。当 `success: true` 且 `items` 缺失或为 null 时,仍返回 `[]`。
192193
- `execution-target=REMOTE_AGENT_HTTP` 时可用性探测报告 `SKIPPED_REMOTE_MODE`(视为可启动)。
193194

194195
<a id="8-core-usage"></a>

‎openspec/changes/harden-opencli-remote-collect/tasks.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# C04 Tasks · Legacy HTTP collect 边界与保真
22

3-
> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
3+
> 勾选项具备对应的实现或执行证据。待验收项继续保留。
44
55
关联规范:[spec](specs/opencli-remote-collect/spec.md)。
66

77
## 1. 服务端契约与失败测试
88

9-
- [ ] 1.1 固定 opencli-admin server 协议版本或可控 fixture,标明它不是 jackwener/OpenCLI 的官方 RPC。
9+
- [x] 1.1 固定可控的 legacy `POST /collect` fixture,记录本地桩与上游 CLI 的范围差异。见下方 OC-REMOTE-004 证据。
1010
- [ ] 1.2 对 Browser/root/external/重复flag/负数/--/空值编写“拒绝且零请求”的测试。
1111
- [ ] 1.3 编写 success=false、503、malformed、null、超大body与超时结果未知用例。
1212

@@ -25,3 +25,12 @@
2525
## 证据交付模板(实施时填写)
2626

2727
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
28+
29+
30+
## OC-REMOTE-004 响应校验
31+
32+
`OpenCliRemoteAgentHttpClientTest.JsonCollectStub` 通过本机 HTTP 服务器提供可控的 legacy `POST /collect` 响应。证据只覆盖 SDK 到此测试桩的 HTTP 交互。jackwener/OpenCLI 提供本地 CLI 接口,真实 opencli-admin 部署仍需验收。
33+
34+
JDK 17 基线 `5ac4bb1` 的 20 项用例实际执行,7 项失败。缺少或显式设为 null 的 `success` 被当成业务失败。字符串和数字布尔值、数字 `error`、重复状态字段及拼接文档曾被当成成功。修正后,具备布尔状态字段的单个 JSON 对象才会继续映射结果,无效响应通过 `OpenCliRemoteProtocolException` 保留类别和相关 ID。现有异常父类保持兼容。合法的成功响应允许省略或置空 `items`,空结果仍为 `[]`。
35+
36+
定向测试命令为 `-Dtest=OpenCliRemoteAgentHttpClientTest test`。使用各维护线的 Maven 和 JDK,报告位于 `target/surefire-reports`。Body 大小限制、总超时和退出码来源仍由其他任务验收。
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package io.github.easy4j.opencli.exception;
2+
3+
/** 远端 /collect 响应不符合协议,保留既有远程异常捕获类型。 */
4+
public final class OpenCliRemoteProtocolException extends OpenCliExecutableFailureException {
5+
6+
public OpenCliRemoteProtocolException(String message, String correlationId) {
7+
super(message + " correlationId=" + correlationId, null);
8+
}
9+
}

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

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
package io.github.easy4j.opencli.remote;
22

3-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
43
import tools.jackson.core.JacksonException;
4+
import tools.jackson.databind.DeserializationFeature;
55
import tools.jackson.databind.JsonNode;
6+
import tools.jackson.databind.ObjectReader;
67
import tools.jackson.databind.json.JsonMapper;
78
import io.github.easy4j.opencli.OpenCliProperties;
89
import io.github.easy4j.opencli.core.OpenCliOutputParser;
910
import io.github.easy4j.opencli.core.OpenCliResult;
1011
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
1112
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
13+
import io.github.easy4j.opencli.exception.OpenCliRemoteProtocolException;
1214
import io.github.easy4j.opencli.parser.OpenCliParsedFields;
1315
import io.github.easy4j.opencli.util.OpenCliStrings;
1416
import java.util.Objects;
@@ -42,6 +44,9 @@
4244
public final class OpenCliRemoteAgentHttpClient implements AutoCloseable {
4345

4446
private static final JsonMapper MAPPER = new JsonMapper();
47+
private static final ObjectReader ENVELOPE_READER = MAPPER.reader().with(
48+
DeserializationFeature.FAIL_ON_TRAILING_TOKENS,
49+
DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
4550

4651
private final OpenCliProperties properties;
4752

@@ -158,28 +163,35 @@ private static OpenCliExecutableFailureException failure(String message, String
158163

159164
private OpenCliResult mapResponse(String respBody, String correlationId) {
160165
String rawCapture = captureRawIfEnabled(respBody);
161-
AgentCollectEnvelope env;
166+
JsonNode envelope;
162167
try {
163-
env = MAPPER.readValue(respBody, AgentCollectEnvelope.class);
168+
envelope = ENVELOPE_READER.readTree(respBody);
164169
} catch (JacksonException e) {
165170
log.warn("Agent response envelope parse failed correlationId={} responseChars={}",
166171
correlationId, respBody.length());
167-
throw failure("Failed to parse agent response envelope", correlationId);
172+
throw new OpenCliRemoteProtocolException("Failed to parse agent response envelope", correlationId);
168173
}
169-
if (Objects.isNull(env)) {
170-
log.warn("Agent response envelope missing correlationId={} responseChars={}",
174+
if (Objects.isNull(envelope) || !envelope.isObject() || !envelope.path("success").isBoolean()) {
175+
log.warn("Agent response envelope status invalid correlationId={} responseChars={}",
171176
correlationId, respBody.length());
172-
throw failure("Missing agent response envelope", correlationId);
177+
throw new OpenCliRemoteProtocolException("Invalid agent response envelope status", correlationId);
173178
}
174-
boolean success = Objects.nonNull(env.success) && env.success;
175-
String err = Objects.isNull(env.error) ? "" : env.error;
179+
JsonNode error = envelope.path("error");
180+
if (!error.isMissingNode() && !error.isNull() && !error.isTextual()) {
181+
log.warn("Agent response envelope error field invalid correlationId={} responseChars={}",
182+
correlationId, respBody.length());
183+
throw new OpenCliRemoteProtocolException("Invalid agent response envelope error field", correlationId);
184+
}
185+
boolean success = envelope.path("success").booleanValue();
186+
String err = error.isTextual() ? error.asText() : "";
187+
JsonNode items = envelope.path("items");
176188
String stdout;
177-
if (Objects.isNull(env.items) || env.items.isNull()) {
189+
if (items.isMissingNode() || items.isNull()) {
178190
stdout = "[]";
179-
} else if (env.items.isArray()) {
180-
stdout = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(env.items);
191+
} else if (items.isArray()) {
192+
stdout = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(items);
181193
} else {
182-
stdout = env.items.toPrettyString();
194+
stdout = items.toPrettyString();
183195
}
184196
OpenCliParsedFields parsed = OpenCliOutputParser.parseBestEffort(stdout, err);
185197
if (!success) {
@@ -216,13 +228,4 @@ private String captureRawIfEnabled(String respBody) {
216228
return respBody;
217229
}
218230

219-
@JsonIgnoreProperties(ignoreUnknown = true)
220-
private static final class AgentCollectEnvelope {
221-
222-
public Boolean success;
223-
224-
public JsonNode items;
225-
226-
public String error;
227-
}
228231
}

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import io.github.easy4j.opencli.core.OpenCliResult;
99
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
1010
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
11+
import io.github.easy4j.opencli.exception.OpenCliRemoteProtocolException;
1112
import java.io.ByteArrayOutputStream;
1213
import java.io.IOException;
1314
import java.io.InputStream;
@@ -22,6 +23,8 @@
2223
import java.util.regex.Pattern;
2324
import org.junit.jupiter.api.Assertions;
2425
import org.junit.jupiter.api.Test;
26+
import org.junit.jupiter.params.ParameterizedTest;
27+
import org.junit.jupiter.params.provider.ValueSource;
2528

2629
/**
2730
* 使用 JDK {@link HttpServer} 模拟 Agent {@code POST /collect},校验 HTTP 客户端与原始报文保留选项。
@@ -157,6 +160,42 @@ void nullEnvelopeUsesSafeCorrelatedParseFailure() throws IOException {
157160
}
158161
}
159162

163+
@Test
164+
void explicitSuccessfulReplyCanOmitItems() throws IOException {
165+
try (JsonCollectStub stub = JsonCollectStub.start("{\"success\":true,\"extension\":42}");
166+
OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(baseProps(stub.port()))) {
167+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("x").command("y").build();
168+
OpenCliResult result = client.collect(request);
169+
Assertions.assertTrue(result.isSuccess());
170+
Assertions.assertEquals("[]", result.getStdout());
171+
}
172+
}
173+
174+
@ParameterizedTest
175+
@ValueSource(strings = {
176+
"",
177+
"null",
178+
"[]",
179+
"{\"items\":[]}",
180+
"{\"success\":null}",
181+
"{\"success\":\"true\"}",
182+
"{\"success\":1}",
183+
"{\"success\":true,\"error\":42}",
184+
"{\"success\":false,\"success\":true}",
185+
"{\"success\":true} {\"success\":false}"
186+
})
187+
void invalidLegacyEnvelopeIsAProtocolFailure(String body) throws IOException {
188+
try (JsonCollectStub stub = JsonCollectStub.start(body);
189+
OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(baseProps(stub.port()))) {
190+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("x").command("y").build();
191+
OpenCliRemoteProtocolException failure = Assertions.assertThrows(
192+
OpenCliRemoteProtocolException.class, () -> client.collect(request));
193+
Assertions.assertTrue(failure.getMessage().contains("response envelope"));
194+
Assertions.assertTrue(failure.getMessage().contains("correlationId="));
195+
Assertions.assertNull(failure.getCause());
196+
}
197+
}
198+
160199
@Test
161200
void malformedResponseDoesNotExposeParserSnippetInException() throws IOException {
162201
String canary = "parser-secret-" + UUID.randomUUID();

0 commit comments

Comments
 (0)