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` 各补回归测试。每条都做了变异验证 (把修复回退,对应测试必须失败)。
This commit is contained in:
+38
-33
@@ -20,6 +20,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"fun.chick/msa-agent/internal/config"
|
||||
"fun.chick/msa-agent/internal/wire"
|
||||
)
|
||||
|
||||
@@ -69,17 +70,12 @@ type Registration struct {
|
||||
}
|
||||
|
||||
// Generate mints the material and renders both artefacts.
|
||||
//
|
||||
// Every input rule is enforced by config.File.Validate below rather than restated here. The three
|
||||
// hand-written checks that used to stand here — relay URL non-empty, port in range, audit path present
|
||||
// — were a second, weaker copy of rules the daemon already had, and the relay URL one was the weakest
|
||||
// of the three: it accepted anything non-empty, including values the transport refuses at dial time.
|
||||
func Generate(opts Options) (Result, error) {
|
||||
if opts.RelayURL == "" {
|
||||
return Result{}, fmt.Errorf("enroll: relay URL is required")
|
||||
}
|
||||
if opts.LocalPort <= 0 || opts.LocalPort > 65535 {
|
||||
return Result{}, fmt.Errorf("enroll: local port %d is out of range", opts.LocalPort)
|
||||
}
|
||||
if opts.AuditPath == "" {
|
||||
return Result{}, fmt.Errorf("enroll: audit path is required")
|
||||
}
|
||||
|
||||
// The signing key is Ed25519: it answers the relay's handshake challenge and signs responses.
|
||||
signingPublic, signingKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
@@ -109,34 +105,43 @@ func Generate(opts Options) (Result, error) {
|
||||
pairingSecret = randomHex(16)
|
||||
}
|
||||
|
||||
config := map[string]any{
|
||||
"nodeId": nodeID,
|
||||
"relayUrl": opts.RelayURL,
|
||||
"agentToken": token,
|
||||
"localPort": opts.LocalPort,
|
||||
"signKey": base64.StdEncoding.EncodeToString(signingKey),
|
||||
"kxKey": base64.StdEncoding.EncodeToString(kxKey),
|
||||
"auditPath": opts.AuditPath,
|
||||
// Only used to authorise the pairing window on an unprotected node. Deleting it after pairing
|
||||
// is fine; nothing else reads it.
|
||||
"provisionSecret": pairingSecret,
|
||||
// The config is built as the type the daemon loads, and validated by the daemon's own rules before it
|
||||
// is written.
|
||||
//
|
||||
// This used to be a map[string]any with a handful of hand-written checks, and it produced configs the
|
||||
// daemon then refused: `--relay relay.example` (no scheme), `--relay https://relay.example/v1` (a
|
||||
// path), `--node node-1` (a malformed id) were all written happily, and the failure appeared later as
|
||||
// "msa-agent exiting" on a node the operator had just installed. Two places that must agree about
|
||||
// what a valid config is, with nothing checking the agreement — the same shape of defect as the
|
||||
// install command that skipped the service user.
|
||||
//
|
||||
// Building the real type and calling the real Validate makes the agreement structural: there is one
|
||||
// definition of a usable config and this cannot drift from it.
|
||||
file := config.File{
|
||||
NodeID: nodeID,
|
||||
RelayURL: opts.RelayURL,
|
||||
AgentToken: token,
|
||||
LocalPort: opts.LocalPort,
|
||||
SignKey: base64.StdEncoding.EncodeToString(signingKey),
|
||||
KxKey: base64.StdEncoding.EncodeToString(kxKey),
|
||||
AuditPath: opts.AuditPath,
|
||||
// Only used to authorise the pairing window on an unprotected node. Deleting it after pairing is
|
||||
// fine; nothing else reads it.
|
||||
ProvisionSecret: pairingSecret,
|
||||
NodePassword: opts.NodePassword,
|
||||
RelayCAFile: opts.RelayCAFile,
|
||||
SelfEnrolled: opts.SelfEnrolled,
|
||||
// Empty on purpose: devices are added by pairing (`msa-agent --pair`), which is the only path
|
||||
// that should ever be able to introduce a trusted phone.
|
||||
"devices": []any{},
|
||||
Devices: []config.Device{},
|
||||
}
|
||||
// Absent rather than empty when unset, so a config that has not been told about a password does not
|
||||
// claim the node has none.
|
||||
if opts.NodePassword != "" {
|
||||
config["nodePassword"] = opts.NodePassword
|
||||
}
|
||||
if opts.RelayCAFile != "" {
|
||||
config["relayCAFile"] = opts.RelayCAFile
|
||||
}
|
||||
if opts.SelfEnrolled {
|
||||
config["selfEnrolled"] = true
|
||||
// pairMode relaxes exactly the empty-device rule, which is the state enrollment produces: the node
|
||||
// has keys and no phone yet.
|
||||
if err := file.Validate(true); err != nil {
|
||||
return Result{}, fmt.Errorf("enroll: refusing to write a config the agent would not load: %w", err)
|
||||
}
|
||||
|
||||
encoded, err := json.MarshalIndent(config, "", " ")
|
||||
encoded, err := config.Marshal(file)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("enroll: encoding the config: %w", err)
|
||||
}
|
||||
|
||||
@@ -129,6 +129,25 @@ func TestTwoEnrollmentsDiffer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Enrollment is where a bad relay URL is cheapest to catch and where it used to be missed entirely.
|
||||
// It built a map[string]any with a handful of hand-written checks, so `--relay relay.example` and
|
||||
// `--relay https://relay.example/v1` both produced a config file, the install reported success, and
|
||||
// the daemon refused the file at the next startup. The values below are the ones that were measured
|
||||
// being written.
|
||||
func TestARelayURLTheDaemonWouldRefuseIsNeverWritten(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"relay.example",
|
||||
"http://relay.example",
|
||||
"https://relay.example/v1",
|
||||
"https://relay.example?x=1",
|
||||
"https://",
|
||||
} {
|
||||
if _, err := Generate(Options{RelayURL: raw, LocalPort: 3000, AuditPath: "/a"}); err == nil {
|
||||
t.Errorf("wrote a config for relay %q", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingInputIsRefused(t *testing.T) {
|
||||
cases := map[string]Options{
|
||||
"no relay": {LocalPort: 3000, AuditPath: "/a"},
|
||||
|
||||
@@ -9,10 +9,11 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"fun.chick/msa-agent/internal/relayurl"
|
||||
)
|
||||
|
||||
// Register announces this node to the relay, using a one-time code an operator generated in the app.
|
||||
@@ -43,14 +44,11 @@ type RegisterOptions struct {
|
||||
// The failure vocabulary is deliberately small and each case names the next action, because this runs
|
||||
// during an install and the operator is looking at one line of output.
|
||||
func Register(ctx context.Context, opts RegisterOptions) error {
|
||||
parsed, err := url.Parse(opts.RelayURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("enroll: relay url: %w", err)
|
||||
}
|
||||
if parsed.Scheme != "https" {
|
||||
// https is not negotiable here for the same reason the agent refuses it: a registration sent in
|
||||
// the clear can be replayed by anyone who sees it, and the code is single-use.
|
||||
return fmt.Errorf("enroll: relay url must be https, got %q", parsed.Scheme)
|
||||
// The same rule the daemon applies, from the same package. This check is not redundant with the
|
||||
// config validation in Generate: registration happens *before* the config is written, so a URL this
|
||||
// rejected late would already have been sent to a host the operator did not mean to reach.
|
||||
if err := relayurl.Validate(opts.RelayURL); err != nil {
|
||||
return fmt.Errorf("enroll: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(opts.Code) == "" {
|
||||
return fmt.Errorf("enroll: the enrollment code is empty")
|
||||
|
||||
Reference in New Issue
Block a user