Skip to content

Commit 2ca2d31

Browse files
committed
Reject lossy legacy collect argv before dispatch
Refs #5 (cherry picked from commit a5448e1)
1 parent fa7e001 commit 2ca2d31

8 files changed

Lines changed: 146 additions & 130 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ 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.
193193
- 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 `[]`.
194+
- Legacy HTTP argv dispatch accepts SDK-listed adapters and one subcommand. Root metadata, Browser sessions, external passthrough, repeated options, `--`, and tokens whose spacing or leading dash cannot be preserved are rejected before HTTP. Place positionals before options. Use local execution for commands that need the original argv. A deployment with its own adapter contract can use the explicit `OpenCliCollectRequest` API.
194195
- `execution-target=REMOTE_AGENT_HTTP` makes the availability probe report `SKIPPED_REMOTE_MODE` (treated as startable).
195196

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

‎README.zh-CN.md‎

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

191191
- 远程模式下 `stdout` 为 Agent 返回的 `items` 的 JSON(已按 `format` 解析为行列表),与本地原始子进程文本可能不同;`leadingArguments` 等仅影响本地进程拼装,**远程路径不注入**。
192192
- 旧版 HTTP `/collect` 响应须包含 JSON 布尔字段 `success`。无效响应抛出 `OpenCliRemoteProtocolException`,它继承 `OpenCliExecutableFailureException`。当 `success: true` 且 `items` 缺失或为 null 时,仍返回 `[]`。
193+
- 旧版 HTTP argv 调用仅接收 SDK 清单中的适配器及其子命令。根命令、Browser 会话、外部程序透传、重复选项、`--` 以及无法保留边界空格或前导短横的参数会在发请求前被拒绝。位置参数应在选项前。需要原样传递 argv 时使用本地执行,已有自定义 Agent 契约时可用显式 `OpenCliCollectRequest` API。
193194
- `execution-target=REMOTE_AGENT_HTTP` 时可用性探测报告 `SKIPPED_REMOTE_MODE`(视为可启动)。
194195

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

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
## 1. 服务端契约与失败测试
88

99
- [x] 1.1 固定可控的 legacy `POST /collect` fixture,记录本地桩与上游 CLI 的范围差异。见下方 OC-REMOTE-004 证据。
10-
- [ ] 1.2 对 Browser/root/external/重复flag/负数/--/空值编写“拒绝且零请求”的测试。
10+
- [x] 1.2 验证 Browser、根命令、外部透传和旧 DTO 无法保真的输入均在发送前拒绝。见下方 OC-REMOTE-001/002 证据。
1111
- [ ] 1.3 编写 success=false、503、malformed、null、超大body与超时结果未知用例。
1212

1313
## 2. 最小适配修复
@@ -34,3 +34,10 @@
3434
JDK 17 基线 `5ac4bb1` 的 20 项用例实际执行,7 项失败。缺少或显式设为 null 的 `success` 被当成业务失败。字符串和数字布尔值、数字 `error`、重复状态字段及拼接文档曾被当成成功。修正后,具备布尔状态字段的单个 JSON 对象才会继续映射结果,无效响应通过 `OpenCliRemoteProtocolException` 保留类别和相关 ID。现有异常父类保持兼容。合法的成功响应允许省略或置空 `items`,空结果仍为 `[]`。
3535

3636
定向测试命令为 `-Dtest=OpenCliRemoteAgentHttpClientTest test`。使用各维护线的 Maven 和 JDK,报告位于 `target/surefire-reports`。Body 大小限制、总超时和退出码来源仍由其他任务验收。
37+
38+
39+
## OC-REMOTE-001/002 发请求前校验
40+
41+
基线 `cf9360e` 的集成测试中,16 组输入有 15 组未按要求在 HTTP 前拒绝。既有 SDK 适配器名可能和外部透传调用重名,额外测试复现了该路径;改为仅本地执行后,HTTP 桩记录为零请求。正常 npm search 调用仍发送一次,并检查实际 JSON 的 site、command、positional_args 和 args。公开的低层 `collect(OpenCliCollectRequest)` 继续接收应用已经验证过的服务端 DTO。
42+
43+
本轮证据来自本地桩和各维护线全量验证,当前 SDK 适配器清单用于限制 argv 路由。各 Agent 部署的实际命令与选项契约仍需验证。

‎src/main/java/io/github/easy4j/opencli/core/OpenCliExecutor.java‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
99
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
1010
import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
11+
import io.github.easy4j.opencli.registry.OpenCliAdapterTaxonomy;
1112
import io.github.easy4j.opencli.remote.OpenCliArgvToCollectParser;
1213
import io.github.easy4j.opencli.remote.OpenCliCollectRequest;
1314
import io.github.easy4j.opencli.remote.OpenCliRemoteAgentHttpClient;
@@ -55,7 +56,7 @@ public OpenCliExecutor(OpenCliProperties properties, OpenCliProcessRuntime proce
5556

5657
/** @param adapterAndRest command and literal values @return execution result */
5758
public OpenCliResult invoke(List<String> adapterAndRest) {
58-
return invokeInternal(adapterAndRest, new OpenCliCancellationToken(), false);
59+
return invokeInternal(adapterAndRest, new OpenCliCancellationToken(), false, false);
5960
}
6061

6162
/**
@@ -67,11 +68,22 @@ public OpenCliResult invoke(List<String> adapterAndRest) {
6768
* @return execution result
6869
*/
6970
public OpenCliResult invoke(List<String> adapterAndRest, OpenCliCancellationToken cancellationToken) {
70-
return invokeInternal(adapterAndRest, Objects.requireNonNull(cancellationToken, "cancellationToken"), true);
71+
return invokeInternal(adapterAndRest, Objects.requireNonNull(cancellationToken, "cancellationToken"), true, false);
72+
}
73+
74+
/**
75+
* Executes argv whose semantics require a local process, such as external CLI passthrough.
76+
*
77+
* @param argv command and literal values
78+
* @return local execution result
79+
* @throws UnsupportedOperationException when configured for legacy HTTP collect
80+
*/
81+
public OpenCliResult invokeLocalOnly(List<String> argv) {
82+
return invokeInternal(argv, new OpenCliCancellationToken(), false, true);
7183
}
7284

7385
private OpenCliResult invokeInternal(List<String> adapterAndRest,
74-
OpenCliCancellationToken cancellationToken, boolean explicitCancellation) {
86+
OpenCliCancellationToken cancellationToken, boolean explicitCancellation, boolean localOnly) {
7587
long submittedAtNanos = System.nanoTime();
7688
long timeoutMillis = properties.getCommandTimeoutMillis();
7789
List<String> tokens = OpenCliArgSupport.snapshotValues(adapterAndRest, "adapterAndRest");
@@ -82,9 +94,16 @@ private OpenCliResult invokeInternal(List<String> adapterAndRest,
8294
throw new IllegalArgumentException("adapterAndRest[0] command identifier must not be blank");
8395
}
8496
if (properties.getExecutionTarget() == OpenCliExecutionTarget.REMOTE_AGENT_HTTP) {
97+
if (localOnly) {
98+
throw new UnsupportedOperationException("This command requires local process execution");
99+
}
85100
if (explicitCancellation) {
86101
throw new UnsupportedOperationException("Explicit process cancellation is local-only for legacy collect");
87102
}
103+
String site = tokens.get(0);
104+
if (!OpenCliAdapterTaxonomy.BROWSER_IDS.contains(site) && !OpenCliAdapterTaxonomy.isDesktopAdapter(site)) {
105+
throw new IllegalArgumentException("Legacy collect requires an adapter registered in the SDK");
106+
}
88107
OpenCliCollectRequest req = OpenCliArgvToCollectParser.parse(tokens,
89108
properties.getRemoteOutputFormat(), properties.getRemoteCollectMode(), properties.getRemoteCdpEndpoint());
90109
return remoteAgent().collect(req);

‎src/main/java/io/github/easy4j/opencli/meta/OpenCliExternalClient.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ public OpenCliResult passthrough(String externalCliName, List<String> passthroug
8787
if (passthroughArgs != null) {
8888
tokens.addAll(passthroughArgs);
8989
}
90-
return executor.invoke(tokens);
90+
return executor.invokeLocalOnly(tokens);
9191
}
9292

9393
/**

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

Lines changed: 48 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,17 @@
44
import java.util.ArrayList;
55
import java.util.LinkedHashMap;
66
import java.util.List;
7-
import java.util.Locale;
87
import java.util.Map;
98
import java.util.Objects;
9+
import java.util.regex.Pattern;
1010
import lombok.extern.slf4j.Slf4j;
1111

12-
/**
13-
* 将 {@link io.github.easy4j.opencli.core.OpenCliExecutor#invoke(List)} 使用的 argv 列表
14-
*({@code [adapter, command, ...]}) best-effort 映射为 Agent {@link OpenCliCollectRequest}。
15-
* 规则:前两个 token 为 {@code site}、{@code command};其后从左到右扫描:
16-
* <ul>
17-
* <li>{@code -f} / {@code --format} 及其下一 token 写入请求 {@code format},不进入 args;</li>
18-
* <li>{@code --key=value} 或 {@code --key} + 下一非选项值 → 进入 {@code args}(key 无 {@code --} 前缀);</li>
19-
* <li>单独 {@code --flag}(下一 token 以 {@code -} 开头或缺失)→ {@code args[flag]=true};</li>
20-
* <li>其余 token 按顺序进入 {@code positional_args}。</li>
21-
* </ul>
22-
* Agent 会自行追加 {@code -f &lt;format&gt;},故本解析器会消费调用方已写的 {@code -f},避免重复。
23-
*/
24-
@Slf4j/**
25-
26-
* Best-effort mapping from the argv list used by
27-
* {@link io.github.easy4j.opencli.core.OpenCliExecutor#invoke(List)}
28-
* ({@code [adapter, command, ...]}) to an Agent {@link OpenCliCollectRequest}.
29-
*
30-
* <p>Parsing rules: the first two tokens are {@code site} and {@code command};
31-
* subsequent tokens are scanned left-to-right:</p>
32-
* <ul>
33-
* <li>{@code -f} / {@code --format} and its next token are written to {@code format}, not args;</li>
34-
* <li>{@code --key=value} or {@code --key} + next non-option value go to {@code args} (key without {@code --} prefix);</li>
35-
* <li>Standalone {@code --flag} (next token starts with {@code -} or is absent) goes to {@code args[flag]=true};</li>
36-
* <li>All other tokens go to {@code positional_args} in order.</li>
37-
* </ul>
38-
39-
*
40-
41-
* @author <a href="https://github.com/loong10k">Loong Wan</a>
42-
43-
* @since 3.0.0
44-
45-
*/
46-
12+
/** Maps the supported adapter argv grammar to the legacy HTTP collect DTO. */
13+
@Slf4j
4714
public final class OpenCliArgvToCollectParser {
4815

16+
private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_-]*");
17+
4918
private OpenCliArgvToCollectParser() {
5019
}
5120

@@ -66,75 +35,53 @@ public static OpenCliCollectRequest parse(
6635
throw new IllegalArgumentException(
6736
"remote invoke requires at least [adapter, command], got " + adapterAndRest.size() + " tokens");
6837
}
69-
String site = adapterAndRest.get(0).trim();
70-
String command = adapterAndRest.get(1).trim();
71-
if (OpenCliStrings.isBlank(site) || OpenCliStrings.isBlank(command)) {
72-
throw new IllegalArgumentException("adapter and command must not be blank");
73-
}
38+
String site = requireIdentifier(adapterAndRest.get(0));
39+
String command = requireIdentifier(adapterAndRest.get(1));
7440

7541
String format = OpenCliStrings.isNotBlank(defaultFormat) ? defaultFormat.trim() : "json";
7642
String mode = OpenCliStrings.isNotBlank(defaultMode) ? defaultMode.trim() : "cdp";
7743
Map<String, Object> args = new LinkedHashMap<>();
7844
List<String> positional = new ArrayList<>();
45+
boolean formatSpecified = false;
7946

80-
int i = 2;
81-
while (i < adapterAndRest.size()) {
82-
String raw = adapterAndRest.get(i);
83-
if (Objects.isNull(raw) || raw.isEmpty()) {
84-
log.warn("Skipping null or empty argv token at index={}", i);
85-
i++;
86-
continue;
47+
int index = 2;
48+
while (index < adapterAndRest.size()) {
49+
String token = adapterAndRest.get(index++);
50+
if (Objects.isNull(token) || token.isEmpty() || !token.equals(token.trim())) {
51+
throw new IllegalArgumentException("Legacy collect cannot preserve an empty or padded token");
8752
}
88-
String t = raw.trim();
89-
if (t.isEmpty()) {
90-
i++;
91-
continue;
92-
}
93-
94-
if ("-f".equals(t) || "--format".equals(t)) {
95-
if (i + 1 >= adapterAndRest.size()) {
96-
throw new IllegalArgumentException("-f requires a value");
53+
if (!token.startsWith("-")) {
54+
if (formatSpecified || !args.isEmpty()) {
55+
throw new IllegalArgumentException("Legacy collect requires positional arguments before options");
9756
}
98-
format = Objects.requireNonNull(adapterAndRest.get(i + 1)).trim();
99-
i += 2;
57+
positional.add(token);
10058
continue;
10159
}
10260

103-
if (t.startsWith("--")) {
104-
if (t.contains("=")) {
105-
int eq = t.indexOf('=');
106-
String key = normalizeKey(t.substring(2, eq));
107-
String val = t.substring(eq + 1);
108-
if (isFormatKey(key)) {
109-
format = val;
110-
} else {
111-
args.put(key, val);
112-
}
113-
i++;
114-
continue;
115-
}
116-
String key = normalizeKey(t.substring(2));
117-
if (isFormatKey(key)) {
118-
if (i + 1 >= adapterAndRest.size()) {
119-
throw new IllegalArgumentException("--" + key + " requires a value");
120-
}
121-
format = adapterAndRest.get(i + 1).trim();
122-
i += 2;
123-
continue;
124-
}
125-
String next = i + 1 < adapterAndRest.size() ? adapterAndRest.get(i + 1) : null;
126-
if (Objects.nonNull(next) && !next.trim().startsWith("-")) {
127-
args.put(key, next.trim());
128-
i += 2;
129-
} else {
130-
args.put(key, Boolean.TRUE);
131-
i++;
61+
int separator = token.indexOf('=');
62+
String option = separator < 0 ? token : token.substring(0, separator);
63+
boolean shortFormat = "-f".equals(option) && separator < 0;
64+
if (!shortFormat && !option.startsWith("--")) {
65+
throw new IllegalArgumentException("Legacy collect does not support this option syntax");
66+
}
67+
String key = shortFormat ? "format" : requireIdentifier(option.substring(2));
68+
boolean isFormat = "format".equals(key) || "f".equals(key);
69+
Object value = Boolean.TRUE;
70+
if (separator >= 0) {
71+
value = requireValue(token.substring(separator + 1));
72+
} else if (index < adapterAndRest.size()
73+
&& (Objects.isNull(adapterAndRest.get(index)) || !adapterAndRest.get(index).startsWith("-"))) {
74+
value = requireValue(adapterAndRest.get(index++));
75+
}
76+
if (isFormat) {
77+
if (formatSpecified || !(value instanceof String)) {
78+
throw new IllegalArgumentException("Legacy collect requires a single explicit format value");
13279
}
133-
continue;
80+
format = (String) value;
81+
formatSpecified = true;
82+
} else if (Objects.nonNull(args.putIfAbsent(key, value))) {
83+
throw new IllegalArgumentException("Legacy collect cannot preserve a repeated option");
13484
}
135-
136-
positional.add(t);
137-
i++;
13885
}
13986

14087
OpenCliCollectRequest.OpenCliCollectRequestBuilder b =
@@ -149,14 +96,17 @@ public static OpenCliCollectRequest parse(
14996
return request;
15097
}
15198

152-
private static String normalizeKey(String key) {
153-
if (Objects.isNull(key) || key.isEmpty()) {
154-
throw new IllegalArgumentException("empty option key");
99+
private static String requireIdentifier(String value) {
100+
if (Objects.isNull(value) || !IDENTIFIER.matcher(value).matches()) {
101+
throw new IllegalArgumentException("Legacy collect requires a valid adapter, command or option identifier");
155102
}
156-
return key.toLowerCase(Locale.ROOT);
103+
return value;
157104
}
158105

159-
private static boolean isFormatKey(String key) {
160-
return "format".equals(key) || "f".equals(key);
106+
private static String requireValue(String value) {
107+
if (Objects.isNull(value) || value.isEmpty() || !value.equals(value.trim()) || value.startsWith("-")) {
108+
throw new IllegalArgumentException("Legacy collect cannot preserve this option value");
109+
}
110+
return value;
161111
}
162112
}

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

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,15 @@ void shouldParseDashDashFormatEquals() {
3030
}
3131

3232
@Test
33-
void shouldSkipNullTokens() {
34-
List<String> argv = new ArrayList<>(Arrays.asList("npm", "search", null, "react"));
35-
OpenCliCollectRequest req = OpenCliArgvToCollectParser.parse(argv, "json", "cdp", "");
36-
assertTrue(req.getPositionalArgs().contains("react"));
33+
void shouldRejectNullTokens() {
34+
assertThrows(IllegalArgumentException.class, () -> OpenCliArgvToCollectParser.parse(
35+
Arrays.asList("npm", "search", null, "react"), "json", "cdp", ""));
3736
}
3837

3938
@Test
40-
void shouldSkipEmptyTokens() {
41-
OpenCliCollectRequest req = OpenCliArgvToCollectParser.parse(
42-
Arrays.asList("npm", "search", "", "react"), "json", "cdp", "");
43-
assertTrue(req.getPositionalArgs().contains("react"));
39+
void shouldRejectEmptyTokens() {
40+
assertThrows(IllegalArgumentException.class, () -> OpenCliArgvToCollectParser.parse(
41+
Arrays.asList("npm", "search", "", "react"), "json", "cdp", ""));
4442
}
4543

4644
@Test

0 commit comments

Comments
 (0)