Skip to content

Commit 88d4eab

Browse files
committed
Verify the real OpenCLI Agent behind local TLS authentication
1 parent 58f675a commit 88d4eab

4 files changed

Lines changed: 139 additions & 4 deletions

File tree

‎openspec/changes/harden-opencli-remote-collect/evidence/2026-11-19-live-agent.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,32 @@ uv run --no-project --with fastapi==0.165.0 --with pydantic==2.14.3 \
4040
```
4141

4242
在 SDK 功能分支以对应 JDK 执行 `OpenCliRemoteAgentHttpClientTest`,从生成的 Surefire XML 读取 `java.class.path`。用该 classpath 编译 [OpenCliAdminLoopbackProbe](fixtures/OpenCliAdminLoopbackProbe.java),再用同一 classpath 加上探针输出目录运行,唯一参数为 `http://127.0.0.1:19823`。复现旧端口问题时,在无其他请求的临时 Agent 上改用 19825 并执行同一探针,首个成功断言会得到业务失败,Agent 日志会显示子进程退出 78。
43+
44+
## HTTPS 和显式 Authorization
45+
46+
在同一版本真实 Agent 前加入 [回环 TLS 代理](fixtures/opencli_agent_tls_proxy.py)。代理使用独立监听套接字,校验 Authorization 后只转发 JSON 请求体。证书只包含 IP SAN 127.0.0.1。Java 使用临时 JKS 信任库和 SDK 默认主机名校验。
47+
48+
| 每条 Java 功能线的场景 | 观察结果 |
49+
| --- | --- |
50+
| 有效模拟令牌 | 收到 HTTP 200 与实际 CLI 帮助。Agent 每线收到一次请求。 |
51+
| 缺少令牌或错误令牌 | 两次均收到 HTTP 401,SDK 保留 HTTP 状态并标为 HTTP_FAILURE,CLI 退出码为空。 |
52+
| 请求主机名改为 localhost | 证书名称不匹配,SDK 标为 TRANSPORT_FAILURE,HTTP 状态为空。 |
53+
54+
Java 8 `afc6b33`、Java 17 `58f675a` 和 Java 21 `5cfa937` 各通过四项。代理日志显示三次转发和六次拒绝。主机名不匹配的请求未进入代理路由。三份 Java 输出与完整异常栈均未出现金丝雀令牌。认证由回环代理执行,生产 Agent 的网关、凭据和部署策略仍需现场验收。
55+
56+
复用前一节的 Agent 源码、OpenCLI 环境和隔离启动脚本,把代理脚本复制到临时目录。生成专用于该目录的证书、信任库和随机测试令牌。
57+
58+
```sh
59+
openssl req -x509 -newkey rsa:2048 -sha256 -nodes -days 1 \
60+
-subj '/CN=OpenCLI Loopback Fixture' -addext 'subjectAltName=IP:127.0.0.1' \
61+
-keyout key.pem -out cert.pem
62+
keytool -importcert -noprompt -storetype JKS -keystore trust.jks \
63+
-storepass changeit -alias opencli-loopback -file cert.pem
64+
openssl rand -hex 24 > token
65+
chmod 600 token
66+
uv run --no-project --with fastapi==0.165.0 --with pydantic==2.14.3 \
67+
--with uvicorn==0.54.0 --with pyyaml==6.0.3 --with httpx==0.28.1 \
68+
python opencli_agent_tls_proxy.py
69+
```
70+
71+
在对应 JDK 下运行同一个 Java 探针,启动参数增加 `-Djavax.net.ssl.trustStore` 和 `-Djavax.net.ssl.trustStorePassword`。探针依次读取 HTTPS 端点和令牌文件绝对路径。代理端口记录在临时目录的 `tls-port` 中。复跑结束后,在临时目录创建 `stop` 让两个监听器正常退出。

‎openspec/changes/harden-opencli-remote-collect/evidence/fixtures/OpenCliAdminLoopbackProbe.java‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,32 @@
11
import io.github.easy4j.opencli.OpenCliExecutionTarget;
22
import io.github.easy4j.opencli.OpenCliProperties;
3+
import io.github.easy4j.opencli.OpenCliRemoteAuthentication;
34
import io.github.easy4j.opencli.core.OpenCliExecutor;
45
import io.github.easy4j.opencli.core.OpenCliRemoteExecutionDetails;
56
import io.github.easy4j.opencli.core.OpenCliResult;
7+
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
68
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
9+
import java.io.IOException;
10+
import java.io.PrintWriter;
11+
import java.io.StringWriter;
712
import java.net.URI;
13+
import java.nio.charset.StandardCharsets;
14+
import java.nio.file.Files;
15+
import java.nio.file.Paths;
816
import java.util.Objects;
917

1018
public final class OpenCliAdminLoopbackProbe {
1119

12-
public static void main(String[] args) {
20+
public static void main(String[] args) throws IOException {
1321
URI endpoint = URI.create(args[0]);
1422
require("127.0.0.1".equals(endpoint.getHost()), "test Agent must be on IPv4 loopback");
15-
try (OpenCliExecutor executor = executor(endpoint, false)) {
23+
if (args.length == 2) {
24+
require("https".equals(endpoint.getScheme()), "TLS proxy requires HTTPS");
25+
String token = new String(Files.readAllBytes(Paths.get(args[1])), StandardCharsets.US_ASCII).trim();
26+
verifyTlsProxy(endpoint, token);
27+
return;
28+
}
29+
try (OpenCliExecutor executor = executor(endpoint, false, null)) {
1630
OpenCliResult help = executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
1731
verify(help, true);
1832
require(help.getStdout().contains("opencli npm search"), "structured CLI help is missing");
@@ -28,7 +42,7 @@ public static void main(String[] args) {
2842
require(result.getStderr().contains("opencli exit"), "the Agent's business error is missing");
2943
}
3044
}
31-
try (OpenCliExecutor executor = executor(endpoint, true)) {
45+
try (OpenCliExecutor executor = executor(endpoint, true, null)) {
3246
OpenCliResult help = executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
3347
verify(help, true);
3448
require(Objects.nonNull(help.getRemoteRawHttpBody()) && help.getRemoteRawHttpBody().contains("opencli npm search"),
@@ -37,12 +51,48 @@ public static void main(String[] args) {
3751
System.out.println("PASS: real Agent help, missing-argument failure, and opt-in raw HTTP capture");
3852
}
3953

40-
private static OpenCliExecutor executor(URI endpoint, boolean capture) {
54+
private static void verifyTlsProxy(URI endpoint, String token) {
55+
try (OpenCliExecutor executor = executor(endpoint, false, "Bearer " + token)) {
56+
OpenCliResult help = executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
57+
verify(help, true);
58+
require(help.getStdout().contains("opencli npm search"), "structured CLI help is missing");
59+
require(Objects.isNull(help.getRemoteRawHttpBody()), "raw capture must be off by default");
60+
}
61+
verifyRejected(endpoint, null, 401);
62+
verifyRejected(endpoint, "Bearer invalid-" + token, 401);
63+
verifyRejected(URI.create("https://localhost:" + endpoint.getPort()), "Bearer " + token, 0);
64+
System.out.println("PASS: real Agent through TLS, missing and invalid credentials, and certificate hostname rejection");
65+
}
66+
67+
private static void verifyRejected(URI endpoint, String credential, int status) {
68+
try (OpenCliExecutor executor = executor(endpoint, false, credential)) {
69+
executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
70+
throw new AssertionError("proxy unexpectedly accepted the request");
71+
} catch (OpenCliExecutableFailureException failure) {
72+
OpenCliResult result = failure.getPartialResult();
73+
OpenCliRemoteExecutionDetails details = result.getRemoteExecutionDetails();
74+
require(details.getObservedHttpStatus().orElse(0) == status, "wrong observed HTTP status");
75+
require(details.getOutcome() == (status == 0 ? OpenCliRemoteExecutionDetails.Outcome.TRANSPORT_FAILURE
76+
: OpenCliRemoteExecutionDetails.Outcome.HTTP_FAILURE), "wrong rejection classification");
77+
require(Objects.isNull(result.getExitCode()), "rejection must not invent an exit code");
78+
require(Objects.isNull(result.getRemoteRawHttpBody()), "raw capture must be off by default");
79+
if (Objects.nonNull(credential)) {
80+
StringWriter diagnostics = new StringWriter();
81+
failure.printStackTrace(new PrintWriter(diagnostics));
82+
require(!diagnostics.toString().contains(credential), "exception included the authorization value");
83+
}
84+
}
85+
}
86+
87+
private static OpenCliExecutor executor(URI endpoint, boolean capture, String credential) {
4188
OpenCliProperties properties = new OpenCliProperties();
4289
properties.setExecutionTarget(OpenCliExecutionTarget.REMOTE_AGENT_HTTP);
4390
properties.setRemoteAgentBaseUrl(endpoint.toString());
4491
properties.setRemoteCollectMode("bridge");
4592
properties.setRemoteCaptureRawHttpResponse(capture);
93+
if (Objects.nonNull(credential)) {
94+
properties.setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", credential));
95+
}
4696
return new OpenCliExecutor(properties);
4797
}
4898

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""Run a TLS proxy and locked OpenCLI Agent on two IPv4 loopback sockets."""
2+
import asyncio
3+
import hmac
4+
import socket
5+
from pathlib import Path
6+
7+
import httpx
8+
import uvicorn
9+
from fastapi import FastAPI, Request, Response
10+
11+
from agent_server import app as agent
12+
13+
14+
def listener():
15+
sock = socket.socket()
16+
sock.bind(("127.0.0.1", 0))
17+
return sock
18+
19+
20+
async def main():
21+
backend, frontend = listener(), listener()
22+
agent_url = f"http://127.0.0.1:{backend.getsockname()[1]}/collect"
23+
Path("tls-port").write_text(str(frontend.getsockname()[1]))
24+
credential = "Bearer " + Path("token").read_text().strip()
25+
proxy = FastAPI()
26+
27+
@proxy.post("/collect")
28+
async def collect(request: Request):
29+
supplied = request.headers.get("authorization", "")
30+
data = await request.body()
31+
if not hmac.compare_digest(supplied, credential):
32+
print("proxy rejected missing or invalid credential", flush=True)
33+
return Response(status_code=401, headers={"WWW-Authenticate": "Bearer"})
34+
assert credential.encode() not in data
35+
async with httpx.AsyncClient(timeout=10, trust_env=False) as client:
36+
response = await client.post(agent_url, content=data, headers={"Content-Type": "application/json"})
37+
print(f"proxy forwarded one accepted request, Agent HTTP {response.status_code}", flush=True)
38+
return Response(response.content, status_code=response.status_code, media_type="application/json")
39+
40+
server = uvicorn.Server(uvicorn.Config(agent, access_log=False))
41+
tls = uvicorn.Server(uvicorn.Config(proxy, access_log=False, ssl_keyfile="key.pem", ssl_certfile="cert.pem"))
42+
local = asyncio.create_task(server.serve(sockets=[backend]))
43+
edge = asyncio.create_task(tls.serve(sockets=[frontend]))
44+
try:
45+
for _ in range(600):
46+
if Path("stop").exists() or local.done() or edge.done():
47+
break
48+
await asyncio.sleep(0.5)
49+
finally:
50+
server.should_exit = tls.should_exit = True
51+
await asyncio.gather(local, edge)
52+
53+
54+
asyncio.run(main())

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,5 @@ argv 入口继续限制为 SDK 已登记适配器和可保真转换的参数。
100100
本地 macOS 按平台步骤分别运行 Java 8、17、21,三线各执行 202 项,协议层各记录 93 项,其中 HTTP 套件 58 项。两个非法响应字符集用例均实际执行,覆盖收到 HTTP 200 和 503 时保留状态。三线零失败、零错误、零跳过。GitHub 平台结果按对应功能提交核验。
101101

102102
实际 Agent 与 OpenCLI 1.8.8 的三线回环验收及默认端口兼容性差异见 [联调记录](evidence/2026-11-19-live-agent.md)。
103+
104+
同一实际 Agent 的三线 HTTPS、Authorization 及证书名称负例,也已写入 [联调记录](evidence/2026-11-19-live-agent.md#https-和显式-authorization)。

0 commit comments

Comments
 (0)