Harden core packages and add interactive CLI config builder (rud config/validate/test)

This commit is contained in:
tyuXX 2026-11-19 13:05:26 +00:00
parent d37503c863
commit 99e24be6c9
29 changed files with 6763 additions and 165 deletions

View file

@ -5,12 +5,43 @@ import (
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"text/template"
"time"
)
// ActionTemplateFuncMap returns the shared Go text/template helper functions
// available to event webhook body_template and command templates.
func ActionTemplateFuncMap() template.FuncMap {
return template.FuncMap{
"json": func(v any) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(b), nil
},
"jsonStr": func(v any) (string, error) {
b, err := json.Marshal(fmt.Sprint(v))
if err != nil {
return "", err
}
s := string(b)
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1], nil
}
return s, nil
},
}
}
// Duration wraps time.Duration so zero values are omitted by json:",omitempty"
// while non-zero values serialize as clean human-readable strings ("15s", "5m", "5h").
type Duration time.Duration
@ -556,16 +587,116 @@ func LoadOrInit(path string, createIfMissing bool) (*Config, bool, error) {
return &cfg, created, nil
}
// SaveConfig writes the Config struct as indented, human-readable JSON without HTML-escaping characters like '<' or '&'.
func SaveConfig(path string, cfg *Config) error {
// LoadForEdit loads and unmarshals a config file without applying fallbacks or failing validation,
// returning both the parsed Config and the raw JSON bytes for linting and diffing.
func LoadForEdit(path string) (*Config, []byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, nil, fmt.Errorf("failed to read config %s: %w", path, err)
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, data, fmt.Errorf("failed to parse %s: %w", path, err)
}
return &cfg, data, nil
}
// Clone returns a deep copy of Config via JSON round-trip.
func (c *Config) Clone() (*Config, error) {
data, err := MarshalConfig(c)
if err != nil {
return nil, err
}
var cp Config
if err := json.Unmarshal(data, &cp); err != nil {
return nil, err
}
return &cp, nil
}
// MarshalConfig encodes Config as indented, human-readable JSON without HTML escaping.
func MarshalConfig(cfg *Config) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(cfg); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func writeFileAtomic(path string, data []byte) error {
dir := filepath.Dir(path)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
} else {
dir = "."
}
tmp, err := os.CreateTemp(dir, ".rud-config-*.tmp")
if err != nil {
return err
}
return os.WriteFile(path, buf.Bytes(), 0644)
tmpPath := tmp.Name()
cleanup := true
defer func() {
if cleanup {
_ = os.Remove(tmpPath)
}
}()
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Chmod(0644); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Rename(tmpPath, path); err != nil {
return err
}
cleanup = false
return nil
}
// SaveConfig atomically writes Config as indented, human-readable JSON without HTML escaping.
func SaveConfig(path string, cfg *Config) error {
data, err := MarshalConfig(cfg)
if err != nil {
return err
}
return writeFileAtomic(path, data)
}
// SaveConfigWithBackup optionally copies an existing file to <path>.bak before atomically saving cfg.
func SaveConfigWithBackup(path string, cfg *Config, backup bool) (string, error) {
var backupPath string
if backup {
existing, err := os.ReadFile(path)
if err == nil {
backupPath = path + ".bak"
if err := writeFileAtomic(backupPath, existing); err != nil {
return "", fmt.Errorf("failed to write backup %s: %w", backupPath, err)
}
} else if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("failed to read existing config %s for backup: %w", path, err)
}
}
if err := SaveConfig(path, cfg); err != nil {
return backupPath, err
}
return backupPath, nil
}
// ApplyFallbacks populates missing structural defaults (like listen address, endpoint, status codes, theme colors)
@ -665,8 +796,27 @@ func (c *Config) ApplyFallbacks() {
}
}
// Validate checks the configuration for duplicate IDs, invalid methods, or invalid regexes.
// Validate checks the configuration for duplicate IDs, invalid methods, invalid URLs/regexes/templates, and negative values.
func (c *Config) Validate() error {
if c.Server.RefreshInterval < 0 {
return fmt.Errorf("server.refresh_interval cannot be negative")
}
if c.Storage.SaveInterval < 0 {
return fmt.Errorf("storage.save_interval cannot be negative")
}
if c.Defaults.Interval < 0 {
return fmt.Errorf("defaults.interval cannot be negative")
}
if c.Defaults.Timeout < 0 {
return fmt.Errorf("defaults.timeout cannot be negative")
}
if c.Defaults.DegradedLatency < 0 {
return fmt.Errorf("defaults.degraded_latency cannot be negative")
}
if c.Defaults.Retries < 0 {
return fmt.Errorf("defaults.retries cannot be negative")
}
seen := make(map[string]bool)
for i := range c.Monitors {
m := &c.Monitors[i]
@ -680,6 +830,18 @@ func (c *Config) Validate() error {
if m.Name == "" {
m.Name = m.ID
}
if m.Interval < 0 {
return fmt.Errorf("monitor %q has negative interval", m.ID)
}
if m.Timeout < 0 {
return fmt.Errorf("monitor %q has negative timeout", m.ID)
}
if m.DegradedLatency < 0 {
return fmt.Errorf("monitor %q has negative degraded_latency", m.ID)
}
if m.Retries != nil && *m.Retries < 0 {
return fmt.Errorf("monitor %q has negative retries", m.ID)
}
method := strings.ToLower(strings.TrimSpace(m.Method))
m.Method = method
@ -688,6 +850,10 @@ func (c *Config) Validate() error {
if m.URL == "" {
return fmt.Errorf("monitor %q (method %s) requires 'url'", m.ID, method)
}
u, err := url.Parse(m.URL)
if err != nil || (!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https")) || u.Host == "" {
return fmt.Errorf("monitor %q has invalid HTTP URL %q", m.ID, m.URL)
}
if m.BodyRegex != "" {
if _, err := regexp.Compile(m.BodyRegex); err != nil {
return fmt.Errorf("monitor %q has invalid body_regex %q: %w", m.ID, m.BodyRegex, err)
@ -733,19 +899,77 @@ func (c *Config) Validate() error {
}
}
seenEvents := make(map[string]bool)
for i, ev := range c.Events {
if ev.ID == "" {
if strings.TrimSpace(ev.ID) == "" {
return fmt.Errorf("event at index %d is missing an 'id'", i)
}
if seenEvents[ev.ID] {
return fmt.Errorf("duplicate event id %q", ev.ID)
}
seenEvents[ev.ID] = true
if ev.Cooldown < 0 {
return fmt.Errorf("event %q has negative cooldown", ev.ID)
}
if err := validateCondition(ev.Condition); err != nil {
return fmt.Errorf("event %q has invalid condition: %w", ev.ID, err)
}
for j, act := range ev.Actions {
if err := validateAction(act); err != nil {
return fmt.Errorf("event %q action[%d]: %w", ev.ID, j, err)
}
}
for j, act := range ev.RecoveryActions {
if err := validateAction(act); err != nil {
return fmt.Errorf("event %q recovery_actions[%d]: %w", ev.ID, j, err)
}
}
}
return nil
}
func validateAction(act EventAction) error {
if act.Timeout < 0 {
return fmt.Errorf("action timeout cannot be negative")
}
t := strings.ToLower(strings.TrimSpace(act.Type))
switch t {
case "webhook":
if strings.TrimSpace(act.URL) == "" {
return fmt.Errorf("webhook action requires 'url'")
}
u, err := url.Parse(act.URL)
if err != nil || (!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https")) || u.Host == "" {
return fmt.Errorf("webhook action has invalid URL %q", act.URL)
}
if act.BodyTemplate != "" {
if _, err := template.New("action").Funcs(ActionTemplateFuncMap()).Parse(act.BodyTemplate); err != nil {
return fmt.Errorf("invalid body_template: %w", err)
}
}
case "command", "cmd", "script":
if strings.TrimSpace(act.Command) == "" {
return fmt.Errorf("command action requires 'command'")
}
if _, err := template.New("action").Funcs(ActionTemplateFuncMap()).Parse(act.Command); err != nil {
return fmt.Errorf("invalid command template: %w", err)
}
for i, a := range act.Args {
if _, err := template.New("action").Funcs(ActionTemplateFuncMap()).Parse(a); err != nil {
return fmt.Errorf("invalid args[%d] template: %w", i, err)
}
}
default:
return fmt.Errorf("unsupported action type %q (supported: webhook, command)", act.Type)
}
return nil
}
func validateCondition(cond EventCondition) error {
if cond.For < 0 {
return fmt.Errorf("condition 'for' duration cannot be negative")
}
if len(cond.Conditions) > 0 {
op := strings.ToLower(cond.Operator)
if op != "" && op != "and" && op != "or" {
@ -788,3 +1012,237 @@ func validateCondition(cond EventCondition) error {
}
return nil
}
// LintIssue describes a non-fatal configuration warning or potential misconfiguration.
type LintIssue struct {
Path string
Message string
}
func (l LintIssue) String() string {
if l.Path == "" {
return l.Message
}
return fmt.Sprintf("%s: %s", l.Path, l.Message)
}
// Lint performs non-fatal semantic and unknown-field checks against the Config and optional raw JSON.
func (c *Config) Lint(rawJSON []byte) []LintIssue {
var issues []LintIssue
if len(bytes.TrimSpace(rawJSON)) > 0 {
var raw any
if err := json.Unmarshal(rawJSON, &raw); err == nil {
lintUnknownFields(raw, reflect.TypeOf(Config{}), "", &issues)
}
}
if len(c.Monitors) == 0 {
issues = append(issues, LintIssue{Path: "monitors", Message: "no monitors configured"})
}
knownMonitors := make(map[string]bool, len(c.Monitors))
for i, m := range c.Monitors {
if m.ID != "" {
knownMonitors[m.ID] = true
}
method := strings.ToLower(strings.TrimSpace(m.Method))
switch method {
case "tcp":
target := m.Target
if target == "" {
target = m.Host
}
if target != "" {
if host, port, err := net.SplitHostPort(target); err != nil || host == "" || port == "" {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("monitors[%d].target", i),
Message: fmt.Sprintf("TCP target %q should be in host:port format", target),
})
}
}
case "dns":
if m.RecordType != "" {
switch strings.ToUpper(strings.TrimSpace(m.RecordType)) {
case "A", "AAAA", "CNAME", "MX", "TXT", "NS":
default:
issues = append(issues, LintIssue{
Path: fmt.Sprintf("monitors[%d].record_type", i),
Message: fmt.Sprintf("unrecognized DNS record_type %q (expected A, AAAA, CNAME, MX, TXT, or NS)", m.RecordType),
})
}
}
case "http", "https":
for j, code := range m.ExpectedStatus {
if code < 100 || code > 599 {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("monitors[%d].expected_status[%d]", i, j),
Message: fmt.Sprintf("HTTP status code %d is outside valid range 100..599", code),
})
}
}
}
}
for i, ev := range c.Events {
if len(ev.Actions) == 0 {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("events[%d].actions", i),
Message: fmt.Sprintf("event %q has no actions configured", ev.ID),
})
}
lintCondition(ev.Condition, fmt.Sprintf("events[%d].condition", i), knownMonitors, &issues)
}
for i, el := range c.Page.Elements {
elType := strings.ToLower(strings.TrimSpace(el.Type))
prefix := fmt.Sprintf("page.elements[%d]", i)
switch elType {
case "header":
switch strings.ToLower(strings.TrimSpace(el.Align)) {
case "", "left", "center", "split":
default:
issues = append(issues, LintIssue{
Path: prefix + ".align",
Message: fmt.Sprintf("unknown header align %q (expected left, center, or split)", el.Align),
})
}
case "status_banner":
case "summary_cards", "summary":
for j, metric := range el.Metrics {
switch strings.ToLower(strings.TrimSpace(metric)) {
case "total", "up", "degraded", "down", "overall_uptime", "uptime", "avg_latency", "latency":
default:
issues = append(issues, LintIssue{
Path: fmt.Sprintf("%s.metrics[%d]", prefix, j),
Message: fmt.Sprintf("unknown summary metric %q", metric),
})
}
}
case "monitor_group", "monitors":
switch strings.ToLower(strings.TrimSpace(el.Layout)) {
case "", "list", "grid":
default:
issues = append(issues, LintIssue{
Path: prefix + ".layout",
Message: fmt.Sprintf("unknown monitor_group layout %q (expected list or grid)", el.Layout),
})
}
for j, id := range el.Monitors {
if id != "*" && !knownMonitors[id] {
issues = append(issues, LintIssue{
Path: fmt.Sprintf("%s.monitors[%d]", prefix, j),
Message: fmt.Sprintf("references unknown monitor id %q", id),
})
}
}
case "custom_block", "text":
switch strings.ToLower(strings.TrimSpace(el.Style)) {
case "", "neutral", "info", "warning", "danger":
default:
issues = append(issues, LintIssue{
Path: prefix + ".style",
Message: fmt.Sprintf("unknown custom_block style %q (expected neutral, info, warning, or danger)", el.Style),
})
}
case "divider":
default:
issues = append(issues, LintIssue{
Path: prefix + ".type",
Message: fmt.Sprintf("unknown page element type %q", el.Type),
})
}
}
return issues
}
func lintCondition(cond EventCondition, path string, knownMonitors map[string]bool, issues *[]LintIssue) {
if len(cond.Conditions) > 0 {
for i, sub := range cond.Conditions {
lintCondition(sub, fmt.Sprintf("%s.conditions[%d]", path, i), knownMonitors, issues)
}
return
}
switch strings.ToLower(strings.TrimSpace(cond.Match)) {
case "", "all", "any":
default:
*issues = append(*issues, LintIssue{
Path: path + ".match",
Message: fmt.Sprintf("unknown match mode %q (expected all or any)", cond.Match),
})
}
for i, id := range cond.Monitors {
if id != "*" && !knownMonitors[id] {
*issues = append(*issues, LintIssue{
Path: fmt.Sprintf("%s.monitors[%d]", path, i),
Message: fmt.Sprintf("references unknown monitor id %q", id),
})
}
}
}
var durationType = reflect.TypeOf(Duration(0))
func lintUnknownFields(raw any, t reflect.Type, path string, issues *[]LintIssue) {
if raw == nil {
return
}
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t == durationType {
return
}
switch t.Kind() {
case reflect.Struct:
m, ok := raw.(map[string]any)
if !ok {
return
}
fields := make(map[string]reflect.Type, t.NumField())
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
if !sf.IsExported() {
continue
}
tag := sf.Tag.Get("json")
if tag == "-" {
continue
}
name := strings.Split(tag, ",")[0]
if name == "" {
name = sf.Name
}
fields[name] = sf.Type
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
subPath := k
if path != "" {
subPath = path + "." + k
}
ft, exists := fields[k]
if !exists {
*issues = append(*issues, LintIssue{
Path: subPath,
Message: fmt.Sprintf("unknown JSON field %q", k),
})
continue
}
lintUnknownFields(m[k], ft, subPath, issues)
}
case reflect.Slice:
arr, ok := raw.([]any)
if !ok {
return
}
for i, item := range arr {
lintUnknownFields(item, t.Elem(), fmt.Sprintf("%s[%d]", path, i), issues)
}
}
}