Add ntfy subscriptions with digests, quiet hours and a cut feed
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s

[[ntfy.subscriptions]] tables make the daemon subscribe to ntfy topics
itself and print each message as a notification card, so the phone's
ntfy app is the only client. Each subscription is one ntfy.Subscriber in
the daemon's errgroup: one event loop owns its state, and one goroutine
per connection reads the JSON stream. internal/app hands its messages to
modules.FromNtfy, Card, Validate and Submit with the source ntfy:<name>
and the message's ID as ref, so ntfy never imports modules.

The cursor is ntfy server time, never an ID. ntfy sends open before the
replay, so only keepalives and messages dealt with move it, and a
reconnect asks for two minutes before it, since a message is dated
before its attachment is stored. The IDs of the messages a replay could
send again are kept, at least the last 512 and 20,000 at most, so a
flood in the overlap never reprints; when the cap forgets IDs a replay
could send, the floor rises past them. A saved floor bounds replays: a
first start sets it to the open event's time, and max_backlog (default
1h, at most 12h), measured by the server's clock as each connection
tells it (its open event, else its Date, then the monotonic clock), never the
host's, so replays are requested unclamped and filtered as they arrive,
raises it when it clamps, so what it left out stays out. The
state, with the held messages and the receipt times, is written
atomically at most once a second and at shutdown. Redirects are never
followed, so credentials never go to another address or over plain http.
A stalled stream reconnects after twice the keepalive plus 15 s,
failures back off 5 to 120 s with jitter, a 429 waits for Retry-After,
and refused credentials, checked at startup through /auth, show as
unauthorized and retry every 5 minutes. A full print queue pauses
reading and retries the message from 1 s to 30 s, and the cursor moves
past it only once it is queued.

The paper budget is a strict window: at most rate_limit receipts (5) in
any rate_window (10m), digests included; the rest are held and print on
one digest card once there is room, and outside quiet hours
bypass_priority (5) and above print at once. Quiet hours hold everything
below their min_priority for one Overnight digest when the window ends,
or drop it; windows cross midnight and keep their times of day when
clocks change, also where the change skips midnight or a window's end.
A message whose sequence printed before, on a card or a digest row, is marked
(updated), or skipped with ntfy.format.updates = "skip"; the first of a
sequence its publisher named prints plain.

/healthz lists the subscriptions without changing how its status code is
decided, and no credential, topic or message text reaches it, the logs
or a config error. Subscriptions come from the file only, with strict
keys and per-entry defaults; credentials are optional, at most one kind.
ntfy.state_dir is required with a subscription: the unit gains
StateDirectory=uberbringer, install.sh writes the path into a new
config, and the Docker image sets it for a volume and runs as the fixed
user 10001. README explains how to lock a self-hosted ntfy server down
so that only your publishers can print.

Breaking: printer.cut_feed (default 3) feeds blank lines before every
cut, so the last line no longer sits right at the cut. They count toward
format.max_lines once per copy, so a job within 3 lines a copy of the
limit now fails. The renderer's option is 0 unless set, so the pinned
receipts keep their bytes.

testing/synctest drives the subscriber on a virtual clock, including a
24-hour soak with floods, repeats, refusals, a full queue, quiet hours
and a restart that fails on any leaked goroutine; it replaces a 24-hour
run on hardware. Tests over real sockets cover net/http's goroutines and
redirects to plain http and to another port.

Checked on the TM-T88IV against a live ntfy server: a phone message, quiet
hours with priorities 3 and 5 and the Overnight digest, a stale cursor, a
30-minute outage with an update, a wrong token, and the three-line cut
feed. The digest and the cut-feed card are pinned in TestPaperReceipts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 17:50:23 -06:00
1 parent 1335ed0687
commit fb76284129
52 files changed
+6464 -390

No files matched your search

+265
View File
@@ -0,0 +1,265 @@
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.
const base = "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nstate_dir = \"state\"\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)
}
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.Ntfy.StateDir != "" || cfg.Ntfy.Subscriptions != nil || cfg.Ntfy.Format.Updates != "print" {
t.Errorf("ntfy defaults %+v", 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, "state_dir = \"state\"", "", 1) + sub, "ntfy.state_dir is required"},
{"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_NTFY_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.Ntfy.StateDir != "/var/lib/uberbringer" || len(cfg.Ntfy.Subscriptions) != 0 {
t.Errorf("ntfy = %+v", cfg.Ntfy)
}
}
func TestValueOfSubscriptions(t *testing.T) {
cfg := config.Default()
cfg.Ntfy.StateDir = "/var/lib/uberbringer"
cfg.Ntfy.Subscriptions = []config.NtfySubscription{{Name: "home", Token: "tk_secret"}}
if got, err := cfg.Value("ntfy.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)
}
}