Skip to content

Commit 4411a4b

Browse files
committed
Guard Windows strict argv and negated option aliases
1 parent 4c9eaab commit 4411a4b

10 files changed

Lines changed: 140 additions & 14 deletions

File tree

‎README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,13 @@ Notes:
203203
<a id="8-core-usage"></a>
204204
## 8. Core Usage
205205

206+
### Local argv migration
207+
208+
- Local invocation preserves empty strings, padding, Unicode, line breaks, and literal option terminators. If your application relied on trimming or dropping values, normalize its inputs explicitly before calling the SDK.
209+
- Use the adapter's no-argument invocation or an empty list for a root command. A null varargs array or null token is invalid. An empty string token remains a valid value.
210+
- In the legacy options map, Boolean `false` still omits the option. Use `OpenCliOption.value` for a schema-supported literal `false`, or `OpenCliOption.negated` for a schema-supported negative flag. A negatable option reserves both its positive and negative names, so duplicate definitions across ordered and legacy options are rejected.
211+
- On Windows, use the full path to a native executable such as `node.exe`, with the installed OpenCLI JavaScript entry point in `leadingArguments`. The SDK rejects batch launchers. If the JVM is running in strict process mode, a literal double quote in a native executable argument is rejected before spawn with its index and an explanation.
212+
206213
### 8.1 meta() and browser()
207214

208215
```java

‎README.zh-CN.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,13 @@ cli.gemini().deepResearch("topic",
202202
<a id="8-core-usage"></a>
203203
## 8. 核心用法
204204

205+
### 本地 argv 迁移
206+
207+
- 本地调用原样保留空字符串、边界空白、Unicode、换行和字面参数终止符。此前依赖 SDK 裁剪或丢弃参数的调用方,应在调用前显式处理自己的输入。
208+
- 调用适配器根命令时使用无参调用或空列表。varargs 数组与 token 不能为 null,空字符串仍是有效参数值。
209+
- 旧选项 Map 的布尔 `false` 继续表示省略。显式布尔值使用有对应 schema 的 `OpenCliOption.value`,否定选项使用 `OpenCliOption.negated`。可否定的结构化选项同时占用正向名和否定别名,避免与旧 Map 或其他结构化选项冲突。
210+
- Windows 使用 `node.exe` 等原生可执行文件的完整路径,并在 `leadingArguments` 中指定已安装的 OpenCLI JavaScript 入口。SDK 拒绝批处理入口。在 JVM 严格进程模式下,原生可执行文件参数中的字面双引号在启动前被明确拒绝,错误包含参数索引。
211+
205212
### 8.1 meta() 与 browser()
206213

207214
```java

‎openspec/changes/harden-opencli-argv-contract/tasks.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,11 @@
3434
- 三条维护线使用同一套已校验 SHA-256 的 `argv.tsv`、`ContractProbe` 和 `OpenCliStructuredArgvContractTest`。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,120 项通过,0 失败、0 错误、0 跳过,退出 0。本地报告为 `target/surefire-reports`。三个版本的 JDK/Jackson/Maven 允许差异见 fixture 的 `sources.lock.json`。远端分支最新 CI 单独记录于 PR。
3535

3636
- 排队回归与原始参数回归共用回显启动配置。首次 JDK 17 Windows CI 使用旧 Java 回显启动器时,子进程把原始中文 token 收成 `???`。改用同套 Windows 原生 Node 回显夹具,继续断言完整 Unicode token,并保留 Java 生命周期进程作为许可占用方。[首次 Windows 结果](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44340768729/job/134929785664)
37+
38+
## 三线 JVM 兼容和迁移复核
39+
40+
以 GitHub 现有目标分支 `feature/1.0.x` 的 `7726b51`、`feature/2.0.x` 的 `196206d`、`feature/3.0.x` 的 `e66f958` 为基线。各线用自己的 Wrapper 和 JDK 编译目标与候选代码,使用 JDK 21 的 `javap -protected -s` 比对已编译的 SDK 类。三个基线各有 151 个可见类型和 1,687 个公开或受保护的已声明成员。候选均保留这些类型声明和成员 JVM 描述符,未出现缩减访问级别的成员。此处核对的是 JVM 声明,参数行为由子进程用例和迁移说明验证。中英文 README 已补齐本地字面值、空参调用、旧 Map 布尔值和结构化否定选项的迁移差异。
41+
42+
独立评审复现了 Windows 严格进程模式下潜在的字面引号降级,以及可否定选项混用否定别名的冲突。Java 17 基线 `75160c6` 的两项定向测试均失败。原生 EXE 的严格模式会在取得子进程前报告无法保真的参数索引,消息不含值,普通参数仍可执行。可否定 schema 同时保留正向名和否定别名,两种排列顺序和旧 Map 均不会发出冲突组合。
43+
44+
修复后 Java 8、17、21 各用自己的 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,257、2,258、2,257 项,零失败、零错误、零跳过。仍待以新提交的 Windows 托管报告和独立复审作为 3.4 的最终依据。

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

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -108,25 +108,31 @@ public List<String> toSubcommandAndArgs() {
108108
}
109109
OpenCliOptionSchema schema = occurrence.getSchema();
110110
String name = schema.getName();
111-
List<String> argv = occurrence.toTokens();
112-
String wireName = argv.get(0);
113-
if (legacyFlags.contains(name) || legacyFlags.contains(wireName)) {
114-
throw new IllegalArgumentException("Legacy and ordered options must not overlap");
115-
}
116111
OpenCliOptionSchema previous = seen.put(name, schema);
117-
if (previous != null && (!schema.isRepeatable() || !previous.equals(schema))) {
112+
if (Objects.nonNull(previous) && (!schema.isRepeatable() || !previous.equals(schema))) {
118113
throw new IllegalArgumentException("Repeated option is not allowed by one consistent schema");
119114
}
120-
String previousCanonical = wireNames.put(wireName, name);
121-
if (previousCanonical != null && !previousCanonical.equals(name)) {
122-
throw new IllegalArgumentException("Different schemas emit the same option identifier");
115+
reserveOptionName(wireNames, legacyFlags, name, name);
116+
if (schema.getKind() == OpenCliOptionSchema.Kind.NEGATABLE_FLAG) {
117+
reserveOptionName(wireNames, legacyFlags, schema.negatedName(), name);
123118
}
124-
tokens.addAll(argv);
119+
tokens.addAll(occurrence.toTokens());
125120
}
126121
}
127122
return tokens;
128123
}
129124

125+
private static void reserveOptionName(Map<String, String> wireNames, Set<String> legacyFlags,
126+
String wireName, String canonicalName) {
127+
if (legacyFlags.contains(wireName)) {
128+
throw new IllegalArgumentException("Legacy and ordered options must not overlap");
129+
}
130+
String previous = wireNames.putIfAbsent(wireName, canonicalName);
131+
if (Objects.nonNull(previous) && !previous.equals(canonicalName)) {
132+
throw new IllegalArgumentException("Different schemas reserve the same option identifier");
133+
}
134+
}
135+
130136
private static Map<String, Object> snapshotOptions(Map<String, Object> source) {
131137
if (source == null) { return Collections.emptyMap(); }
132138
Map<String, Object> snapshot = new LinkedHashMap<>();

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public static OpenCliOption negated(OpenCliOptionSchema schema) {
6666

6767
/** @return immutable literal tokens; no quoting or trimming is applied */
6868
public List<String> toTokens() {
69-
String flag = negated ? "--no-" + schema.getName().substring(2) : schema.getName();
69+
String flag = negated ? schema.negatedName() : schema.getName();
7070
return value == null ? Collections.singletonList(flag)
7171
: Collections.unmodifiableList(Arrays.asList(flag, value));
7272
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ public static OpenCliOptionSchema negatableFlag(String name) {
5757
/** @return declared input kind */
5858
public Kind getKind() { return kind; }
5959

60+
String negatedName() {
61+
return "--no-" + name.substring(2);
62+
}
63+
6064
/** @return whether the command accepts repeated occurrences */
6165
public boolean isRepeatable() { return repeatable; }
6266

‎src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ public Runtime(int maxConcurrent) {
116116

117117
public RunSession execute(ExecutionRequest request) throws IOException, InterruptedException {
118118
Objects.requireNonNull(request, "request");
119+
List<String> launchArguments = processArguments(request.nativeArgv);
119120
long budget = nanos(request.timeoutMillis, "timeoutMillis");
120121
BoundedCapture out = new BoundedCapture(request.stdoutLimitBytes);
121122
BoundedCapture err = new BoundedCapture(request.stderrLimitBytes);
@@ -164,7 +165,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
164165
}
165166
}
166167
if (acquired && reason == null) {
167-
ProcessBuilder builder = new ProcessBuilder(processArguments(request.nativeArgv));
168+
ProcessBuilder builder = new ProcessBuilder(launchArguments);
168169
if (request.workingDirectory != null) { builder.directory(request.workingDirectory); }
169170
if (request.environment != null) {
170171
builder.environment().clear();
@@ -391,14 +392,19 @@ synchronized boolean isPending() {
391392
private static List<String> processArguments(List<String> argv) {
392393
String executable = argv.get(0).toLowerCase(Locale.ROOT);
393394
if (!System.getProperty("os.name").startsWith("Windows") || !executable.endsWith(".exe")
394-
|| executable.endsWith("cmd.exe") || Objects.nonNull(System.getSecurityManager())
395-
|| "false".equalsIgnoreCase(System.getProperty("jdk.lang.Process.allowAmbiguousCommands"))) {
395+
|| executable.endsWith("cmd.exe")) {
396396
return argv;
397397
}
398+
boolean strict = Objects.nonNull(System.getSecurityManager())
399+
|| "false".equalsIgnoreCase(System.getProperty("jdk.lang.Process.allowAmbiguousCommands"));
398400
List<String> arguments = new ArrayList<>(argv);
399401
for (int i = 1; i < arguments.size(); i++) {
400402
String argument = arguments.get(i);
401403
if (argument.indexOf('"') >= 0) {
404+
if (strict) {
405+
throw new UnsupportedOperationException(
406+
"Windows strict process mode cannot preserve a literal double quote in argv[" + i + "]");
407+
}
402408
arguments.set(i, quoteWindowsExecutableArgument(argument));
403409
}
404410
}

‎src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import static org.junit.jupiter.api.Assertions.*;
3232

3333
/** Shared Java 8-compatible contract tests, with a real child rather than Recording executor. */
34+
@org.junit.jupiter.api.parallel.Isolated
3435
class OpenCliArgvContractTest {
3536
static OpenCliProperties properties() {
3637
OpenCliProperties p = new OpenCliProperties();
@@ -172,6 +173,34 @@ void blankCommandIdentifierIsRejectedBeforeSpawn() {
172173
.subcommand(" ").build().toSubcommandAndArgs());
173174
}
174175

176+
@Test
177+
void strictWindowsLauncherRejectsQuotesAndStillAcceptsUnambiguousArguments() throws Exception {
178+
String property = "jdk.lang.Process.allowAmbiguousCommands";
179+
String previous = System.getProperty(property);
180+
String quoted = "\"private-literal-quote\"";
181+
try {
182+
System.setProperty(property, "false");
183+
try (OpenCliExecutor executor = new OpenCliExecutor(properties())) {
184+
List<String> ordinary = Arrays.asList("demo", "echo", "literal");
185+
assertEquals(ordinary, received(executor.invoke(ordinary)));
186+
List<String> withQuote = Arrays.asList("demo", "echo", quoted);
187+
if (System.getProperty("os.name").startsWith("Windows")) {
188+
UnsupportedOperationException failure =
189+
assertThrows(UnsupportedOperationException.class, () -> executor.invoke(withQuote));
190+
assertFalse(failure.getMessage().contains("private-literal-quote"));
191+
} else {
192+
assertEquals(withQuote, received(executor.invoke(withQuote)));
193+
}
194+
}
195+
} finally {
196+
if (previous == null) {
197+
System.clearProperty(property);
198+
} else {
199+
System.setProperty(property, previous);
200+
}
201+
}
202+
}
203+
175204
@Test
176205
void nullVarargsContainerIsRejectedConsistently() {
177206
OpenCliExecutor executor = new OpenCliExecutor(properties());

‎src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredArgvContractTest.java‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,26 @@ void legacyAndOrderedOptionsCannotCollide() {
131131
assertThrows(IllegalArgumentException.class, () -> b.build().toSubcommandAndArgs());
132132
}
133133

134+
@Test
135+
void aNegatableOptionReservesBothSpellingsAcrossAllOccurrences() {
136+
Object cache = schema("negatableFlag", "--cache", false);
137+
OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder legacy =
138+
OpenCliAdapterCommandRequest.builder().subcommand("echo")
139+
.options(Collections.<String, Object>singletonMap("no-cache", true));
140+
add(legacy, flag("present", cache));
141+
assertThrows(IllegalArgumentException.class, () -> legacy.build().toSubcommandAndArgs());
142+
143+
for (boolean reversed : new boolean[]{false, true}) {
144+
OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder ordered =
145+
OpenCliAdapterCommandRequest.builder().subcommand("echo");
146+
Object positive = flag("present", cache);
147+
Object alias = flag("present", schema("flag", "--no-cache", false));
148+
add(ordered, reversed ? alias : positive);
149+
add(ordered, reversed ? positive : alias);
150+
assertThrows(IllegalArgumentException.class, () -> ordered.build().toSubcommandAndArgs());
151+
}
152+
}
153+
134154
@Test
135155
void mutableOccurrenceValueIsCapturedWhenCreated() {
136156
StringBuilder text = new StringBuilder(" before ");

‎src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
44
import io.github.easy4j.opencli.contract.LifecycleProbe;
55
import java.io.File;
6+
import java.io.IOException;
7+
import java.util.concurrent.atomic.AtomicInteger;
68
import java.io.PrintWriter;
79
import java.io.StringWriter;
810
import java.nio.charset.StandardCharsets;
@@ -12,6 +14,7 @@
1214
import static org.junit.jupiter.api.Assertions.*;
1315
import org.junit.jupiter.api.Test;
1416

17+
@org.junit.jupiter.api.parallel.Isolated
1518
class SubprocessExecutionSupportTest {
1619

1720
@Test
@@ -85,6 +88,42 @@ void shouldKeepNativePathOutOfDefaultHandlerException(@TempDir Path temporary) t
8588
assertFalse(diagnostics.toString().contains(canary));
8689
}
8790

91+
@Test
92+
void rejectsQuotedWindowsArgumentsBeforeNativeSpawnInStrictMode() throws Exception {
93+
String previousOs = System.getProperty("os.name");
94+
String property = "jdk.lang.Process.allowAmbiguousCommands";
95+
String previousMode = System.getProperty(property);
96+
AtomicInteger launches = new AtomicInteger();
97+
SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1, builder -> {
98+
launches.incrementAndGet();
99+
throw new IOException("fixture must not launch");
100+
}, timeout -> new org.apache.commons.exec.ExecuteWatchdog(timeout));
101+
CommandLine command = new CommandLine("fixture.exe") {
102+
@Override
103+
public String[] toStrings() {
104+
return new String[]{"fixture.exe", "\"private-quoted-value\""};
105+
}
106+
};
107+
SubprocessExecutionSupport.ExecutionRequest request =
108+
new SubprocessExecutionSupport.ExecutionRequest(command, null, null, 1_000L);
109+
try {
110+
System.setProperty("os.name", "Windows");
111+
System.setProperty(property, "false");
112+
UnsupportedOperationException failure = assertThrows(
113+
UnsupportedOperationException.class, () -> runtime.execute(request));
114+
assertTrue(failure.getMessage().contains("argv[1]"));
115+
assertFalse(failure.getMessage().contains("private-quoted-value"));
116+
assertEquals(0, launches.get());
117+
} finally {
118+
System.setProperty("os.name", previousOs);
119+
if (previousMode == null) {
120+
System.clearProperty(property);
121+
} else {
122+
System.setProperty(property, previousMode);
123+
}
124+
}
125+
}
126+
88127
@Test
89128
void shouldReturnDefaultMaxConcurrent() {
90129
int defaultVal = SubprocessExecutionSupport.defaultMaxConcurrentExecutions();

0 commit comments

Comments
 (0)