You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/agent/config/config.go

246 lines
8.7 KiB
Go

package config
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
const (
maxConfigBytes = 1 << 20
defaultOperationTimeoutSeconds = int64(840)
maximumOperationTimeoutSeconds = int64(840)
defaultGuestAgentTimeoutSeconds = int64(15)
minimumGuestAgentTimeoutSeconds = int64(5)
maximumGuestAgentTimeoutSeconds = int64(120)
defaultHeavyIOConcurrency = 4
minimumHeavyIOConcurrency = 2
maximumHeavyIOConcurrency = 4
defaultPeerMigrationPort = 9443
)
// Config contains only host-agent settings. File ownership and mode are
// deliberately not part of validation: a readable configuration is accepted
// regardless of how it was provisioned.
type Config struct {
PanelURL string `json:"panel_url"`
AgentID string `json:"agent_id"`
AgentSecret string `json:"agent_secret"`
JournalPath string `json:"journal_path"`
LibvirtURI string `json:"libvirt_uri,omitempty"`
MaxBodyBytes int64 `json:"max_body_bytes,omitempty"`
ClockSkewSeconds int64 `json:"clock_skew_seconds,omitempty"`
NonceTTLSeconds int64 `json:"nonce_ttl_seconds,omitempty"`
OperationTimeoutSec int64 `json:"operation_timeout_seconds,omitempty"`
GuestAgentTimeoutSec int64 `json:"guest_agent_timeout_seconds,omitempty"`
HeavyIOConcurrency int `json:"heavy_io_concurrency,omitempty"`
StoragePathRoots []string `json:"storage_path_roots,omitempty"`
FirmwareLoader string `json:"firmware_loader"`
FirmwareNVRAMTemplate string `json:"firmware_nvram_template"`
NVRAMDirectory string `json:"nvram_directory"`
PeerMigrationPort int `json:"peer_migration_port,omitempty"`
}
var agentIDPattern = regexp.MustCompile(`^[1-9][0-9]{0,18}$`)
func (c *Config) applyDefaults() {
if c.LibvirtURI == "" {
c.LibvirtURI = "qemu:///system"
}
if c.MaxBodyBytes == 0 {
c.MaxBodyBytes = 1 << 20
}
if c.ClockSkewSeconds == 0 {
c.ClockSkewSeconds = 300
}
if c.NonceTTLSeconds == 0 {
c.NonceTTLSeconds = 600
}
if c.OperationTimeoutSec == 0 {
c.OperationTimeoutSec = defaultOperationTimeoutSeconds
}
if c.GuestAgentTimeoutSec == 0 {
c.GuestAgentTimeoutSec = defaultGuestAgentTimeoutSeconds
}
if c.HeavyIOConcurrency == 0 {
c.HeavyIOConcurrency = defaultHeavyIOConcurrency
}
if c.PeerMigrationPort == 0 {
c.PeerMigrationPort = defaultPeerMigrationPort
}
}
func (c Config) Validate() error {
var problems []string
if err := validatePanelOrigin(c.PanelURL); err != nil {
problems = append(problems, err.Error())
}
if !agentIDPattern.MatchString(c.AgentID) {
problems = append(problems, "agent_id must be a positive decimal host ID")
}
if len(c.AgentSecret) < 32 || len(c.AgentSecret) > 256 ||
strings.IndexFunc(c.AgentSecret, func(value rune) bool { return value < 0x21 || value > 0x7e }) >= 0 {
problems = append(problems, "agent_secret must contain 32-256 non-space printable ASCII bytes")
}
if c.JournalPath == "" || !filepath.IsAbs(c.JournalPath) ||
filepath.Clean(c.JournalPath) != c.JournalPath || strings.ContainsRune(c.JournalPath, 0) {
problems = append(problems, "journal_path must be a clean absolute path")
}
if c.LibvirtURI != "qemu:///system" {
problems = append(problems, "libvirt_uri must be qemu:///system")
}
if c.MaxBodyBytes < 1024 || c.MaxBodyBytes > 1<<20 {
problems = append(problems, "max_body_bytes must be between 1024 and 1048576")
}
if c.ClockSkewSeconds < 30 || c.ClockSkewSeconds > 3600 {
problems = append(problems, "clock_skew_seconds must be between 30 and 3600")
}
minimumNonceTTL := int64(0)
if c.ClockSkewSeconds >= 30 && c.ClockSkewSeconds <= 3600 {
minimumNonceTTL = 2 * c.ClockSkewSeconds
}
if minimumNonceTTL == 0 || c.NonceTTLSeconds < minimumNonceTTL || c.NonceTTLSeconds > 86400 {
problems = append(problems, "nonce_ttl_seconds must be at least twice clock_skew_seconds and at most 86400")
}
if c.OperationTimeoutSec < 5 || c.OperationTimeoutSec > maximumOperationTimeoutSeconds {
problems = append(problems, "operation_timeout_seconds must be between 5 and 840")
}
if c.GuestAgentTimeoutSec < minimumGuestAgentTimeoutSeconds || c.GuestAgentTimeoutSec > maximumGuestAgentTimeoutSeconds {
problems = append(problems, "guest_agent_timeout_seconds must be between 5 and 120")
}
if c.HeavyIOConcurrency < minimumHeavyIOConcurrency || c.HeavyIOConcurrency > maximumHeavyIOConcurrency {
problems = append(problems, "heavy_io_concurrency must be between 2 and 4")
}
if c.PeerMigrationPort < 1 || c.PeerMigrationPort > 65535 {
problems = append(problems, "peer_migration_port must be between 1 and 65535")
}
if len(c.StoragePathRoots) == 0 || len(c.StoragePathRoots) > 16 {
problems = append(problems, "storage_path_roots must contain between 1 and 16 paths")
}
seenStorageRoots := make(map[string]struct{}, len(c.StoragePathRoots))
for _, value := range c.StoragePathRoots {
if value == "" || !filepath.IsAbs(value) || filepath.Clean(value) != value ||
value == string(filepath.Separator) || strings.ContainsRune(value, 0) {
problems = append(problems, "storage_path_roots must contain only clean absolute non-root paths")
continue
}
if _, exists := seenStorageRoots[value]; exists {
problems = append(problems, "storage_path_roots must not contain duplicates")
continue
}
seenStorageRoots[value] = struct{}{}
}
for label, value := range map[string]string{
"firmware_loader": c.FirmwareLoader,
"firmware_nvram_template": c.FirmwareNVRAMTemplate,
"nvram_directory": c.NVRAMDirectory,
} {
if value == "" || !filepath.IsAbs(value) || filepath.Clean(value) != value || strings.ContainsRune(value, 0) {
problems = append(problems, label+" must be a clean absolute path")
}
}
if len(problems) != 0 {
return errors.New(strings.Join(problems, "; "))
}
return nil
}
func validatePanelOrigin(value string) error {
if value == "" || len(value) > 2048 || strings.TrimSpace(value) != value || strings.ContainsAny(value, "\x00\r\n\\") {
return errors.New("panel_url must be an HTTPS origin")
}
parsed, err := url.Parse(value)
if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.Hostname() == "" ||
parsed.User != nil || parsed.Opaque != "" || parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" ||
parsed.RawPath != "" || (parsed.Path != "" && parsed.Path != "/") || strings.HasSuffix(parsed.Host, ":") {
return errors.New("panel_url must be an HTTPS origin without credentials, path, query, or fragment")
}
if parsed.Port() != "" {
port, err := strconv.Atoi(parsed.Port())
if err != nil || port < 1 || port > 65535 {
return errors.New("panel_url contains an invalid port")
}
}
return nil
}
func (c Config) PeerMigrationStatePath() string {
return c.JournalPath + ".peer-v3"
}
func (c Config) PublicGuardLockPath() string {
return c.JournalPath + ".public-guard.lock"
}
func (c Config) PublicGuardStatePath() string {
return c.JournalPath + ".public-guard-v1.json"
}
func (c Config) PeerMigrationListenAddress() string {
return ":" + strconv.Itoa(c.PeerMigrationPort)
}
func (c Config) PeerMigrationStagingPath() string {
if len(c.StoragePathRoots) == 0 {
return ""
}
return filepath.Join(c.StoragePathRoots[0], ".peer-migration-staging")
}
func (c Config) ClockSkew() time.Duration {
return time.Duration(c.ClockSkewSeconds) * time.Second
}
func (c Config) NonceTTL() time.Duration {
return time.Duration(c.NonceTTLSeconds) * time.Second
}
func (c Config) OperationTimeout() time.Duration {
return time.Duration(c.OperationTimeoutSec) * time.Second
}
// Load reads one bounded JSON object and validates its contents. It
// intentionally does not call Stat, Chmod, Chown, or inspect permission bits.
func Load(path string) (Config, error) {
f, err := os.Open(path)
if err != nil {
return Config{}, fmt.Errorf("open agent config: %w", err)
}
defer f.Close()
raw, err := io.ReadAll(io.LimitReader(f, maxConfigBytes+1))
if err != nil {
return Config{}, fmt.Errorf("read agent config: %w", err)
}
if len(raw) > maxConfigBytes {
return Config{}, errors.New("read agent config: file exceeds 1048576 bytes")
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
var cfg Config
if err := decoder.Decode(&cfg); err != nil {
return Config{}, fmt.Errorf("decode agent config: %w", err)
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
if err == nil {
return Config{}, errors.New("decode agent config: multiple JSON values are not allowed")
}
return Config{}, fmt.Errorf("decode agent config trailer: %w", err)
}
cfg.applyDefaults()
if err := cfg.Validate(); err != nil {
return Config{}, fmt.Errorf("validate agent config: %w", err)
}
return cfg, nil
}