四处"校验在错误的层"的缺陷,都属于同一类:每个组件单独看都对,接缝错了。 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` 各补回归测试。每条都做了变异验证 (把修复回退,对应测试必须失败)。
176 lines
7.5 KiB
Go
176 lines
7.5 KiB
Go
// Package enroll mints the key material, identifiers and secrets a node needs, and renders the two
|
|
// artefacts an operator has to place: the agent's config file and the relay's registration entry.
|
|
//
|
|
// It exists as a package rather than as a command because two callers need the same thing and must
|
|
// not drift. `msa-keygen` was the first, and it required a Go toolchain on whichever machine ran it —
|
|
// fine when that was the operator's laptop, wrong now that enrollment happens on the node itself,
|
|
// where there is a cross-compiled binary and no toolchain. `msa-agent enroll` is the second caller,
|
|
// and it is the same code path, so the two can never disagree about what a config looks like.
|
|
//
|
|
// What it deliberately does NOT do: invent the node's SimAdmin password. That is the operator's, and
|
|
// it is the one secret a tool must not make up. An unprotected node needs no value; a protected one
|
|
// needs the real one, or every command fails with node_auth_failed and the cause is not obvious.
|
|
package enroll
|
|
|
|
import (
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"fun.chick/msa-agent/internal/config"
|
|
"fun.chick/msa-agent/internal/wire"
|
|
)
|
|
|
|
// Options are what the caller knows and cannot derive.
|
|
type Options struct {
|
|
// RelayURL is the relay this node will connect to. https; the agent refuses anything else.
|
|
RelayURL string
|
|
// LocalPort is the SimAdmin port on 127.0.0.1. There is deliberately no host.
|
|
LocalPort int
|
|
// AuditPath is where the audit log is appended.
|
|
AuditPath string
|
|
// NodeID, AgentToken and ProvisionSecret are generated when empty. They are settable so an
|
|
// operator re-enrolling a node can keep the identifiers the relay already knows.
|
|
NodeID string
|
|
AgentToken string
|
|
ProvisionSecret string
|
|
// RelayCAFile pins the relay's CA instead of the system trust store. Optional.
|
|
RelayCAFile string
|
|
// NodePassword is written into the config when non-empty. Never generated.
|
|
NodePassword string
|
|
// SelfEnrolled records that this node registered itself with a one-time code, so `uninstall` can
|
|
// tell the operator which of the relay's two records mentions it.
|
|
SelfEnrolled bool
|
|
}
|
|
|
|
// Result is everything the caller has to place or show.
|
|
type Result struct {
|
|
// Config is the agent config file, ready to write 0600.
|
|
Config []byte
|
|
// Registration is the relay's agents.json entry, as compact JSON.
|
|
Registration []byte
|
|
// NodeID and ProvisionSecret are echoed because both have to be shown to the operator.
|
|
NodeID string
|
|
ProvisionSecret string
|
|
}
|
|
|
|
// Registration is the relay's view of this node: an id, a bearer token, and the public key that
|
|
// verifies its handshake signatures.
|
|
//
|
|
// The signing key is the part that cannot be omitted, and the reason is not tidiness. The relay
|
|
// refuses to start when an entry has no usable key — it did ship once with an optional verifier that
|
|
// nobody supplied, and the result was a relay that reported healthy and answered every node with 500.
|
|
type Registration struct {
|
|
NodeID string `json:"nodeID"`
|
|
Token string `json:"token"`
|
|
SignKey string `json:"signKey"`
|
|
}
|
|
|
|
// 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) {
|
|
// 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 {
|
|
return Result{}, fmt.Errorf("enroll: generating the signing key: %w", err)
|
|
}
|
|
// The key-agreement key is raw X25519. Clamping is the curve library's job, and a stored key that
|
|
// had already been clamped would be a second, non-standard encoding to keep in sync across three
|
|
// languages.
|
|
kxKey := make([]byte, wire.KeyBytes)
|
|
if _, err := rand.Read(kxKey); err != nil {
|
|
return Result{}, fmt.Errorf("enroll: generating the key-agreement key: %w", err)
|
|
}
|
|
|
|
nodeID := opts.NodeID
|
|
if nodeID == "" {
|
|
nodeID = "nd_" + randomHex(5)
|
|
}
|
|
token := opts.AgentToken
|
|
if token == "" {
|
|
token = randomHex(32)
|
|
}
|
|
// The pairing secret is minted even though an unprotected node is the only thing that needs it: a
|
|
// config without one cannot pair at all, and discovering that at pairing time means another trip to
|
|
// the node. When the node *is* protected, nodePassword takes precedence and this value is unused.
|
|
pairingSecret := opts.ProvisionSecret
|
|
if pairingSecret == "" {
|
|
pairingSecret = randomHex(16)
|
|
}
|
|
|
|
// 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: []config.Device{},
|
|
}
|
|
// 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 := config.Marshal(file)
|
|
if err != nil {
|
|
return Result{}, fmt.Errorf("enroll: encoding the config: %w", err)
|
|
}
|
|
encoded = append(encoded, '\n')
|
|
|
|
registration, err := json.Marshal(Registration{
|
|
NodeID: nodeID,
|
|
Token: token,
|
|
SignKey: base64.StdEncoding.EncodeToString(signingPublic),
|
|
})
|
|
if err != nil {
|
|
return Result{}, fmt.Errorf("enroll: encoding the registration: %w", err)
|
|
}
|
|
|
|
return Result{
|
|
Config: encoded,
|
|
Registration: registration,
|
|
NodeID: nodeID,
|
|
ProvisionSecret: pairingSecret,
|
|
}, nil
|
|
}
|
|
|
|
func randomHex(bytes int) string {
|
|
raw := make([]byte, bytes)
|
|
if _, err := rand.Read(raw); err != nil {
|
|
// rand.Read only fails if the system entropy source is gone, in which case nothing here can run
|
|
// safely: a key minted from a broken source is worse than no key.
|
|
panic(fmt.Sprintf("enroll: entropy source failed: %v", err))
|
|
}
|
|
return hex.EncodeToString(raw)
|
|
}
|