Skip to content

Commit 1ee75dc

Browse files
committed
Send explicit collect credentials only over verified HTTPS
Refs #5 (cherry picked from commit b40ed5a)
1 parent 2555ab9 commit 1ee75dc

9 files changed

Lines changed: 289 additions & 48 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ Notes:
195195
- 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.
196196
- A collect timeout raises `OpenCliRemoteTimeoutException`. After dispatch to the HTTP transport, `isRemoteOutcomeUnknown()` is true. Collect does not automatically retry or follow redirects.
197197
- Inspect `getRemoteExecutionDetails()` on the result or on an exception’s `getPartialResult()` to distinguish HTTP status, Agent business status and the source of `items`. The legacy 0/1 returned by `getExitCode()` is synthetic. HTTP and protocol failure snapshots have no exit code. Accepted response text is available in those snapshots only when raw capture is enabled.
198+
- If your Agent accepts a credential header, configure `setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", System.getenv("OPENCLI_AGENT_AUTHORIZATION")))`. Supply the complete header value. The Agent base URL must use HTTPS for credentials and contain no user info, query or fragment. The SDK sends the configured header on `/collect`. OAuth discovery and request signing are unsupported.
198199
- `execution-target=REMOTE_AGENT_HTTP` makes the availability probe report `SKIPPED_REMOTE_MODE` (treated as startable).
199200

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

‎README.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ cli.gemini().deepResearch("topic",
194194
- 旧版 HTTP argv 调用仅接收 SDK 清单中的适配器及其子命令。根命令、Browser 会话、外部程序透传、重复选项、`--` 以及无法保留边界空格或前导短横的参数会在发请求前被拒绝。位置参数应在选项前。需要原样传递 argv 时使用本地执行,已有自定义 Agent 契约时可用显式 `OpenCliCollectRequest` API。
195195
- 远程调用超时抛出 `OpenCliRemoteTimeoutException`。请求提交给 HTTP 传输后,`isRemoteOutcomeUnknown()` 为 true。客户端不会自动重试或跟随重定向。
196196
- 通过结果或异常的 `getPartialResult()` 调用 `getRemoteExecutionDetails()`,查看 HTTP 状态、Agent 业务状态和 `items` 的来源。`getExitCode()` 的 0/1 是兼容映射。HTTP 或协议失败快照没有退出码。仅在开启原文捕获时,失败快照才携带已通过字节上限检查的响应正文。
197+
- Agent 支持认证请求头时,可调用 `setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", System.getenv("OPENCLI_AGENT_AUTHORIZATION")))`,传入完整请求头值。认证须使用 HTTPS,Agent 基础地址须省略用户信息、查询参数和片段。SDK 只在 `/collect` 请求上发送已配置的认证头。OAuth 发现和请求签名尚不支持。
197198
- `execution-target=REMOTE_AGENT_HTTP` 时可用性探测报告 `SKIPPED_REMOTE_MODE`(视为可启动)。
198199

199200
<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
@@ -18,7 +18,7 @@
1818

1919
## 3. 三线与安全
2020

21-
- [ ] 3.1 对照 C09 测试凭据、URL query、body preview 和异常 cause 的默认脱敏边界。
21+
- [x] 3.1 验证凭据、URL query、正文和异常 cause 的默认诊断边界。见 OC-REMOTE-006 验证。
2222
- [ ] 3.2 在三分支分别跑本地 HTTP fixture;记录旧 API 的行为收紧与迁移例子。
2323
- [ ] 3.3 未取得服务端契约的扩展仍标记 unsupported,不借此宣称远程全量兼容。
2424

@@ -62,3 +62,10 @@ JDK 17 基线中,chunked 响应每 125 ms 持续发送数据,900 ms 的原
6262
对基线加入结果证据断言后,HTTP 200 业务失败、HTTP 503、缺省 `items` 和十种畸形响应共 13 项未能提供所需证据。修改后,`getRemoteExecutionDetails()` 保留 HTTP 状态、Agent 业务状态、失败层级和 `items` 来源。兼容退出值标记为 `SYNTHETIC_COMPATIBILITY`,观测到的远端退出码为空。HTTP 或协议失败快照保留真实状态且退出值为空,按原文捕获开关提供通过字节上限检查的完整响应。超限和超时沿用原有异常及保留策略。
6363

6464
验证覆盖 503 的 HTML 响应、可选原文与安全诊断、合法业务失败和协议失败。显式诊断导出先输出退出码来源,再输出兼容退出值,避免截断产生缺少来源的数字。
65+
66+
67+
## OC-REMOTE-006 显式认证与 TLS
68+
69+
基线先增加配置和夹具,尚未接入传输。HTTPS 认证成功、明文认证拒绝及三类 URL 凭据输入共 5 项验收失败。接入后,回环 HTTPS 服务使用独立测试证书和显式信任。未信任的证书在请求转交应用处理器前被拒绝。信任证书后,桩仅在明确收到正确的指定请求头时返回成功。去除配置后按 401 处理,不自动生成认证数据。错误凭据的 401 回显未出现在默认日志、异常栈或原文捕获关闭时的失败快照中。
70+
71+
显式认证采用 SDK 已有 Apache HttpClient 的 HTTPS 校验。明文认证、URL 用户信息、查询参数和片段均在发送前拒绝。测试复用了 WebSocket 的回环证书生成方式。真实 Agent 可接受的请求头和生产认证流程仍待部署契约验证。

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import java.util.List;
66
import java.util.Map;
77
import lombok.Data;
8+
import lombok.ToString;
89

910
/**
1011
* OpenCLI runtime configuration POJO with no Spring dependency.
@@ -49,8 +50,13 @@ public class OpenCliProperties {
4950
* 远端 Agent 根 URL(不含尾斜杠),例如 {@code http://192.168.1.10:19823}。
5051
* <p>仅当 {@link #executionTarget} 为 {@link OpenCliExecutionTarget#REMOTE_AGENT_HTTP} 时必填。</p>
5152
*/
53+
@ToString.Exclude
5254
private String remoteAgentBaseUrl;
5355

56+
/** Explicit credential header for the configured HTTPS Agent. */
57+
@ToString.Exclude
58+
private OpenCliRemoteAuthentication remoteAuthentication;
59+
5460
/**
5561
* 传给 Agent collect 的 {@code mode}:{@code bridge} 或 {@code cdp}(与 Agent 环境一致)。
5662
*/
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package io.github.easy4j.opencli;
2+
3+
import java.util.Objects;
4+
import java.util.regex.Pattern;
5+
import lombok.AccessLevel;
6+
import lombok.Getter;
7+
8+
/** A caller-supplied credential for an Agent's explicitly supported HTTP header. */
9+
@Getter
10+
public final class OpenCliRemoteAuthentication {
11+
12+
private static final Pattern HEADER_NAME =
13+
Pattern.compile("(?:Authorization|Api-Key|X-[A-Za-z0-9][A-Za-z0-9-]*)", Pattern.CASE_INSENSITIVE);
14+
private static final Pattern HEADER_VALUE = Pattern.compile("[!-~](?:[ -~]*[!-~])?");
15+
16+
private final String headerName;
17+
@Getter(AccessLevel.NONE)
18+
private final String headerValue;
19+
20+
/**
21+
* @param headerName Authorization, Api-Key or a custom X- header
22+
* @param headerValue complete printable ASCII credential value, including any scheme
23+
*/
24+
public OpenCliRemoteAuthentication(String headerName, String headerValue) {
25+
if (Objects.isNull(headerName) || !HEADER_NAME.matcher(headerName).matches()) {
26+
throw new IllegalArgumentException("Unsupported remote authentication header name");
27+
}
28+
if (Objects.isNull(headerValue) || !HEADER_VALUE.matcher(headerValue).matches()) {
29+
throw new IllegalArgumentException("Invalid remote authentication header value");
30+
}
31+
this.headerName = headerName;
32+
this.headerValue = headerValue;
33+
}
34+
/** @return the raw credential for the explicitly configured HTTP request */
35+
public String headerValue() {
36+
return headerValue;
37+
}
38+
}

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

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import tools.jackson.databind.ObjectReader;
77
import tools.jackson.databind.json.JsonMapper;
88
import io.github.easy4j.opencli.OpenCliProperties;
9+
import io.github.easy4j.opencli.OpenCliRemoteAuthentication;
910
import io.github.easy4j.opencli.core.OpenCliOutputParser;
1011
import io.github.easy4j.opencli.core.OpenCliRemoteExecutionDetails;
1112
import io.github.easy4j.opencli.core.OpenCliRemoteExecutionDetails.ItemsSource;
@@ -22,6 +23,7 @@
2223
import java.io.IOException;
2324
import java.io.InputStream;
2425
import java.net.SocketTimeoutException;
26+
import java.net.URI;
2527
import java.nio.charset.Charset;
2628
import java.nio.charset.StandardCharsets;
2729
import java.util.Objects;
@@ -111,11 +113,14 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
111113
throw failure("Failed to serialize collect request", correlationId);
112114
}
113115

114-
HttpPost post;
115-
try {
116-
post = new HttpPost(base.trim().replaceAll("/+$", "") + "/collect");
117-
} catch (IllegalArgumentException exception) {
118-
throw failure("Invalid agent HTTP endpoint", correlationId);
116+
URI endpoint = parseEndpoint(base, correlationId);
117+
OpenCliRemoteAuthentication authentication = properties.getRemoteAuthentication();
118+
HttpPost post = new HttpPost(endpoint);
119+
if (Objects.nonNull(authentication)) {
120+
if (!"https".equalsIgnoreCase(endpoint.getScheme())) {
121+
throw failure("Remote authentication requires an HTTPS Agent", correlationId);
122+
}
123+
post.setHeader(authentication.getHeaderName(), authentication.headerValue());
119124
}
120125
post.setEntity(new StringEntity(bodyJson, ContentType.APPLICATION_JSON));
121126
CloseableHttpClient client = transport();
@@ -125,6 +130,7 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
125130
}
126131
int remainingMillis = (int) Math.max(1, TimeUnit.NANOSECONDS.toMillis(remainingNanos));
127132
post.setConfig(RequestConfig.custom()
133+
.setAuthenticationEnabled(false)
128134
.setConnectionRequestTimeout(remainingMillis)
129135
.setConnectTimeout(remainingMillis)
130136
.setSocketTimeout(remainingMillis)
@@ -162,6 +168,21 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
162168
}
163169
}
164170

171+
private static URI parseEndpoint(String base, String correlationId) {
172+
URI endpoint;
173+
try {
174+
endpoint = URI.create(base.trim());
175+
} catch (IllegalArgumentException exception) {
176+
throw failure("Invalid agent HTTP endpoint", correlationId);
177+
}
178+
if ((!"http".equalsIgnoreCase(endpoint.getScheme()) && !"https".equalsIgnoreCase(endpoint.getScheme()))
179+
|| Objects.isNull(endpoint.getHost()) || Objects.nonNull(endpoint.getRawUserInfo())
180+
|| Objects.nonNull(endpoint.getRawQuery()) || Objects.nonNull(endpoint.getRawFragment())) {
181+
throw failure("Agent endpoint must be an HTTP base URL without user info, query or fragment", correlationId);
182+
}
183+
return URI.create(endpoint.toASCIIString().replaceAll("/+$", "") + "/collect");
184+
}
185+
165186
private CloseableHttpClient transport() {
166187
synchronized (transportLock) {
167188
if (closed) {

‎src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java‎

Lines changed: 5 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package io.github.easy4j.opencli.center.ws;
22

3+
import io.github.easy4j.opencli.testsupport.OpenCliTlsFixture;
34
import tools.jackson.databind.JsonNode;
45
import tools.jackson.databind.json.JsonMapper;
56
import tools.jackson.databind.node.ObjectNode;
@@ -10,14 +11,11 @@
1011
import java.io.PrintStream;
1112
import java.io.File;
1213
import tools.jackson.core.JacksonException;
13-
import java.io.InputStream;
1414
import java.net.InetSocketAddress;
1515
import java.nio.ByteBuffer;
1616
import java.nio.charset.StandardCharsets;
1717
import java.nio.file.Files;
1818
import java.nio.file.Path;
19-
import java.nio.file.Paths;
20-
import java.security.KeyStore;
2119
import java.util.Arrays;
2220
import java.util.Base64;
2321
import java.util.HashSet;
@@ -31,9 +29,7 @@
3129
import java.util.concurrent.atomic.AtomicBoolean;
3230
import java.util.concurrent.atomic.AtomicReference;
3331
import java.util.stream.Collectors;
34-
import javax.net.ssl.KeyManagerFactory;
3532
import javax.net.ssl.SSLContext;
36-
import javax.net.ssl.TrustManagerFactory;
3733
import org.java_websocket.WebSocket;
3834
import org.java_websocket.enums.Opcode;
3935
import org.java_websocket.handshake.ClientHandshake;
@@ -559,40 +555,14 @@ void plainWebSocketReconnectDoesNotExposePreviousSessionCache(@TempDir Path temp
559555
@ParameterizedTest
560556
@ValueSource(booleans = {false, true})
561557
void verifiedTlsReconnectReplaysOnlyAfterAnExplicitRetry(boolean failDelivery, @TempDir Path temporary) throws Exception {
562-
Path storePath = temporary.resolve("center.p12");
563-
String keytool = System.getProperty("os.name").startsWith("Windows") ? "keytool.exe" : "keytool";
564-
Path tool = Paths.get(System.getProperty("java.home"), "bin", keytool);
565-
Process keygen = new ProcessBuilder(tool.toString(), "-genkeypair", "-alias", "center", "-keyalg", "RSA",
566-
"-keysize", "2048", "-dname", "CN=localhost", "-ext", "SAN=IP:127.0.0.1", "-validity", "1",
567-
"-storetype", "PKCS12", "-keystore", storePath.toString(), "-storepass", "test-password")
568-
.redirectErrorStream(true).redirectOutput(temporary.resolve("keytool.log").toFile()).start();
569-
try {
570-
assertTrue(keygen.waitFor(10, TimeUnit.SECONDS));
571-
assertEquals(0, keygen.exitValue());
572-
} finally {
573-
if (keygen.isAlive()) {
574-
keygen.destroyForcibly();
575-
}
576-
}
577-
KeyStore store = KeyStore.getInstance("PKCS12");
578-
try (InputStream input = Files.newInputStream(storePath)) {
579-
store.load(input, "test-password".toCharArray());
580-
}
581-
KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
582-
keys.init(store, "test-password".toCharArray());
583-
SSLContext server = SSLContext.getInstance("TLS");
584-
server.init(keys.getKeyManagers(), null, null);
585-
TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
586-
trust.init(store);
587-
SSLContext trustedClient = SSLContext.getInstance("TLS");
588-
trustedClient.init(null, trust.getTrustManagers(), null);
558+
OpenCliTlsFixture tls = OpenCliTlsFixture.create(temporary);
589559
SSLContext previous = SSLContext.getDefault();
590560
try {
591-
SSLContext.setDefault(trustedClient);
561+
SSLContext.setDefault(tls.getTrustedClient());
592562
if (failDelivery) {
593-
verifyFailedDeliveryReplay(temporary, server);
563+
verifyFailedDeliveryReplay(temporary, tls.getServer());
594564
} else {
595-
verifyReconnectReplay(temporary, server, true);
565+
verifyReconnectReplay(temporary, tls.getServer(), true);
596566
}
597567
} finally {
598568
SSLContext.setDefault(previous);

0 commit comments

Comments
 (0)