Files
msa-agent/internal/config/config_test.go
T
chick 78e0d303ab feat: 配对管理端点与中继侧设备注册上报
- agent --pair:临时监听 :3001 仅开放 /provision 与 /destroy,以节点密码为共享秘密;
  窗口由三个独立条件关闭(首次成功配对 / 失败尝试 10 次 / 10 分钟超时),配对成功后
  管理监听即关(设计 §7 第 4 步)
- agent 为每台配对手机生成中继 bearer(config.Save 0600 原子写;启动时为手写条目补发)
- transport.PushDevices:握手成功后全量上报本节点受信设备集;空集是吊销声明而非无操作
- relay /v1/agent/devices:agent 会话后鉴权的设备注册;全量替换本节点条目;
  操作员 MSA_DEVICES 为 static 不可被覆盖;跨节点 id 不可抢占
- 中继设备注册替代了 §11 第 6 项的一部分:节点 destroy + 重握手即可在路由层吊销
- 配置:provisionSecret 字段(无密码保护节点需显式设置才可配对);Validate(pairMode)
- 测试:pair 流程 8 项、设备注册 6 项、transport 1 项;文档 §7 实现修订注记与 README 状态
2026-09-16 11:43:52 +08:00

141 lines
4.7 KiB
Go

package config
import (
"os"
"path/filepath"
"testing"
)
// The interesting property is not that a good file parses, it is that a bad one is refused at boot.
// An agent that starts half-configured sits there answering nothing, and "why does nothing work" is
// much harder to diagnose than a service that will not start.
func valid() File {
return File{
NodeID: "nd_7f3a9c2e",
RelayURL: "https://relay.example",
AgentToken: "tok",
LocalPort: 8788,
SignKey: "AAAA",
KxKey: "AAAA",
AuditPath: "/var/log/msa-agent/audit.log",
Devices: []Device{{ID: "ap_5b1d0000", SignKey: "AAAA"}},
}
}
func TestValidateAcceptsACompleteFile(t *testing.T) {
if err := valid().Validate(false); err != nil {
t.Fatalf("a complete file was refused: %v", err)
}
}
// Pair mode relaxes exactly one rule: an empty device list is the starting state of a node that
// has not been paired yet, not a misconfiguration. Every other field still validates, because a
// pair-mode agent with a broken nodeId pairs successfully and then commands nothing.
func TestPairModeRelaxesOnlyTheDeviceList(t *testing.T) {
cfg := valid()
cfg.Devices = nil
if err := cfg.Validate(true); err != nil {
t.Fatalf("pair mode refused an empty device list: %v", err)
}
cfg.NodeID = "node-1"
if err := cfg.Validate(true); err == nil {
t.Fatal("pair mode accepted a malformed nodeId")
}
}
func TestSaveRoundTripsAndIsSixHundred(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.json")
cfg := valid()
if err := Save(path, cfg); err != nil {
t.Fatalf("Save: %v", err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("saved config mode is %v, want 0600", info.Mode().Perm())
}
reloaded, err := Load(path)
if err != nil {
t.Fatalf("Load after Save: %v", err)
}
if reloaded.NodeID != cfg.NodeID || len(reloaded.Devices) != 1 ||
reloaded.Devices[0].SignKey != cfg.Devices[0].SignKey {
t.Fatalf("round-trip lost fields: %+v", reloaded)
}
}
// A save must not be able to write a file that the next boot would refuse: the validation runs
// before the rename, so a caller building a device list with a bad id gets an error, not a
// corrupted file.
func TestSaveRefusesAnInvalidFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.json")
cfg := valid()
cfg.Devices[0].ID = "not-an-app-id"
if err := Save(path, cfg); err == nil {
t.Fatal("saved a device list the loader would refuse")
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatal("a failed save left a file behind")
}
}
func TestValidateNamesEveryMissingField(t *testing.T) {
cases := map[string]func(*File){
"nodeId": func(c *File) { c.NodeID = "" },
"relayUrl": func(c *File) { c.RelayURL = "" },
"token": func(c *File) { c.AgentToken = "" },
"signKey": func(c *File) { c.SignKey = "" },
"kxKey": func(c *File) { c.KxKey = "" },
"auditPath": func(c *File) { c.AuditPath = "" },
"devices": func(c *File) { c.Devices = nil },
"badNode": func(c *File) { c.NodeID = "node-1" },
"badApp": func(c *File) { c.Devices[0].ID = "phone" },
"noSignKey": func(c *File) { c.Devices[0].SignKey = "" },
"port0": func(c *File) { c.LocalPort = 0 },
"portHigh": func(c *File) { c.LocalPort = 70000 },
"duplicate": func(c *File) { c.Devices = append(c.Devices, c.Devices[0]) },
}
for name, mutate := range cases {
cfg := valid()
mutate(&cfg)
if err := cfg.Validate(false); err == nil {
t.Errorf("%s: a broken config was accepted", name)
}
}
}
// There is no host field, and this test is what keeps it that way: a "localHost" entry would be the
// one setting able to turn the agent into a LAN pivot.
func TestThereIsNoHostField(t *testing.T) {
raw := []byte(`{"nodeId":"nd_7f3a9c2e","relayUrl":"https://r","agentToken":"t","localHost":"10.0.0.5",
"localPort":8788,"signKey":"AAAA","kxKey":"AAAA","auditPath":"/tmp/a.log",
"devices":[{"id":"ap_5b1d0000","signKey":"AAAA"}]}`)
path := filepath.Join(t.TempDir(), "config.json")
if err := os.WriteFile(path, raw, 0o600); err != nil {
t.Fatal(err)
}
cfg, err := Load(path)
if err != nil {
t.Fatal(err)
}
// The unknown field is ignored, and the port is all the agent knows about the local service.
if cfg.LocalPort != 8788 {
t.Fatalf("localPort is %d", cfg.LocalPort)
}
}
func TestLoadReportsMissingAndMalformedFiles(t *testing.T) {
if _, err := Load(filepath.Join(t.TempDir(), "absent.json")); err == nil {
t.Fatal("a missing file was accepted")
}
path := filepath.Join(t.TempDir(), "broken.json")
if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil {
t.Fatal("a malformed file was accepted")
}
}