Skip to content

Commit 7f17d75

Browse files
committed
Bound decoded legacy collect response bodies
Refs #5 (cherry picked from commit bf05ba6)
1 parent 866c65e commit 7f17d75

7 files changed

Lines changed: 224 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ Configuration is object-based via `OpenCliProperties`:
186186
| `remoteOutputFormat` | `json` | Output format requested from the agent |
187187
| `remoteCdpEndpoint` | — | Optional CDP endpoint overriding the agent default |
188188
| `remoteCaptureRawHttpResponse` | `false` | Keep the raw HTTP body in `OpenCliResult#getRemoteRawHttpBody()` (large responses — use with care) |
189+
| `maxRemoteResponseBytes` | `10485760` | Positive byte limit after HTTP decompression. An oversized response raises `OpenCliRemoteResponseLimitException` with its HTTP status and limit. Raw capture only applies to accepted bodies. |
189190

190191
Notes:
191192

‎README.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ cli.gemini().deepResearch("topic",
185185
| `remoteOutputFormat` | `json` | 向 Agent 请求的输出格式 |
186186
| `remoteCdpEndpoint` | — | 可选,覆盖 Agent 默认 CDP 端点 |
187187
| `remoteCaptureRawHttpResponse` | `false` | 在 `OpenCliResult#getRemoteRawHttpBody()` 中保留原始 HTTP 报文(大响应请谨慎开启) |
188+
| `maxRemoteResponseBytes` | `10485760` | HTTP 解压后的响应体字节上限,须为正数。超限抛出 `OpenCliRemoteResponseLimitException`,含 HTTP 状态和上限。原文捕获受同一上限约束。 |
188189

189190
注意事项:
190191

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,10 @@ JDK 17 基线 `5ac4bb1` 的 20 项用例实际执行,7 项失败。缺少或
4141
基线 `cf9360e` 的集成测试中,16 组输入有 15 组未按要求在 HTTP 前拒绝。既有 SDK 适配器名可能和外部透传调用重名,额外测试复现了该路径;改为仅本地执行后,HTTP 桩记录为零请求。正常 npm search 调用仍发送一次,并检查实际 JSON 的 site、command、positional_args 和 args。公开的低层 `collect(OpenCliCollectRequest)` 继续接收应用已经验证过的服务端 DTO。
4242

4343
本轮证据来自本地桩和各维护线全量验证,当前 SDK 适配器清单用于限制 argv 路由。各 Agent 部署的实际命令与选项契约仍需验证。
44+
45+
46+
## OC-REMOTE-005 响应体预算
47+
48+
JDK 17 基线在 42 项 HTTP 用例中有 4 项失败,覆盖多字节响应超出一字节、HTTP 200 和 503 的分块响应,以及 gzip 解压超限。修改复用现有 Unirest 的原始响应流,从解压后的流读取至上限。读取超限检测只需额外一个字节,超限后由 Unirest 释放响应连接。既有整包读取 API 无法在流尚未结束时执行这一限制。分块桩在收到结果前保持响应开启,验证客户端不等待 EOF。
49+
50+
默认上限为 10 MiB,可通过 `maxRemoteResponseBytes` 配置正数。异常保留 HTTP 状态、上限和相关 ID。启用原文捕获的客户端也无法取得超限内容。补充验证恰好满足预算、声明字符集、无效配置零请求以及超限后同一客户端继续执行。总超时、结果不确定性和认证 header 仍待相应场景验收。

‎src/main/java/io/github/easy4j/opencli/OpenCliProperties.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ public class OpenCliProperties {
7272
* 本地模式无效果。大响应时请谨慎开启。
7373
*/
7474
private boolean remoteCaptureRawHttpResponse = false;
75+
/** Maximum decoded HTTP response body bytes accepted from a remote Agent. */
76+
private int maxRemoteResponseBytes = 10 * 1024 * 1024;
7577

7678
/**
7779
* OpenCLI 可执行文件名或绝对路径;默认假定已在 {@code PATH} 中。
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package io.github.easy4j.opencli.exception;
2+
3+
import lombok.Getter;
4+
5+
/** 远端 HTTP 响应体超出允许字节数,保留 HTTP 状态及上限。 */
6+
@Getter
7+
public final class OpenCliRemoteResponseLimitException extends OpenCliExecutableFailureException {
8+
9+
private final int httpStatus;
10+
private final int maxResponseBytes;
11+
12+
/**
13+
* @param httpStatus HTTP 响应状态码
14+
* @param maxResponseBytes 客户端允许读取的最大响应字节数
15+
* @param correlationId SDK 请求关联标识
16+
*/
17+
public OpenCliRemoteResponseLimitException(int httpStatus, int maxResponseBytes, String correlationId) {
18+
super("Agent HTTP response body exceeded " + maxResponseBytes + " bytes, status="
19+
+ httpStatus + " correlationId=" + correlationId, null);
20+
this.httpStatus = httpStatus;
21+
this.maxResponseBytes = maxResponseBytes;
22+
}
23+
}

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

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,22 @@
1111
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
1212
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
1313
import io.github.easy4j.opencli.exception.OpenCliRemoteProtocolException;
14+
import io.github.easy4j.opencli.exception.OpenCliRemoteResponseLimitException;
1415
import io.github.easy4j.opencli.parser.OpenCliParsedFields;
1516
import io.github.easy4j.opencli.util.OpenCliStrings;
17+
import java.io.ByteArrayOutputStream;
18+
import java.io.IOException;
19+
import java.io.InputStream;
20+
import java.nio.charset.Charset;
1621
import java.util.Objects;
22+
import java.util.Optional;
1723
import java.util.UUID;
1824
import kong.unirest.HttpResponse;
19-
import kong.unirest.Unirest;
25+
import kong.unirest.RawResponse;
26+
import kong.unirest.UnrecoverableException;
2027
import kong.unirest.UnirestException;
2128
import lombok.extern.slf4j.Slf4j;
29+
import org.apache.http.entity.ContentType;
2230

2331
/**
2432
* 调用 opencli-admin 边缘 Agent 的 HTTP {@code POST /collect}。
@@ -75,6 +83,10 @@ public OpenCliResult collect(OpenCliCollectRequest request) {
7583
}
7684
String url = base.trim().replaceAll("/+$", "") + "/collect";
7785
int timeout = resolveTimeoutMillis();
86+
int maxResponseBytes = properties.getMaxRemoteResponseBytes();
87+
if (maxResponseBytes <= 0) {
88+
throw new IllegalArgumentException("maxRemoteResponseBytes must be positive");
89+
}
7890
String correlationId = UUID.randomUUID().toString();
7991
String bodyJson;
8092
try {
@@ -84,16 +96,21 @@ public OpenCliResult collect(OpenCliCollectRequest request) {
8496
throw failure("Failed to serialize collect request", correlationId);
8597
}
8698
try {
87-
HttpResponse<String> response =
99+
HttpResponse<Optional<String>> response =
88100
transport()
89101
.post(url)
90102
.connectTimeout(timeout)
91103
.socketTimeout(timeout)
92104
.header("Content-Type", "application/json; charset=UTF-8")
93105
.body(bodyJson)
94-
.asString();
106+
.asObject(raw -> readBoundedBody(raw, maxResponseBytes));
95107
int status = response.getStatus();
96-
String respBody = Objects.isNull(response.getBody()) ? "" : response.getBody();
108+
if (response.getParsingError().isPresent()) {
109+
log.warn("Agent HTTP body read failed correlationId={} status={}", correlationId, status);
110+
throw failure("Agent HTTP I/O error", correlationId);
111+
}
112+
String respBody = response.getBody().orElseThrow(
113+
() -> new OpenCliRemoteResponseLimitException(status, maxResponseBytes, correlationId));
97114
if (status < 200 || status >= 300) {
98115
log.warn("Agent HTTP non-2xx correlationId={} status={} responseChars={}",
99116
correlationId, status, respBody.length());
@@ -149,6 +166,34 @@ public void close() {
149166
}
150167
}
151168

169+
private static Optional<String> readBoundedBody(RawResponse response, int limit) {
170+
try {
171+
// Unirest owns the response stream. Closing it here can drain an oversized HTTP entity.
172+
InputStream input = response.getContent();
173+
byte[] buffer = new byte[Math.min(8192, limit)];
174+
ByteArrayOutputStream body = new ByteArrayOutputStream(buffer.length);
175+
while (true) {
176+
int remaining = limit - body.size();
177+
int length = (int) Math.min(buffer.length, (long) remaining + 1);
178+
int read = input.read(buffer, 0, length);
179+
if (read < 0) {
180+
break;
181+
}
182+
if (read > remaining) {
183+
return Optional.empty();
184+
}
185+
body.write(buffer, 0, read);
186+
}
187+
String contentType = response.getContentType();
188+
Charset charset = OpenCliStrings.isBlank(contentType) ? null : ContentType.parse(contentType).getCharset();
189+
String encoding = Objects.nonNull(charset) ? charset.name() : response.getConfig().getDefaultResponseEncoding();
190+
return Optional.of(body.toString(encoding));
191+
} catch (IOException | RuntimeException exception) {
192+
// Avoid Unirest's fallback, which otherwise retries by reading the full body for diagnostics.
193+
throw new UnrecoverableException(exception);
194+
}
195+
}
196+
152197
private int resolveTimeoutMillis() {
153198
long timeoutMs = properties.getCommandTimeoutMillis();
154199
if (timeoutMs <= 0) {

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

Lines changed: 141 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
1111
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
1212
import io.github.easy4j.opencli.exception.OpenCliRemoteProtocolException;
13+
import io.github.easy4j.opencli.exception.OpenCliRemoteResponseLimitException;
1314
import io.github.easy4j.opencli.meta.OpenCliExternalClient;
1415
import java.io.ByteArrayOutputStream;
1516
import java.io.IOException;
@@ -19,12 +20,16 @@
1920
import java.io.StringWriter;
2021
import java.net.InetSocketAddress;
2122
import java.nio.charset.StandardCharsets;
23+
import java.time.Duration;
2224
import java.util.Arrays;
2325
import java.util.Scanner;
2426
import java.util.UUID;
27+
import java.util.concurrent.CountDownLatch;
28+
import java.util.concurrent.TimeUnit;
2529
import java.util.concurrent.atomic.AtomicInteger;
2630
import java.util.regex.Matcher;
2731
import java.util.regex.Pattern;
32+
import java.util.zip.GZIPOutputStream;
2833
import org.junit.jupiter.api.Assertions;
2934
import org.junit.jupiter.api.Test;
3035
import org.junit.jupiter.params.ParameterizedTest;
@@ -95,6 +100,132 @@ void collectFailureIncludesRawBodyWhenEnabled() throws IOException {
95100
}
96101
}
97102

103+
@Test
104+
void permitsABodyAtTheByteLimitAndRejectsOneByteLess() throws IOException {
105+
String body = "{\"success\":true,\"items\":[\"你好\"]}";
106+
try (JsonCollectStub stub = JsonCollectStub.start(body)) {
107+
OpenCliProperties props = baseProps(stub.port());
108+
props.setMaxRemoteResponseBytes(body.getBytes(StandardCharsets.UTF_8).length);
109+
props.setRemoteCaptureRawHttpResponse(true);
110+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(props)) {
111+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("npm").command("search").build();
112+
Assertions.assertEquals(body, client.collect(request).getRemoteRawHttpBody());
113+
props.setMaxRemoteResponseBytes(props.getMaxRemoteResponseBytes() - 1);
114+
OpenCliRemoteResponseLimitException exception = Assertions.assertThrows(
115+
OpenCliRemoteResponseLimitException.class, () -> client.collect(request));
116+
Assertions.assertEquals(200, exception.getHttpStatus());
117+
Assertions.assertEquals(props.getMaxRemoteResponseBytes(), exception.getMaxResponseBytes());
118+
Assertions.assertNull(exception.getPartialResult());
119+
props.setMaxRemoteResponseBytes(props.getMaxRemoteResponseBytes() + 1);
120+
Assertions.assertEquals(body, client.collect(request).getRemoteRawHttpBody());
121+
}
122+
}
123+
}
124+
125+
@ParameterizedTest
126+
@ValueSource(ints = {200, 503})
127+
void stopsReadingOversizedChunkedBodiesWithoutWaitingForEof(int status) throws IOException {
128+
CountDownLatch release = new CountDownLatch(1);
129+
byte[] prefix = ("{\"success\":true,\"items\":[\"private-body-" + UUID.randomUUID()).getBytes(StandardCharsets.UTF_8);
130+
try (JsonCollectStub stub = JsonCollectStub.start(exchange -> {
131+
exchange.sendResponseHeaders(status, 0);
132+
try (OutputStream output = exchange.getResponseBody()) {
133+
output.write(prefix);
134+
output.flush();
135+
try {
136+
release.await(10, TimeUnit.SECONDS);
137+
} catch (InterruptedException interrupted) {
138+
Thread.currentThread().interrupt();
139+
}
140+
}
141+
})) {
142+
try {
143+
OpenCliProperties props = baseProps(stub.port());
144+
props.setMaxRemoteResponseBytes(24);
145+
props.setCommandTimeoutMillis(8_000);
146+
props.setRemoteCaptureRawHttpResponse(true);
147+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(props)) {
148+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("npm").command("search").build();
149+
OpenCliRemoteResponseLimitException exception = Assertions.assertTimeoutPreemptively(
150+
Duration.ofSeconds(3), () -> Assertions.assertThrows(
151+
OpenCliRemoteResponseLimitException.class, () -> client.collect(request)));
152+
Assertions.assertEquals(status, exception.getHttpStatus());
153+
Assertions.assertEquals(24, exception.getMaxResponseBytes());
154+
Assertions.assertFalse(exception.getMessage().contains("private-body-"));
155+
Assertions.assertNull(exception.getCause());
156+
Assertions.assertNull(exception.getPartialResult());
157+
Assertions.assertEquals(1, stub.requests());
158+
}
159+
} finally {
160+
release.countDown();
161+
}
162+
}
163+
}
164+
165+
@Test
166+
void capsDecodedGzipBodyRatherThanCompressedContentLength() throws IOException {
167+
StringBuilder body = new StringBuilder("{\"success\":true,\"items\":[\"");
168+
for (int i = 0; i < 500; i++) {
169+
body.append('a');
170+
}
171+
body.append("\"]}");
172+
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
173+
try (GZIPOutputStream gzip = new GZIPOutputStream(compressed)) {
174+
gzip.write(body.toString().getBytes(StandardCharsets.UTF_8));
175+
}
176+
Assertions.assertTrue(compressed.size() < 128);
177+
try (JsonCollectStub stub = JsonCollectStub.start(exchange -> {
178+
exchange.getResponseHeaders().set("Content-Encoding", "gzip");
179+
exchange.sendResponseHeaders(200, compressed.size());
180+
try (OutputStream output = exchange.getResponseBody()) {
181+
compressed.writeTo(output);
182+
}
183+
})) {
184+
OpenCliProperties props = baseProps(stub.port());
185+
props.setMaxRemoteResponseBytes(128);
186+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(props)) {
187+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("npm").command("search").build();
188+
OpenCliRemoteResponseLimitException exception = Assertions.assertThrows(
189+
OpenCliRemoteResponseLimitException.class, () -> client.collect(request));
190+
Assertions.assertTrue(exception.getMessage().contains("response body exceeded"));
191+
}
192+
}
193+
}
194+
195+
@Test
196+
void rejectsNonpositiveResponseLimitBeforeHttp() throws IOException {
197+
try (JsonCollectStub stub = JsonCollectStub.start("{\"success\":true}")) {
198+
OpenCliProperties props = baseProps(stub.port());
199+
props.setMaxRemoteResponseBytes(0);
200+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(props)) {
201+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("npm").command("search").build();
202+
Assertions.assertThrows(IllegalArgumentException.class, () -> client.collect(request));
203+
Assertions.assertEquals(0, stub.requests());
204+
}
205+
}
206+
}
207+
208+
@Test
209+
void keepsDeclaredCharsetWithinTheResponseLimit() throws IOException {
210+
String body = "{\"success\":true,\"items\":[\"café\"]}";
211+
byte[] bytes = body.getBytes(StandardCharsets.ISO_8859_1);
212+
try (JsonCollectStub stub = JsonCollectStub.start(exchange -> {
213+
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=ISO-8859-1");
214+
exchange.sendResponseHeaders(200, bytes.length);
215+
try (OutputStream output = exchange.getResponseBody()) {
216+
output.write(bytes);
217+
}
218+
})) {
219+
OpenCliProperties props = baseProps(stub.port());
220+
props.setMaxRemoteResponseBytes(bytes.length);
221+
props.setRemoteCaptureRawHttpResponse(true);
222+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(props)) {
223+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("npm").command("search").build();
224+
Assertions.assertEquals(body, client.collect(request).getRemoteRawHttpBody());
225+
}
226+
}
227+
}
228+
98229
@Test
99230
void nonSuccessHttpResponseDoesNotExposeBodyCanaryInException() throws IOException {
100231
String canary = "body-secret-" + UUID.randomUUID();
@@ -307,6 +438,15 @@ static JsonCollectStub start(String jsonBody) throws IOException {
307438

308439
static JsonCollectStub start(String jsonBody, int status) throws IOException {
309440
byte[] bytes = jsonBody.getBytes(StandardCharsets.UTF_8);
441+
return start(exchange -> {
442+
exchange.sendResponseHeaders(status, bytes.length);
443+
try (OutputStream os = exchange.getResponseBody()) {
444+
os.write(bytes);
445+
}
446+
});
447+
}
448+
449+
static JsonCollectStub start(HttpHandler response) throws IOException {
310450
HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
311451
JsonCollectStub stub = new JsonCollectStub(server, server.getAddress().getPort());
312452
server.createContext(
@@ -327,10 +467,7 @@ public void handle(HttpExchange exchange) throws IOException {
327467
exchange
328468
.getResponseHeaders()
329469
.set("Content-Type", "application/json; charset=utf-8");
330-
exchange.sendResponseHeaders(status, bytes.length);
331-
try (OutputStream os = exchange.getResponseBody()) {
332-
os.write(bytes);
333-
}
470+
response.handle(exchange);
334471
}
335472
});
336473
server.start();

0 commit comments

Comments
 (0)