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 状态
This commit is contained in:
+129
-25
@@ -7,6 +7,8 @@ package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -24,6 +26,10 @@ type Device struct {
|
||||
// it and holds no corresponding secret, so a phone cannot be impersonated from the relay side.
|
||||
SignKey string `json:"signKey"`
|
||||
Name string `json:"name,omitempty"`
|
||||
// RelayToken is the bearer credential the phone presents to the relay for this pairing. The
|
||||
// agent generated it at pairing time and re-registers it with the relay on every handshake,
|
||||
// because the relay holds no state across restarts.
|
||||
RelayToken string `json:"relayToken,omitempty"`
|
||||
}
|
||||
|
||||
// File is the on-disk shape.
|
||||
@@ -45,33 +51,23 @@ type File struct {
|
||||
// commands with node_auth_failed rather than looping against a lockout.
|
||||
NodePassword string `json:"nodePassword,omitempty"`
|
||||
// AuditPath is where the audit log is appended.
|
||||
AuditPath string `json:"auditPath"`
|
||||
Devices []Device `json:"devices"`
|
||||
}
|
||||
|
||||
// Load reads and validates a config file.
|
||||
//
|
||||
// Validation is exhaustive rather than partial on purpose: an agent that starts with a missing
|
||||
// device or a bad port would sit there healthy and uncommandable, which is harder to notice than a
|
||||
// crash at boot.
|
||||
func Load(path string) (File, error) {
|
||||
var cfg File
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
if err := decoder.Decode(&cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config: decode %s: %w", path, err)
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return cfg, fmt.Errorf("config: %s: %w", path, err)
|
||||
}
|
||||
return cfg, nil
|
||||
AuditPath string `json:"auditPath"`
|
||||
// Devices may be empty only in pair mode (--pair). In normal operation an agent with no
|
||||
// paired devices refuses to start, because it could authorise nothing.
|
||||
Devices []Device `json:"devices"`
|
||||
// ProvisionSecret is the shared secret a phone must present to pair during the temporary
|
||||
// --pair window (design §7 step 2, "以节点密码作为共享秘密"). When the node is protected it
|
||||
// defaults to NodePassword; an unprotected node needs an explicit value here or pairing is
|
||||
// refused. It is secret material and lives in the config file like the private keys do.
|
||||
ProvisionSecret string `json:"provisionSecret,omitempty"`
|
||||
}
|
||||
|
||||
// Validate checks every field the agent depends on.
|
||||
func (c File) Validate() error {
|
||||
//
|
||||
// pairMode relaxes exactly one rule: devices may be empty while the agent is waiting to be
|
||||
// paired. Everything else stays enforced, because a pair-mode agent with a broken nodeId or a
|
||||
// missing key would pair successfully and then command nothing.
|
||||
func (c File) Validate(pairMode bool) error {
|
||||
if !nodePattern.MatchString(c.NodeID) {
|
||||
return errors.New("nodeId must look like nd_xxxxxxxx")
|
||||
}
|
||||
@@ -93,7 +89,7 @@ func (c File) Validate() error {
|
||||
if c.AuditPath == "" {
|
||||
return errors.New("auditPath is required")
|
||||
}
|
||||
if len(c.Devices) == 0 {
|
||||
if len(c.Devices) == 0 && !pairMode {
|
||||
return errors.New("devices is empty, so no phone could ever be authorised")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
@@ -111,3 +107,111 @@ func (c File) Validate() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Load reads a config file for the normal (commanding) mode.
|
||||
func Load(path string) (File, error) {
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if err := cfg.Validate(false); err != nil {
|
||||
return cfg, fmt.Errorf("config: %s: %w", path, err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadForPairing reads a config file for --pair mode, where an empty device list is the starting
|
||||
// state rather than a misconfiguration.
|
||||
func LoadForPairing(path string) (File, error) {
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if err := cfg.Validate(true); err != nil {
|
||||
return cfg, fmt.Errorf("config: %s: %w", path, err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func loadFile(path string) (File, error) {
|
||||
var cfg File
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
if err := decoder.Decode(&cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config: decode %s: %w", path, err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Save writes the config back with 0600, atomically.
|
||||
//
|
||||
// Atomic (temp file + rename) because the pairing flow writes the device list at moments when the
|
||||
// agent may be concurrently read by systemd restarts: a half-written config is a config that fails
|
||||
// to load, which turns a completed pairing into an uncommandable node.
|
||||
func Save(path string, cfg File) error {
|
||||
if err := cfg.Validate(true); err != nil {
|
||||
return fmt.Errorf("config: refusing to save an invalid file: %w", err)
|
||||
}
|
||||
encoded, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
encoded = append(encoded, '\n')
|
||||
temp := path + ".tmp"
|
||||
if err := os.WriteFile(temp, encoded, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temp, path)
|
||||
}
|
||||
|
||||
// NewRelayToken mints a device bearer for the relay: 24 random bytes, hex. Hex because the relay
|
||||
// only requires a bearer string and hex never contains a character that needs escaping when it
|
||||
// travels through JSON or headers.
|
||||
func NewRelayToken() string {
|
||||
raw := make([]byte, 24)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
// rand.Read only fails if the system entropy source is gone, in which case nothing in the
|
||||
// agent can run safely anyway.
|
||||
panic(fmt.Sprintf("config: entropy source failed: %v", err))
|
||||
}
|
||||
return hex.EncodeToString(raw)
|
||||
}
|
||||
|
||||
// NewDeviceID mints an app id for a freshly paired phone. The relay and the agent both match ids
|
||||
// against ^ap_[A-Za-z0-9_-]{8,64}$, so 12 hex characters is the narrowest thing that fits.
|
||||
func NewDeviceID() string {
|
||||
raw := make([]byte, 6)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
panic(fmt.Sprintf("config: entropy source failed: %v", err))
|
||||
}
|
||||
return "ap_" + hex.EncodeToString(raw)
|
||||
}
|
||||
|
||||
// EnsureRelayTokens fills in bearer tokens for hand-written device entries that lack one and
|
||||
// persists the result. It reports whether the file changed so a caller can log the event rather
|
||||
// than silently rewriting an operator's file on every boot.
|
||||
func EnsureRelayTokens(path string) (File, bool, error) {
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
return cfg, false, err
|
||||
}
|
||||
if err := cfg.Validate(false); err != nil {
|
||||
return cfg, false, fmt.Errorf("config: %s: %w", path, err)
|
||||
}
|
||||
changed := false
|
||||
for i := range cfg.Devices {
|
||||
if cfg.Devices[i].RelayToken == "" {
|
||||
cfg.Devices[i].RelayToken = NewRelayToken()
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
if err := Save(path, cfg); err != nil {
|
||||
return cfg, false, err
|
||||
}
|
||||
}
|
||||
return cfg, changed, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user