Files
57_WolveandClaude Opus 5.5 66531e7314
Security / Vulnerability check (push) Successful in 45s
Test / Lint and test (push) Successful in 2m1s
Replace ntfy.state_dir with a top-level [state] dir
The job store is to keep its database in the directory that holds the
ntfy subscriptions' state files, so the directory moves to a section
of its own: [state] dir, or UBERBRINGER_STATE_DIR, in place of
[ntfy] state_dir. For now only the subscriptions use it. It still has
no default and is still required with a subscription, and the checks
at start name state.dir in their errors.

install.sh writes [state] dir into new configs, and the Docker image
sets UBERBRINGER_STATE_DIR. ntfy.state_dir has never been in a
release, so its CHANGELOG entry changes in place and there is no
fallback: a config that still sets it fails to load with an unknown
key until the line moves to [state].

The image itself was not built, since the workstation has no Docker.

Part of stage 1b of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:21:29 -06:00

272 lines
12 KiB
Go

package config_test
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/config"
)
// base is a config with the required settings and a state directory, which
// ends in the [ntfy] table, so that keys appended to it set ntfy keys.
const base = "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[state]\ndir = \"state\"\n[ntfy]\n"
func TestLoadSubscriptions(t *testing.T) {
cfg, err := config.Load(writeConfig(t, base+`
[[ntfy.subscriptions]]
name = "home"
server = "https://ntfy.example.com/"
topics = ["alerts", "backups"]
token_file = "/etc/uberbringer/ntfy.token"
min_priority = 3
max_backlog = "12h"
rate_limit = 3
rate_window = "5m"
bypass_priority = 4
keepalive = "1m"
[ntfy.subscriptions.quiet]
start = "23:30"
end = "06:15"
days = ["sat", "sun"]
timezone = "Europe/London"
min_priority = 4
action = "drop"
[[ntfy.subscriptions]]
name = "work"
server = "http://ntfy.lan:8080"
allow_insecure = true
topics = ["ci"]
user = "printer"
password_file = "ntfy.password"
[ntfy.subscriptions.quiet]
start = "20:00"
[[ntfy.subscriptions]]
name = "open"
server = "https://ntfy.sh"
topics = ["long-random-topic-name"]
`))
if err != nil {
t.Fatal(err)
}
if cfg.State.Dir != "state" {
t.Errorf("state.dir = %q, want state", cfg.State.Dir)
}
subs := cfg.Ntfy.Subscriptions
if len(subs) != 3 {
t.Fatalf("%d subscriptions, want 3", len(subs))
}
want := config.NtfySubscription{
Name: "home", Server: "https://ntfy.example.com/", Topics: []string{"alerts", "backups"},
TokenFile: "/etc/uberbringer/ntfy.token", MinPriority: 3, MaxBacklog: 12 * time.Hour,
RateLimit: 3, RateWindow: 5 * time.Minute, BypassPriority: 4, Keepalive: time.Minute,
Quiet: &config.NtfyQuiet{Start: "23:30", End: "06:15", Days: []string{"sat", "sun"},
Timezone: "Europe/London", MinPriority: 4, Action: "drop"},
}
if !reflect.DeepEqual(subs[0], want) {
t.Errorf("home = %+v %+v\nwant %+v %+v", subs[0], subs[0].Quiet, want, want.Quiet)
}
// Keys an entry leaves out keep their defaults, in the entry and in
// its quiet table.
work := config.DefaultSubscription()
work.Name, work.Server, work.AllowInsecure, work.Topics = "work", "http://ntfy.lan:8080", true, []string{"ci"}
work.User, work.PasswordFile = "printer", "ntfy.password"
quiet := config.DefaultQuiet()
quiet.Start = "20:00"
work.Quiet = &quiet
if !reflect.DeepEqual(subs[1], work) {
t.Errorf("work = %+v %+v\nwant %+v %+v", subs[1], subs[1].Quiet, work, work.Quiet)
}
open := config.DefaultSubscription()
open.Name, open.Server, open.Topics = "open", "https://ntfy.sh", []string{"long-random-topic-name"}
if !reflect.DeepEqual(subs[2], open) {
t.Errorf("open = %+v, want %+v without quiet hours and credentials", subs[2], open)
}
}
func TestSubscriptionDefaults(t *testing.T) {
def := config.DefaultSubscription()
if def.MinPriority != 1 || def.MaxBacklog != time.Hour || def.RateLimit != 5 || def.RateWindow != 10*time.Minute ||
def.BypassPriority != 5 || def.Keepalive != 45*time.Second || def.Quiet != nil {
t.Errorf("subscription defaults %+v", def)
}
q := config.DefaultQuiet()
if q.Start != "22:00" || q.End != "07:00" || len(q.Days) != 7 || q.Timezone != "" || q.MinPriority != 5 || q.Action != "digest" {
t.Errorf("quiet defaults %+v", q)
}
if cfg := config.Default(); cfg.State.Dir != "" || cfg.Ntfy.Subscriptions != nil || cfg.Ntfy.Format.Updates != "print" {
t.Errorf("state defaults %+v, ntfy defaults %+v", cfg.State, cfg.Ntfy)
}
}
// The subscription in the example config, commented out there, loads and
// shows the defaults.
func TestExampleSubscriptionLoads(t *testing.T) {
example, err := os.ReadFile(filepath.Join("..", "..", "..", "configs", "config.example.toml"))
if err != nil {
t.Fatal(err)
}
var block []string
in := false
for line := range strings.SplitSeq(strings.ReplaceAll(string(example), "\r\n", "\n"), "\n") {
if strings.HasPrefix(line, "# [[ntfy.subscriptions]]") {
in = true
}
if !in {
continue
}
if !strings.HasPrefix(line, "#") {
break
}
block = append(block, strings.TrimPrefix(strings.TrimPrefix(line, "#"), " "))
}
if len(block) == 0 {
t.Fatal("the example config has no commented [[ntfy.subscriptions]] block")
}
cfg, err := config.Load(writeConfig(t, base+strings.Join(block, "\n")))
if err != nil {
t.Fatalf("example subscription: %v", err)
}
if len(cfg.Ntfy.Subscriptions) != 1 {
t.Fatalf("%d subscriptions", len(cfg.Ntfy.Subscriptions))
}
got := cfg.Ntfy.Subscriptions[0]
def := config.DefaultSubscription()
if got.MinPriority != def.MinPriority || got.MaxBacklog != def.MaxBacklog || got.RateLimit != def.RateLimit ||
got.RateWindow != def.RateWindow || got.BypassPriority != def.BypassPriority || got.Keepalive != def.Keepalive {
t.Errorf("example subscription %+v drifted from the defaults it documents", got)
}
if got.Quiet == nil || !reflect.DeepEqual(*got.Quiet, config.DefaultQuiet()) {
t.Errorf("example quiet hours %+v drifted from the defaults", got.Quiet)
}
}
func TestLoadSubscriptionErrors(t *testing.T) {
const sub = "[[ntfy.subscriptions]]\nname = \"home\"\nserver = \"https://ntfy.sh\"\ntopics = [\"alerts\"]\n"
const quiet = sub + "[ntfy.subscriptions.quiet]\n"
tests := []struct {
name, body, wantErr string
}{
{"no state dir", strings.Replace(base, "dir = \"state\"", "", 1) + sub, "state.dir is required"},
{"blank state dir", strings.Replace(base, "dir = \"state\"", "dir = \" \"", 1) + sub, "state.dir is required"},
{"state dir under ntfy", "state_dir = \"state\"\n", "unknown keys: ntfy.state_dir"},
{"unknown key", sub + "topic = \"x\"\n", "unknown keys: ntfy.subscriptions[0].topic"},
{"unknown quiet key", quiet + "begin = \"22:00\"\n", "unknown keys: ntfy.subscriptions[0].quiet.begin"},
{"keys that differ in case", sub + "Name = \"x\"\n", "keys that differ only in case: ntfy.subscriptions[0].Name and ntfy.subscriptions[0].name"},
{"subscriptions as a value", "subscriptions = \"home\"\n", "unknown keys: ntfy.subscriptions"},
{"subscription as a value", "subscriptions = [\"home\"]\n", "unknown keys: ntfy.subscriptions[0]"},
{"missing name", "[[ntfy.subscriptions]]\nserver = \"https://ntfy.sh\"\ntopics = [\"a\"]\n", "ntfy.subscriptions[0].name is required"},
{"bad name", strings.Replace(sub, `"home"`, `"Home Office"`, 1), `name: "Home Office" must be 1-32 lowercase letters`},
{"duplicate name", sub + sub, `ntfy.subscriptions[1].name: "home" is also the name of ntfy.subscriptions[0]`},
{"missing server", "[[ntfy.subscriptions]]\nname = \"a\"\ntopics = [\"a\"]\n", "ntfy.subscriptions[0].server is required"},
{"server not a URL", strings.Replace(sub, "https://ntfy.sh", "ntfy.sh", 1), "server is not an http or https URL"},
{"server with another scheme", strings.Replace(sub, "https://ntfy.sh", "ftp://ntfy.sh", 1), "server is not an http or https URL"},
{"plain http", strings.Replace(sub, "https://", "http://", 1), "server is not https; set allow_insecure"},
{"credentials in the URL", strings.Replace(sub, "https://", "https://me:hunter2@", 1), "server holds credentials"},
{"query in the URL", strings.Replace(sub, "ntfy.sh", "ntfy.sh/?x=1", 1), "server must have no query or fragment"},
{"no topics", strings.Replace(sub, `["alerts"]`, `[]`, 1), "topics: name 1-150 topics"},
{"bad topic", strings.Replace(sub, `"alerts"`, `"ok", "alerts/x"`, 1), `ntfy.subscriptions[0].topics[1] must be 1-64 letters`},
{"long topic", strings.Replace(sub, `"alerts"`, `"`+strings.Repeat("a", 65)+`"`, 1), "topics[0] must be 1-64 letters"},
{"duplicate topic", strings.Replace(sub, `"alerts"`, `"alerts", "x", "alerts"`, 1), `topics[2] repeats topics[0]`},
{"two auth methods", sub + "token = \"tk_x\"\ntoken_file = \"t\"\n", "set at most one of token, token_file, or user with password_file"},
{"token and user", sub + "token = \"tk_x\"\nuser = \"u\"\npassword_file = \"p\"\n", "set at most one of"},
{"user without password", sub + "user = \"u\"\n", "user and password_file go together"},
{"password without user", sub + "password_file = \"p\"\n", "user and password_file go together"},
{"min priority", sub + "min_priority = 0\n", "min_priority must be 1-5"},
{"bypass priority", sub + "bypass_priority = 6\n", "bypass_priority must be 1-5"},
{"backlog too long", sub + "max_backlog = \"13h\"\n", "max_backlog must be more than 0 and at most 12h0m0s"},
{"zero backlog", sub + "max_backlog = \"0s\"\n", "max_backlog must be more than 0"},
{"zero rate limit", sub + "rate_limit = 0\n", "rate_limit must be 1-1000"},
{"zero rate window", sub + "rate_window = \"0s\"\n", "rate_window must be positive"},
{"short keepalive", sub + "keepalive = \"1s\"\n", "keepalive must be 5s-1h0m0s"},
{"bad duration", sub + "keepalive = 45\n", "keepalive"},
{"quiet start", quiet + "start = \"10pm\"\n", `quiet.start: "10pm" is not a time of day HH:MM`},
{"quiet end", quiet + "end = \"24:00\"\n", `quiet.end: "24:00" is not a time of day HH:MM`},
{"quiet empty", quiet + "start = \"07:00\"\n", `quiet: start and end are both "07:00"`},
{"quiet no days", quiet + "days = []\n", "quiet.days: name at least one day"},
{"quiet bad day", quiet + "days = [\"monday\"]\n", `quiet.days: "monday" must be one of mon, tue`},
{"quiet duplicate day", quiet + "days = [\"sat\", \"sat\"]\n", `quiet.days: "sat" is given twice`},
{"quiet time zone", quiet + "timezone = \"Europe/Londn\"\n", `quiet.timezone: "Europe/Londn" is not a known time zone`},
{"quiet min priority", quiet + "min_priority = 6\n", "quiet.min_priority must be 1-5"},
{"quiet action", quiet + "action = \"hold\"\n", `quiet.action: "hold" must be one of digest, drop`},
{"updates", "[ntfy.format]\nupdates = \"mark\"\n", `ntfy.format.updates: "mark" must be one of print, skip`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := tt.body
if !strings.Contains(body, "[api]") {
body = base + body
}
_, err := config.Load(writeConfig(t, body))
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Load error = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
// A server URL is never quoted in an error, since it can hold a password,
// and neither is a topic, whose name can be all that guards it.
func TestLoadSubscriptionErrorHidesSecrets(t *testing.T) {
_, err := config.Load(writeConfig(t, base+"[[ntfy.subscriptions]]\nname = \"a\"\nserver = \"https://me:hunter2@ntfy.sh\"\ntopics = [\"a\"]\n"))
if err == nil || strings.Contains(err.Error(), "hunter2") {
t.Errorf("error = %v, want a failure that does not quote the URL", err)
}
_, err = config.Load(writeConfig(t, base+"[[ntfy.subscriptions]]\nname = \"a\"\nserver = \"https://ntfy.sh\"\n"+
"topics = [\"zq7_topic_9f3a\", \"zq7_topic_9f3a\", \"zq7/topic\"]\n"))
if err == nil || strings.Contains(err.Error(), "zq7") {
t.Errorf("error = %v, want a failure that does not quote a topic", err)
}
}
// Subscriptions come from the file only; a variable named after them sets
// nothing, and the error names it as likely misspelt.
func TestLoadSubscriptionsHaveNoVariable(t *testing.T) {
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
t.Setenv("UBERBRINGER_STATE_DIR", "/var/lib/uberbringer")
t.Setenv("UBERBRINGER_NTFY_SUBSCRIPTIONS", "home")
t.Setenv("UBERBRINGER_NTFY_SUBSCRIPTIONS_NAME", "home")
t.Setenv("UBERBRINGER_LOG_LEVEL", "loud")
_, err := config.Load("")
if err == nil {
t.Fatal("Load accepted log.level loud")
}
if !strings.Contains(err.Error(), "variables that set nothing: UBERBRINGER_NTFY_SUBSCRIPTIONS, UBERBRINGER_NTFY_SUBSCRIPTIONS_NAME") {
t.Errorf("error = %q, want it to name both subscription variables", err)
}
t.Setenv("UBERBRINGER_LOG_LEVEL", "")
cfg, err := config.Load("")
if err != nil {
t.Fatal(err)
}
if cfg.State.Dir != "/var/lib/uberbringer" || len(cfg.Ntfy.Subscriptions) != 0 {
t.Errorf("state = %+v, ntfy = %+v", cfg.State, cfg.Ntfy)
}
}
func TestValueOfSubscriptions(t *testing.T) {
cfg := config.Default()
cfg.State.Dir = "/var/lib/uberbringer"
cfg.Ntfy.Subscriptions = []config.NtfySubscription{{Name: "home", Token: "tk_secret"}}
if got, err := cfg.Value("state.dir"); err != nil || got != "/var/lib/uberbringer" {
t.Errorf("state.dir = %q, %v", got, err)
}
if got, err := cfg.Value("ntfy.format.updates"); err != nil || got != "print" {
t.Errorf("updates = %q, %v", got, err)
}
got, err := cfg.Value("ntfy.subscriptions")
if err == nil || !strings.Contains(err.Error(), "is a list of tables") || strings.Contains(got, "tk_secret") {
t.Errorf("Value = %q, %v; want a refusal that shows no token", got, err)
}
}