Files
homeagent-sdk/tools/hmapdev/proxy_config_test.go
JianFeeeee a176cc3e20 feat(sdk): 反代声明(ProxyDef / RegisterProxy)—— 插件声明服务,HomeAgent 反代出去
配套核心仓「webui 通用反向代理」。SDK 1.4.0 尚未发布,接口未冻结,
本次按开发期自由变更处理(正式发版时并入版本号推进)。

## 声明契约

plugin.json 的 proxies 字段(声明式,静态可发现)或 RegisterProxy
(运行期,供没有 plugin.json 的内置插件用):

    {"name":"ui","host":"myapp","path":"/p/myapp","strip_path":true,
     "target":"127.0.0.1:12100","auth":"homeagent"}

命名与既有能力对齐(ToolDef / ChannelDef / ConfigDef / RegisterTool /
ToolRegistrar)——第一版写成 ProxyDecl / DeclareProxy / ProxyDeclarer
被评审指出「跟 SDK 其他接口不是一个风格」,已全面改名。

## strip_path:Path 的两种语义

Path 不能一刀切成「原样保留」,真实需求有两种且**不能自动判定**
(同一个 path 在两种语义下都说得通,猜错即全部 404 且像上游故障):

  strip_path 缺省/false(别名模式)—— path 是上游真实路径的一部分
    /api/v1/device/ws + path=/api/v1/device → 上游收到原样
    适用:客户端**已硬编码**路径的机器接口(设备网关即如此)

  strip_path=true(前缀模式)—— path 只是门户上的挂载点
    /p/myapp/api/status + path=/p/myapp → 上游收到 /api/status
    适用:自带 UI 的服务(前端用相对路径)

非法组合(strip_path 而无 path)被 ValidateProxyDef 挡住。

## 单一入口原则(契约级要求)

一个声明 = 一个入口。两种挂载形态对「根路径」处理截然不同:
Host 形态下根路径是插件的根(fetch('/api/x') 天然正确);
Path 形态下根路径**属于门户**,同样代码会打到门户自己身上
(静默错路由:页面能开、功能全坏)。

故被反代的插件必须**一律使用相对路径**,绝不硬编码以 / 开头的绝对路径。
这样同一份前端在两种形态下都正确,插件不必知道自己被挂在哪,
反代层也能按外部条件(子域是否有证书/放行)自由选择形态。

## 判据

sdk/proxy_test.go:两种语义的映射、非法组合、单一入口原则的契约存在性。
hmapdev proxy_config_test.go:schema 漂移保护(新增字段忘了同步就判红)、
非法声明在**打包时**就被拒(不必装到 HomeAgent 才看到)。

两模块 go test 全绿;文档站已重新生成(ProxyDef 与单一入口原则进入
docs/api/misc.md 与 llms-full.txt)。

## 顺带修回的一处(此前随工作树丢失)

writePluginJSON 漏写 proxies 键 —— 漏写的话插件装得上、启动正常、
就是不出现,没有任何报错。该 bug 曾在核心仓侧出现过(判据抓到过),
这次移植时由 TestWritePluginJSONPreservesProxies 再次判红并修复。
2026-09-26 14:08:30 +08:00

137 lines
4.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
// writePluginJSON 是「白名单 map 重建」,新增字段若忘了同步进 map 会被静默丢弃。
// 本测试钉住这件事:声明了 proxies 的插件,产物 plugin.json 里必须还有 proxies。
func TestWritePluginJSONPreservesProxies(t *testing.T) {
dir := t.TempDir()
old, _ := os.Getwd()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
defer os.Chdir(old)
plg := &PlgConfig{
Name: "demo",
NameZh: "示例",
NameEn: "Demo",
Version: "0.1.0",
Author: "test",
Entry: "plugin.bin",
Tags: []string{"demo"},
Proxies: []ProxyConfig{
{Name: "ui", Host: "demo", Target: "127.0.0.1:12100"},
{Name: "gw", Host: "demo-gw", Target: "127.0.0.1:9890", WebSocket: true, Auth: "none"},
},
}
writePluginJSON(plg, []string{"linux"}, "plugin.bin")
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
if err != nil {
t.Fatal(err)
}
var got map[string]interface{}
if err := json.Unmarshal(raw, &got); err != nil {
t.Fatal(err)
}
proxies, ok := got["proxies"].([]interface{})
if !ok {
t.Fatalf("产物 plugin.json 丢了 proxies 字段,内容:%s", raw)
}
if len(proxies) != 2 {
t.Fatalf("proxies 条数 = %d,期望 2", len(proxies))
}
first, _ := proxies[0].(map[string]interface{})
if first["target"] != "127.0.0.1:12100" || first["host"] != "demo" {
t.Errorf("第 1 条声明内容不对: %v", first)
}
second, _ := proxies[1].(map[string]interface{})
if second["websocket"] != true || second["auth"] != "none" {
t.Errorf("第 2 条声明丢了 websocket/auth: %v", second)
}
}
// 没声明 proxies 时不应凭空冒出该字段(保持旧产物的字段集合不变)。
func TestWritePluginJSONOmitsEmptyProxies(t *testing.T) {
dir := t.TempDir()
old, _ := os.Getwd()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
defer os.Chdir(old)
writePluginJSON(&PlgConfig{Name: "nop", Entry: "plugin.bin"}, nil, "plugin.bin")
raw, _ := os.ReadFile(filepath.Join(dir, "plugin.json"))
if strings.Contains(string(raw), "proxies") {
t.Errorf("未声明 proxies 却出现在产物里:%s", raw)
}
}
// 字段漂移守卫:ProxyConfig 的 JSON 键必须与 proxySchemaKeys 完全一致。
// 加字段时若只改结构体不改这个清单,测试会红,提醒同步内核侧解析与文档。
func TestProxyConfigSchemaKeys(t *testing.T) {
raw, err := json.Marshal(ProxyConfig{})
if err != nil {
t.Fatal(err)
}
var m map[string]interface{}
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
// 空结构体 + omitempty 会全部省略,所以改用非零值探测。
// 每个字段都必须出现在探测体里,否则「新增字段忘了同步」检测不出来。
raw, _ = json.Marshal(ProxyConfig{
Name: "n", Host: "h", Path: "/p", StripPath: true,
Target: "t", WebSocket: true, Auth: "a",
})
m = nil
_ = json.Unmarshal(raw, &m)
if len(m) != len(proxySchemaKeys) {
t.Fatalf("ProxyConfig 有 %d 个 JSON 键,proxySchemaKeys 列了 %d 个;请同步",
len(m), len(proxySchemaKeys))
}
for _, k := range proxySchemaKeys {
if _, ok := m[k]; !ok {
t.Errorf("proxySchemaKeys 列了 %q,但 ProxyConfig 序列化后没有该键", k)
}
}
}
// validateProxies 必须让插件作者在**打包时**就发现写错的声明。
func TestValidateProxies(t *testing.T) {
ok := [][]ProxyConfig{
{{Target: "127.0.0.1:12100"}},
{{Target: "http://127.0.0.1:12100", Host: "aaa"}},
{{Target: "127.0.0.1:9890", Host: "devices", WebSocket: true, Auth: "none"}},
{{Target: "https://example.com"}}, // 远程允许
}
for i, list := range ok {
if err := validateProxies(list); err != nil {
t.Errorf("合法集合 #%d 被拒: %v", i, err)
}
}
bad := [][]ProxyConfig{
{{Target: ""}},
{{Target: " "}},
{{Target: "127.0.0.1:1", Auth: "nope"}},
{{Target: "127.0.0.1:1", Host: "a_b"}},
{{Target: "127.0.0.1:1", Host: "-x"}},
{{Target: "127.0.0.1:1", Host: "X"}},
{{Target: "127.0.0.1:notaport"}},
{{Target: "127.0.0.1:99999"}},
{{Target: "127.0.0.1:1", Host: "dup"}, {Target: "127.0.0.1:2", Host: "dup"}}, // 同包内重复
}
for i, list := range bad {
if err := validateProxies(list); err == nil {
t.Errorf("非法集合 #%d 应被拒: %+v", i, list)
}
}
}