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)
}
}
}

View file

@ -1,7 +1,9 @@
package config
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
@ -58,6 +60,18 @@ func TestDurationMarshalUnmarshal(t *testing.T) {
func TestConfigValidation(t *testing.T) {
cfg := DefaultConfig()
if err := cfg.Validate(); err != nil {
t.Fatalf("DefaultConfig should validate cleanly, got: %v", err)
}
rawDef, err := MarshalConfig(&cfg)
if err != nil {
t.Fatalf("MarshalConfig failed: %v", err)
}
if issues := cfg.Lint(rawDef); len(issues) != 0 {
t.Fatalf("DefaultConfig should have 0 lint issues, got: %v", issues)
}
// Duplicate monitor ID
cfg.Monitors = []MonitorConfig{
{ID: "dup", Method: "tcp", Target: "127.0.0.1:80"},
{ID: "dup", Method: "tcp", Target: "127.0.0.1:81"},
@ -66,10 +80,201 @@ func TestConfigValidation(t *testing.T) {
t.Fatalf("expected duplicate monitor id error")
}
// Invalid regex
cfg.Monitors = []MonitorConfig{
{ID: "bad-regex", Method: "http", URL: "http://example.com", BodyRegex: "["},
}
if err := cfg.Validate(); err == nil {
t.Fatalf("expected invalid body_regex error")
}
// Invalid HTTP URL
cfg.Monitors = []MonitorConfig{
{ID: "bad-url", Method: "https", URL: "not-a-url"},
}
if err := cfg.Validate(); err == nil {
t.Fatalf("expected invalid HTTP URL error")
}
// Negative duration / retries
cfg = DefaultConfig()
cfg.Defaults.Interval = NewDuration(-5 * time.Second)
if err := cfg.Validate(); err == nil {
t.Fatalf("expected negative defaults.interval error")
}
cfg = DefaultConfig()
cfg.Monitors[0].Retries = IntPtr(-1)
if err := cfg.Validate(); err == nil {
t.Fatalf("expected negative monitor retries error")
}
// Duplicate event IDs
cfg = DefaultConfig()
cfg.Events = append(cfg.Events, cfg.Events[0])
if err := cfg.Validate(); err == nil {
t.Fatalf("expected duplicate event id error")
}
// Invalid webhook template
cfg = DefaultConfig()
cfg.Events[0].Actions = []EventAction{
{Type: "webhook", URL: "https://hooks.example.com/test", BodyTemplate: "{{.Unclosed"},
}
if err := cfg.Validate(); err == nil {
t.Fatalf("expected invalid webhook body_template error")
}
// Valid json/jsonStr template functions in webhook
cfg.Events[0].Actions = []EventAction{
{Type: "webhook", URL: "https://hooks.example.com/test", BodyTemplate: `{"msg":{{json .EventName}},"sub":"{{jsonStr .Status}}"}`},
}
if err := cfg.Validate(); err != nil {
t.Fatalf("expected valid json template functions, got: %v", err)
}
// Invalid command template
cfg.Events[0].Actions = []EventAction{
{Type: "command", Command: "echo {{.MissingParen"},
}
if err := cfg.Validate(); err == nil {
t.Fatalf("expected invalid command template error")
}
}
func TestAtomicSaveAndBackup(t *testing.T) {
tmpDir := t.TempDir()
nestedPath := filepath.Join(tmpDir, "nested", "dir", "rud.json")
cfg := DefaultConfig()
cfg.Page.Title = "Initial Title"
if err := SaveConfig(nestedPath, &cfg); err != nil {
t.Fatalf("SaveConfig nested path failed: %v", err)
}
cfg.Page.Title = "Updated Title"
bakPath, err := SaveConfigWithBackup(nestedPath, &cfg, true)
if err != nil {
t.Fatalf("SaveConfigWithBackup failed: %v", err)
}
if bakPath != nestedPath+".bak" {
t.Fatalf("unexpected backup path %q", bakPath)
}
bakBytes, err := os.ReadFile(bakPath)
if err != nil {
t.Fatalf("read backup failed: %v", err)
}
if !strings.Contains(string(bakBytes), "Initial Title") {
t.Fatalf("backup did not contain initial content")
}
loaded, raw, err := LoadForEdit(nestedPath)
if err != nil {
t.Fatalf("LoadForEdit failed: %v", err)
}
if loaded.Page.Title != "Updated Title" {
t.Fatalf("expected Updated Title, got %q", loaded.Page.Title)
}
if len(raw) == 0 {
t.Fatalf("expected raw bytes from LoadForEdit")
}
cloned, err := loaded.Clone()
if err != nil {
t.Fatalf("Clone failed: %v", err)
}
cloned.Page.Title = "Mutated Clone"
if loaded.Page.Title != "Updated Title" {
t.Fatalf("Clone mutation affected original")
}
}
func TestConfigLint(t *testing.T) {
raw := []byte(`{
"unknown_top": true,
"monitors": [
{
"id": "tcp-bad",
"method": "tcp",
"target": "no-port-here",
"body_regx": "typo"
}
],
"events": [
{
"id": "ev1",
"name": "Ev",
"condition": {
"type": "state",
"monitors": ["missing-mon"],
"match": "some",
"state": "down"
},
"actions": []
}
],
"page": {
"title": "Test",
"elements": [
{
"type": "monitor_group",
"monitors": ["missing-mon-2"],
"layout": "carousel"
},
{
"type": "unknown_widget"
}
]
}
}`)
cfg := Config{
Monitors: []MonitorConfig{
{ID: "tcp-bad", Method: "tcp", Target: "no-port-here"},
},
Events: []EventConfig{
{
ID: "ev1",
Name: "Ev",
Condition: EventCondition{
Type: "state",
Monitors: []string{"missing-mon"},
Match: "some",
State: "down",
},
},
},
Page: PageConfig{
Title: "Test",
Elements: []PageElement{
{Type: "monitor_group", Monitors: []string{"missing-mon-2"}, Layout: "carousel"},
{Type: "unknown_widget"},
},
},
}
issues := cfg.Lint(raw)
joined := make([]string, 0, len(issues))
for _, iss := range issues {
joined = append(joined, iss.String())
}
all := strings.Join(joined, "\n")
wantSubstrings := []string{
"unknown_top",
"monitors[0].body_regx",
"host:port",
"has no actions",
"missing-mon",
"unknown match mode",
"missing-mon-2",
"unknown monitor_group layout",
"unknown page element type",
}
for _, want := range wantSubstrings {
if !strings.Contains(all, want) {
t.Errorf("expected lint issues to contain %q, got:\n%s", want, all)
}
}
}