Files
msa-agent/internal/config/config_test.go
T
chick 20070b90f7 fix: enroll 写出守护进程会拒绝的配置,install 写出与自身路径不符的单元
四处"校验在错误的层"的缺陷,都属于同一类:每个组件单独看都对,接缝错了。

1. `msa-agent enroll --relay http://relay.example` / `relay.example` /
   `https://relay.example/v1` 都会写出配置文件,install 报成功,守护进程在**下一次启动**才
   拒绝,日志里只有一行 "msa-agent exiting"。规则原本散在三处(config 只查非空、transport
   查真实规则、enroll 的注册客户端另有一份),现在收进 `internal/relayurl` 一份,三处都调它。
   `config.File.Validate` 因此也补上了 https/host/无路径/无 query 的检查。

2. `enroll` 不再自己手写字段检查,改为构造真正的 `config.File` 并调用真正的 `Validate`——
   一份"什么是可用配置"的定义,结构上无法再漂移。`config.Marshal` 让 enroll 与 Save 用同一个
   编码器。

3. `install --config /srv/msa/config.json` 会给该文件改属主、交给服务用户,然后写一个
   ExecStart 指向 `/etc/msa-agent/config.json` 的单元——服务起来找不到配置就退出,而它需要的
   文件就在别处、属主正确、从未被读。`enroll --audit /srv/audit/audit.log` 同理:单元的
   `ReadWritePaths` 只覆盖 `/var/log/msa-agent`,在 `ProtectSystem=strict` 下 agent 的
   `MkdirAll` 报 EROFS,进程启动即退出,报错既不提那个 flag 也不提那条指令。现在单元是模板,
   `RenderedUnit` 按实际布局渲染,`--print-unit` 打印的就是会被写入的那一份;默认布局渲染结果
   与仓库里被 review 过的文件逐字节相同,所以 vendored 副本的漂移检查仍然有意义。

测试:新增 `internal/relayurl`,`config`/`enroll`/`install` 各补回归测试。每条都做了变异验证
(把修复回退,对应测试必须失败)。
2026-09-18 12:38:56 +08:00

224 lines
7.6 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"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 rewrite must keep the file's owner. The deployment document tells the operator to run --pair
// with sudo while the installed config belongs to the msa-agent user; without preserving ownership
// the rename would leave a root-owned 0600 file that the systemd unit cannot read, so the pairing
// would look successful and the node would come up unable to load its own configuration.
//
// The test cannot become root, so it asserts the property that is observable without privileges:
// the owner after a save is the same as the owner before it, and the temp file does not survive.
func TestSavePreservesTheFileOwner(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.json")
cfg := valid()
if err := Save(path, cfg); err != nil {
t.Fatalf("first Save: %v", err)
}
before := owner(t, path)
// A second save goes through the ownership-preserving path. The inode necessarily changes — the
// write is a temp file plus a rename — so what is compared is the owner, which is the thing the
// rename would otherwise reset.
cfg.Devices = append(cfg.Devices, Device{
ID: "ap_second0001", SignKey: cfg.Devices[0].SignKey, RelayToken: strings.Repeat("b", 48),
})
if err := Save(path, cfg); err != nil {
t.Fatalf("second Save: %v", err)
}
after := owner(t, path)
if before != after {
t.Fatalf("the rewrite changed the owner from %v to %v", before, after)
}
if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
t.Fatal("a temp file was left behind")
}
reloaded, err := Load(path)
if err != nil {
t.Fatalf("Load after rewrite: %v", err)
}
if len(reloaded.Devices) != 2 {
t.Fatalf("the rewrite lost a device: %d", len(reloaded.Devices))
}
}
// 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")
}
}
// The relay URL used to be checked only for being non-empty, so a shape the transport refuses was
// accepted here and refused later — at dial time in the daemon, or at the next startup for a config
// `enroll` had already written and reported as success. These are the values that reached real nodes.
func TestValidateRefusesARelayURLTheDaemonCannotDial(t *testing.T) {
for _, raw := range []string{
"relay.example",
"http://relay.example",
"https://relay.example/v1",
"https://relay.example?x=1",
"https://",
} {
cfg := valid()
cfg.RelayURL = raw
if err := cfg.Validate(false); err == nil {
t.Errorf("accepted relayUrl %q", raw)
}
if err := cfg.Validate(true); err == nil {
t.Errorf("pair mode accepted relayUrl %q", raw)
}
}
cfg := valid()
cfg.RelayURL = "https://relay.example/"
if err := cfg.Validate(false); err != nil {
t.Fatalf("refused a trailing slash: %v", err)
}
}
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")
}
}
// owner reads the uid and gid of a path, which is what a rewrite must preserve.
func owner(t *testing.T, path string) string {
t.Helper()
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
t.Skip("stat_t is not available on this platform")
}
return fmt.Sprintf("%d:%d", stat.Uid, stat.Gid)
}