Add ntfy subscriptions with digests, quiet hours and a cut feed
[[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:
1 parent
1335ed0687
commit
fb76284129
52 files changed
+6464
-390
No files matched your search
+380
-19
@@ -8,8 +8,10 @@ import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -34,6 +36,9 @@ const MinSecretLength = 32
|
||||
// takes.
|
||||
const MaxLineSpacing = 255
|
||||
|
||||
// MaxCutFeed is the largest printer.cut_feed, the most ESC d feeds at once.
|
||||
const MaxCutFeed = 255
|
||||
|
||||
// Log formats accepted by [LogConfig.Format].
|
||||
const (
|
||||
LogFormatText = "text"
|
||||
@@ -106,6 +111,10 @@ type PrinterConfig struct {
|
||||
// keeps the printer's default spacing.
|
||||
BoxLineSpacing int `mapstructure:"box_line_spacing"`
|
||||
|
||||
// CutFeed is how many blank lines feed before each cut, so that the
|
||||
// last printed line does not sit right at the cut.
|
||||
CutFeed int `mapstructure:"cut_feed"`
|
||||
|
||||
DialTimeout time.Duration `mapstructure:"dial_timeout"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout"`
|
||||
|
||||
@@ -129,27 +138,152 @@ type FormatConfig struct {
|
||||
TimeLayout string `mapstructure:"time_layout"`
|
||||
}
|
||||
|
||||
// Values of NtfyFormatConfig's settings.
|
||||
// Values of the ntfy settings.
|
||||
var (
|
||||
NtfyStyles = []string{"auto", "box", "compact"}
|
||||
NtfyQRModes = []string{"all", "first", "none"}
|
||||
NtfyStyles = []string{"auto", "box", "compact"}
|
||||
NtfyQRModes = []string{"all", "first", "none"}
|
||||
NtfyUpdateModes = []string{"print", "skip"}
|
||||
NtfyQuietActions = []string{"digest", "drop"}
|
||||
NtfyDays = []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"}
|
||||
)
|
||||
|
||||
// Limits of the ntfy settings: the largest ntfy.format.max_lines, and the
|
||||
// most characters in a marker.
|
||||
// Limits of the ntfy settings.
|
||||
const (
|
||||
// MaxNtfyLines is the largest ntfy.format.max_lines.
|
||||
MaxNtfyLines = 400
|
||||
MaxMarker = 16
|
||||
|
||||
// MaxMarker is the most characters in a marker.
|
||||
MaxMarker = 16
|
||||
|
||||
// MaxNtfyTopics is how many topics one subscription may name, as many
|
||||
// as ntfy serves on one connection.
|
||||
MaxNtfyTopics = 150
|
||||
|
||||
// MaxNtfyBacklog is the longest max_backlog: ntfy keeps messages for
|
||||
// 12 hours by default.
|
||||
MaxNtfyBacklog = 12 * time.Hour
|
||||
|
||||
// MaxNtfyRateLimit is the largest rate_limit.
|
||||
MaxNtfyRateLimit = 1000
|
||||
|
||||
// MinNtfyKeepalive and MaxNtfyKeepalive bound keepalive.
|
||||
MinNtfyKeepalive = 5 * time.Second
|
||||
MaxNtfyKeepalive = time.Hour
|
||||
)
|
||||
|
||||
// NtfyConfig configures how notifications print, from the notify and ntfy
|
||||
// modules.
|
||||
// modules and from the subscriptions.
|
||||
type NtfyConfig struct {
|
||||
Format NtfyFormatConfig `mapstructure:"format"`
|
||||
|
||||
// Markers override the markers printed for tags, by tag: an empty
|
||||
// marker hides the tag.
|
||||
Markers map[string]string `mapstructure:"markers"`
|
||||
|
||||
// StateDir is the directory each subscription keeps its state in: its
|
||||
// cursor, the IDs it has seen and the messages it holds. Required when
|
||||
// a subscription is configured.
|
||||
StateDir string `mapstructure:"state_dir"`
|
||||
|
||||
// Subscriptions are the ntfy servers and topics whose messages print.
|
||||
// They come from the file only: a list of tables has no environment
|
||||
// variable.
|
||||
Subscriptions []NtfySubscription `mapstructure:"subscriptions"`
|
||||
}
|
||||
|
||||
// NtfySubscription is one connection to an ntfy server, for one or more
|
||||
// topics.
|
||||
type NtfySubscription struct {
|
||||
// Name names the subscription in /healthz, in logs, in job sources
|
||||
// (ntfy:<name>) and in its state file.
|
||||
Name string `mapstructure:"name"`
|
||||
|
||||
// Server is the ntfy server's base URL, e.g. https://ntfy.sh.
|
||||
Server string `mapstructure:"server"`
|
||||
|
||||
// Topics are the topics to print.
|
||||
Topics []string `mapstructure:"topics"`
|
||||
|
||||
// Token, TokenFile, or User with PasswordFile authenticate the
|
||||
// subscription; at most one of them is set. A file holds the secret
|
||||
// alone, and spaces around it are ignored.
|
||||
Token string `mapstructure:"token"`
|
||||
TokenFile string `mapstructure:"token_file"`
|
||||
User string `mapstructure:"user"`
|
||||
PasswordFile string `mapstructure:"password_file"`
|
||||
|
||||
// AllowInsecure allows a server URL that is http rather than https.
|
||||
AllowInsecure bool `mapstructure:"allow_insecure"`
|
||||
|
||||
// MinPriority is the lowest priority that prints, 1-5.
|
||||
MinPriority int `mapstructure:"min_priority"`
|
||||
|
||||
// MaxBacklog is how far back missed messages are printed after a
|
||||
// restart or an outage.
|
||||
MaxBacklog time.Duration `mapstructure:"max_backlog"`
|
||||
|
||||
// RateLimit receipts print per RateWindow at most; messages over it
|
||||
// are held and print together on one digest receipt.
|
||||
RateLimit int `mapstructure:"rate_limit"`
|
||||
RateWindow time.Duration `mapstructure:"rate_window"`
|
||||
|
||||
// BypassPriority is the lowest priority that prints at once, outside
|
||||
// the rate limit, 1-5.
|
||||
BypassPriority int `mapstructure:"bypass_priority"`
|
||||
|
||||
// Keepalive is the server's keepalive interval. A connection that
|
||||
// sends nothing for twice this, plus 15 seconds, is reconnected.
|
||||
Keepalive time.Duration `mapstructure:"keepalive"`
|
||||
|
||||
// Quiet sets quiet hours; nil leaves them off.
|
||||
Quiet *NtfyQuiet `mapstructure:"quiet"`
|
||||
}
|
||||
|
||||
// NtfyQuiet configures a subscription's quiet hours: a daily window in
|
||||
// which only urgent messages print.
|
||||
type NtfyQuiet struct {
|
||||
// Start and End are the window's times of day, HH:MM. An End before
|
||||
// Start ends the window on the next day.
|
||||
Start string `mapstructure:"start"`
|
||||
End string `mapstructure:"end"`
|
||||
|
||||
// Days are the days the window starts on: mon, tue, wed, thu, fri,
|
||||
// sat or sun.
|
||||
Days []string `mapstructure:"days"`
|
||||
|
||||
// Timezone is the zone Start and End are in; "" means format.timezone.
|
||||
Timezone string `mapstructure:"timezone"`
|
||||
|
||||
// MinPriority is the lowest priority that prints during the window.
|
||||
MinPriority int `mapstructure:"min_priority"`
|
||||
|
||||
// Action is digest, to print the held messages on one receipt when the
|
||||
// window ends, or drop.
|
||||
Action string `mapstructure:"action"`
|
||||
}
|
||||
|
||||
// DefaultSubscription returns a subscription with every optional setting
|
||||
// at its default. Name, Server and Topics have no defaults.
|
||||
func DefaultSubscription() NtfySubscription {
|
||||
return NtfySubscription{
|
||||
MinPriority: 1,
|
||||
MaxBacklog: time.Hour,
|
||||
RateLimit: 5,
|
||||
RateWindow: 10 * time.Minute,
|
||||
BypassPriority: 5,
|
||||
Keepalive: 45 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultQuiet returns quiet hours with every setting at its default.
|
||||
func DefaultQuiet() NtfyQuiet {
|
||||
return NtfyQuiet{
|
||||
Start: "22:00",
|
||||
End: "07:00",
|
||||
Days: slices.Clone(NtfyDays),
|
||||
MinPriority: 5,
|
||||
Action: "digest",
|
||||
}
|
||||
}
|
||||
|
||||
// NtfyFormatConfig configures the layout of a notification.
|
||||
@@ -169,6 +303,11 @@ type NtfyFormatConfig struct {
|
||||
|
||||
// Markdown lays out markdown messages.
|
||||
Markdown bool `mapstructure:"markdown"`
|
||||
|
||||
// Updates says what a subscription does with a message that replaces
|
||||
// one it printed: print marks its title "(updated)", skip leaves it
|
||||
// out. The module routes print every message plain.
|
||||
Updates string `mapstructure:"updates"`
|
||||
}
|
||||
|
||||
// QueueConfig configures the print queue.
|
||||
@@ -237,6 +376,7 @@ func Default() Config {
|
||||
// printer makes it break words at the right edge.
|
||||
Model: "tm-t88",
|
||||
CodePage: "cp437",
|
||||
CutFeed: 3,
|
||||
DialTimeout: 5 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
Retries: 3,
|
||||
@@ -254,6 +394,7 @@ func Default() Config {
|
||||
QR: "all",
|
||||
Images: true,
|
||||
Markdown: true,
|
||||
Updates: "print",
|
||||
},
|
||||
},
|
||||
Queue: QueueConfig{
|
||||
@@ -293,7 +434,7 @@ func Load(path string) (*Config, error) {
|
||||
var envSet []string
|
||||
bound := map[string]bool{PathEnvVar: true}
|
||||
for _, key := range slices.Sorted(maps.Keys(keys)) {
|
||||
if keys[key] == section {
|
||||
if kind := keys[key]; kind != setting && kind != tableSetting {
|
||||
continue
|
||||
}
|
||||
name := envVar(key)
|
||||
@@ -340,13 +481,7 @@ func Load(path string) (*Config, error) {
|
||||
|
||||
var cfg Config
|
||||
err := v.Unmarshal(&cfg,
|
||||
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
|
||||
durations(),
|
||||
stringToList(),
|
||||
stringToTable(),
|
||||
refuseFractions(),
|
||||
stringToNumberOrFlag(),
|
||||
)),
|
||||
viper.DecodeHook(decodeHooks()),
|
||||
// Values are taken as written, apart from the strings that hooks
|
||||
// above parse: environment variables are strings.
|
||||
func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false },
|
||||
@@ -417,14 +552,21 @@ func readFile(path string) (map[string]any, error) {
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// keyKind tells a setting from a section that holds settings, and from a
|
||||
// table setting, whose keys are the user's own.
|
||||
// keyKind tells a setting from a section that holds settings, from a
|
||||
// table setting, whose keys are the user's own, and from a list of tables.
|
||||
type keyKind int
|
||||
|
||||
const (
|
||||
setting keyKind = iota + 1
|
||||
section
|
||||
tableSetting
|
||||
|
||||
// tableList is a list of tables, such as ntfy.subscriptions, which only
|
||||
// the file sets. listSetting and listSection are the keys of its
|
||||
// entries.
|
||||
tableList
|
||||
listSetting
|
||||
listSection
|
||||
)
|
||||
|
||||
// registerDefaults sets every field of the config struct rv as a Viper
|
||||
@@ -449,6 +591,14 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
|
||||
// A default table would merge with the file's instead of
|
||||
// giving way to it; the table settings default to empty.
|
||||
keys[key] = tableSetting
|
||||
case reflect.Slice:
|
||||
if elem := field.Type().Elem(); elem.Kind() == reflect.Struct {
|
||||
keys[key] = tableList
|
||||
registerListKeys(key, elem, keys)
|
||||
continue
|
||||
}
|
||||
v.SetDefault(key, field.Interface())
|
||||
keys[key] = setting
|
||||
default:
|
||||
v.SetDefault(key, field.Interface())
|
||||
keys[key] = setting
|
||||
@@ -456,6 +606,29 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
|
||||
}
|
||||
}
|
||||
|
||||
// registerListKeys records the keys of an entry of a list of tables, a
|
||||
// struct of type t, under prefix. They have no Viper defaults: decodeHooks
|
||||
// starts each entry from its own defaults.
|
||||
func registerListKeys(prefix string, t reflect.Type, keys map[string]keyKind) {
|
||||
for i := range t.NumField() {
|
||||
tag := t.Field(i).Tag.Get("mapstructure")
|
||||
if tag == "" {
|
||||
continue
|
||||
}
|
||||
key := prefix + "." + tag
|
||||
ft := t.Field(i).Type
|
||||
if ft.Kind() == reflect.Pointer {
|
||||
ft = ft.Elem()
|
||||
}
|
||||
if ft.Kind() == reflect.Struct {
|
||||
keys[key] = listSection
|
||||
registerListKeys(key, ft, keys)
|
||||
continue
|
||||
}
|
||||
keys[key] = listSetting
|
||||
}
|
||||
}
|
||||
|
||||
// checkKeys walks the file's table under prefix. It returns the keys Config
|
||||
// does not have (unknown names, empty tables included, a setting written as
|
||||
// a table, a section written as a value, and a quoted name with a dot, which
|
||||
@@ -485,7 +658,7 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
kind = 0
|
||||
}
|
||||
switch {
|
||||
case isTable && kind == section:
|
||||
case isTable && (kind == section || kind == listSection):
|
||||
u, c := checkKeys(sub, path, key, keys)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
@@ -493,7 +666,11 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
u, c := checkTable(sub, path)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
case !isTable && kind == setting:
|
||||
case kind == tableList:
|
||||
u, c := checkList(table[name], path, key, keys)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
case !isTable && (kind == setting || kind == listSetting):
|
||||
default:
|
||||
unknown = append(unknown, path)
|
||||
}
|
||||
@@ -501,6 +678,38 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
return unknown, clashes
|
||||
}
|
||||
|
||||
// checkList checks the entries of a list of tables at path, whose dotted
|
||||
// lowercase key is lookup. Each entry must be a table, whose keys are
|
||||
// checked as a section's; an entry is named by its index, as
|
||||
// ntfy.subscriptions[0].name. A list given as anything else is unknown.
|
||||
func checkList(value any, path, lookup string, keys map[string]keyKind) (unknown, clashes []string) {
|
||||
var entries []map[string]any
|
||||
switch list := value.(type) {
|
||||
case []map[string]any:
|
||||
entries = list
|
||||
case []any:
|
||||
for i, item := range list {
|
||||
entry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
unknown = append(unknown, fmt.Sprintf("%s[%d]", path, i))
|
||||
continue
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
if len(unknown) > 0 {
|
||||
return unknown, nil
|
||||
}
|
||||
default:
|
||||
return []string{path}, nil
|
||||
}
|
||||
for i, entry := range entries {
|
||||
u, c := checkKeys(entry, fmt.Sprintf("%s[%d]", path, i), lookup, keys)
|
||||
unknown = append(unknown, u...)
|
||||
clashes = append(clashes, c...)
|
||||
}
|
||||
return unknown, clashes
|
||||
}
|
||||
|
||||
// checkTable checks the entries of a table setting at path, whose names are
|
||||
// the user's own. Like checkKeys, it returns as unknown a name with a dot
|
||||
// and an entry that is itself a table, and the names that differ only in
|
||||
@@ -530,6 +739,50 @@ func displayKey(name string) string {
|
||||
return strconv.Quote(name)
|
||||
}
|
||||
|
||||
// decodeHooks are the hooks that decode the config: values from strings,
|
||||
// and the entries of the lists of tables from their own defaults.
|
||||
func decodeHooks() mapstructure.DecodeHookFunc {
|
||||
values := []mapstructure.DecodeHookFunc{
|
||||
durations(),
|
||||
stringToList(),
|
||||
stringToTable(),
|
||||
refuseFractions(),
|
||||
stringToNumberOrFlag(),
|
||||
}
|
||||
quiet := entryDefaults(DefaultQuiet, values)
|
||||
subscription := entryDefaults(DefaultSubscription, append(slices.Clone(values), quiet))
|
||||
return mapstructure.ComposeDecodeHookFunc(append(values, subscription, quiet)...)
|
||||
}
|
||||
|
||||
// entryDefaults decodes a table into a T, an entry of a list of tables or
|
||||
// a table inside one, starting from defaults(): the keys the table leaves
|
||||
// out keep their defaults, which Viper cannot give the entries of a list.
|
||||
// hooks decode the entry's values.
|
||||
func entryDefaults[T any](defaults func() T, hooks []mapstructure.DecodeHookFunc) mapstructure.DecodeHookFunc {
|
||||
target := reflect.TypeFor[T]()
|
||||
return func(_, to reflect.Type, data any) (any, error) {
|
||||
table, ok := data.(map[string]any)
|
||||
if to != target || !ok {
|
||||
return data, nil
|
||||
}
|
||||
entry := defaults()
|
||||
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
|
||||
DecodeHook: mapstructure.ComposeDecodeHookFunc(hooks...),
|
||||
// A list the table gives replaces the default list rather than
|
||||
// overwriting its first items.
|
||||
ZeroFields: true,
|
||||
Result: &entry,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := dec.Decode(table); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
}
|
||||
|
||||
// durations decodes a duration from a string such as "1m30s". A bare number
|
||||
// is refused, since the decoder would read it as nanoseconds.
|
||||
func durations() mapstructure.DecodeHookFunc {
|
||||
@@ -692,6 +945,7 @@ func (c *Config) Validate() error {
|
||||
check(p.Columns >= 0, "printer.columns must not be negative")
|
||||
check(p.BoxLineSpacing >= 0 && p.BoxLineSpacing <= MaxLineSpacing,
|
||||
"printer.box_line_spacing must be 0-%d", MaxLineSpacing)
|
||||
check(p.CutFeed >= 0 && p.CutFeed <= MaxCutFeed, "printer.cut_feed must be 0-%d", MaxCutFeed)
|
||||
check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive")
|
||||
check(p.Retries >= 0, "printer.retries must not be negative")
|
||||
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
|
||||
@@ -714,6 +968,8 @@ func (c *Config) Validate() error {
|
||||
check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker,
|
||||
"ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker)
|
||||
}
|
||||
check(slices.Contains(NtfyUpdateModes, nf.Updates), "ntfy.format.updates: %q must be one of %s", nf.Updates, strings.Join(NtfyUpdateModes, ", "))
|
||||
errs = append(errs, validateSubscriptions(c.Ntfy)...)
|
||||
|
||||
check(c.Queue.Size > 0, "queue.size must be positive")
|
||||
check(c.Queue.History >= 0, "queue.history must not be negative")
|
||||
@@ -732,6 +988,111 @@ func (c *Config) Validate() error {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
var (
|
||||
// subscriptionName is the form of a subscription's name, which appears
|
||||
// in job sources and in a file name.
|
||||
subscriptionName = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
|
||||
|
||||
// ntfyTopic is the form of an ntfy topic name.
|
||||
ntfyTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
|
||||
|
||||
// clock is a time of day, HH:MM.
|
||||
clock = regexp.MustCompile(`^([01][0-9]|2[0-3]):[0-5][0-9]$`)
|
||||
)
|
||||
|
||||
// validateSubscriptions reports every problem with the ntfy subscriptions.
|
||||
// The server URL is never quoted, since it could hold a password.
|
||||
func validateSubscriptions(n NtfyConfig) []error {
|
||||
var errs []error
|
||||
if len(n.Subscriptions) > 0 && strings.TrimSpace(n.StateDir) == "" {
|
||||
errs = append(errs, errors.New(`ntfy.state_dir is required when a subscription is configured, e.g. "/var/lib/uberbringer"`))
|
||||
}
|
||||
names := make(map[string]int)
|
||||
for i, s := range n.Subscriptions {
|
||||
at := fmt.Sprintf("ntfy.subscriptions[%d]", i)
|
||||
check := func(ok bool, format string, args ...any) {
|
||||
if !ok {
|
||||
errs = append(errs, fmt.Errorf(at+"."+format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
switch other, dup := names[s.Name]; {
|
||||
case s.Name == "":
|
||||
check(false, "name is required")
|
||||
case !subscriptionName.MatchString(s.Name):
|
||||
check(false, "name: %q must be 1-32 lowercase letters, digits, - and _, starting with a letter or digit", s.Name)
|
||||
case dup:
|
||||
check(false, "name: %q is also the name of ntfy.subscriptions[%d]", s.Name, other)
|
||||
default:
|
||||
names[s.Name] = i
|
||||
}
|
||||
|
||||
u, err := url.Parse(s.Server)
|
||||
switch {
|
||||
case s.Server == "":
|
||||
check(false, "server is required, e.g. \"https://ntfy.sh\"")
|
||||
case err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http"):
|
||||
check(false, "server is not an http or https URL")
|
||||
case u.User != nil:
|
||||
check(false, "server holds credentials; set token, token_file, or user and password_file instead")
|
||||
case u.RawQuery != "" || u.Fragment != "":
|
||||
check(false, "server must have no query or fragment")
|
||||
case u.Scheme == "http" && !s.AllowInsecure:
|
||||
check(false, "server is not https; set allow_insecure = true to allow plain http")
|
||||
}
|
||||
|
||||
// A topic is named by its index, never quoted: on a public server
|
||||
// its name can be all that keeps others from publishing to it.
|
||||
check(len(s.Topics) >= 1 && len(s.Topics) <= MaxNtfyTopics, "topics: name 1-%d topics", MaxNtfyTopics)
|
||||
seen := make(map[string]int, len(s.Topics))
|
||||
for j, topic := range s.Topics {
|
||||
check(ntfyTopic.MatchString(topic), "topics[%d] must be 1-64 letters, digits, - and _", j)
|
||||
if first, dup := seen[topic]; dup {
|
||||
check(false, "topics[%d] repeats topics[%d]", j, first)
|
||||
continue
|
||||
}
|
||||
seen[topic] = j
|
||||
}
|
||||
|
||||
methods := 0
|
||||
for _, set := range []bool{s.Token != "", s.TokenFile != "", s.User != "" || s.PasswordFile != ""} {
|
||||
if set {
|
||||
methods++
|
||||
}
|
||||
}
|
||||
check(methods <= 1, "set at most one of token, token_file, or user with password_file")
|
||||
check((s.User == "") == (s.PasswordFile == ""), "user and password_file go together")
|
||||
|
||||
check(s.MinPriority >= 1 && s.MinPriority <= 5, "min_priority must be 1-5")
|
||||
check(s.BypassPriority >= 1 && s.BypassPriority <= 5, "bypass_priority must be 1-5")
|
||||
check(s.MaxBacklog > 0 && s.MaxBacklog <= MaxNtfyBacklog, "max_backlog must be more than 0 and at most %s", MaxNtfyBacklog)
|
||||
check(s.RateLimit >= 1 && s.RateLimit <= MaxNtfyRateLimit, "rate_limit must be 1-%d", MaxNtfyRateLimit)
|
||||
check(s.RateWindow > 0, "rate_window must be positive")
|
||||
check(s.Keepalive >= MinNtfyKeepalive && s.Keepalive <= MaxNtfyKeepalive,
|
||||
"keepalive must be %s-%s", MinNtfyKeepalive, MaxNtfyKeepalive)
|
||||
|
||||
if q := s.Quiet; q != nil {
|
||||
check(clock.MatchString(q.Start), "quiet.start: %q is not a time of day HH:MM", q.Start)
|
||||
check(clock.MatchString(q.End), "quiet.end: %q is not a time of day HH:MM", q.End)
|
||||
check(q.Start != q.End, "quiet: start and end are both %q; the window would be empty", q.Start)
|
||||
check(len(q.Days) > 0, "quiet.days: name at least one day")
|
||||
days := make(map[string]bool, len(q.Days))
|
||||
for _, day := range q.Days {
|
||||
check(slices.Contains(NtfyDays, day), "quiet.days: %q must be one of %s", day, strings.Join(NtfyDays, ", "))
|
||||
check(!days[day], "quiet.days: %q is given twice", day)
|
||||
days[day] = true
|
||||
}
|
||||
if q.Timezone != "" {
|
||||
_, err := time.LoadLocation(q.Timezone)
|
||||
check(err == nil, `quiet.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, q.Timezone)
|
||||
}
|
||||
check(q.MinPriority >= 1 && q.MinPriority <= 5, "quiet.min_priority must be 1-5")
|
||||
check(slices.Contains(NtfyQuietActions, q.Action), "quiet.action: %q must be one of %s", q.Action, strings.Join(NtfyQuietActions, ", "))
|
||||
}
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
// showsTime reports whether layout prints something of the time it
|
||||
// formats: two times that differ in every field format differently. A
|
||||
// layout with none of Go's reference values, such as "HH:MM", prints
|
||||
|
||||
@@ -53,8 +53,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
|
||||
if cfg.Images.AllowPrivateNetworks {
|
||||
t.Error("private networks must be blocked by default")
|
||||
}
|
||||
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 {
|
||||
t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing)
|
||||
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 || cfg.Printer.CutFeed != 3 {
|
||||
t.Errorf("defaults not applied: max_lines %d, box_line_spacing %d, cut_feed %d",
|
||||
cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing, cfg.Printer.CutFeed)
|
||||
}
|
||||
if cfg.Format.Timezone != "Local" || cfg.Format.TimeLayout != "02 Jan 15:04" {
|
||||
t.Errorf("format defaults not applied: timezone %q, time_layout %q", cfg.Format.Timezone, cfg.Format.TimeLayout)
|
||||
@@ -165,6 +166,16 @@ func TestLoadErrors(t *testing.T) {
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n",
|
||||
wantErr: "printer.box_line_spacing must be 0-255",
|
||||
},
|
||||
{
|
||||
name: "negative cut feed",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ncut_feed = -1\n",
|
||||
wantErr: "printer.cut_feed must be 0-255",
|
||||
},
|
||||
{
|
||||
name: "cut feed too large",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ncut_feed = 256\n",
|
||||
wantErr: "printer.cut_feed must be 0-255",
|
||||
},
|
||||
{
|
||||
name: "unknown time zone",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"Europe/Londn\"\n",
|
||||
@@ -386,15 +397,17 @@ func TestExampleConfigLoads(t *testing.T) {
|
||||
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
|
||||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
|
||||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
|
||||
cfg.Printer.CutFeed != def.Printer.CutFeed ||
|
||||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout ||
|
||||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 {
|
||||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 ||
|
||||
cfg.Ntfy.StateDir != def.Ntfy.StateDir || len(cfg.Ntfy.Subscriptions) != 0 {
|
||||
t.Error("example config values drifted from the defaults it documents")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadNtfy(t *testing.T) {
|
||||
def := config.Default().Ntfy.Format
|
||||
if def != (config.NtfyFormatConfig{Style: "auto", MaxLines: 40, QR: "all", Images: true, Markdown: true}) {
|
||||
if def != (config.NtfyFormatConfig{Style: "auto", MaxLines: 40, QR: "all", Images: true, Markdown: true, Updates: "print"}) {
|
||||
t.Errorf("defaults %+v", def)
|
||||
}
|
||||
|
||||
@@ -409,6 +422,7 @@ max_lines = 400
|
||||
qr = "first"
|
||||
images = false
|
||||
markdown = false
|
||||
updates = "skip"
|
||||
[ntfy.markers]
|
||||
backup = "[B]"
|
||||
skull = ""
|
||||
@@ -417,7 +431,7 @@ skull = ""
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := config.NtfyFormatConfig{Style: "compact", MaxLines: 400, QR: "first", Images: false, Markdown: false}
|
||||
want := config.NtfyFormatConfig{Style: "compact", MaxLines: 400, QR: "first", Images: false, Markdown: false, Updates: "skip"}
|
||||
if cfg.Ntfy.Format != want {
|
||||
t.Errorf("format %+v, want %+v", cfg.Ntfy.Format, want)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ func (c *Config) Value(key string) (string, error) {
|
||||
if v.Kind() == reflect.Struct {
|
||||
return "", fmt.Errorf("%q is a section; name one of its settings", key)
|
||||
}
|
||||
if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Struct {
|
||||
return "", fmt.Errorf("%q is a list of tables, which has no single value", key)
|
||||
}
|
||||
switch value := v.Interface().(type) {
|
||||
case time.Duration:
|
||||
return value.String(), nil
|
||||
|
||||
Reference in new issue
Block a user