Files
uberbringer/internal/app/uberbringer/ntfy_test.go
T
57_WolveandClaude Opus 5.5 f0b5bf020e
Security / Vulnerability check (push) Successful in 46s
Test / Lint and test (push) Successful in 2m0s
Skip state-file flushes in the daemon's subscription test
TestServeWithSubscription failed on CI: the message did not print
within 10 seconds. On a first start the open event sets the cursor, and
the subscription writes its state, flushing the file and its directory
to disk, before it reads the next line. The test's fake server sends
open and the message together, so the print waited behind two real
flushes, and on the CI runner, which is slow to flush, it did not come
in time. A flush made to take 11 seconds fails the test the same way,
at the same line.

run and newSubscribers now take the flush. The daemon passes
(*os.File).Sync, as before, and its tests pass one that does nothing,
as the ntfy package's tests do; TestSaveStateSyncs checks the flush
itself. Writing the first cursor at once stays: a saved cursor of 0
means a first start, which replays nothing.

On leil-test-1, on an ext4 file system that another process was
filling, a 4 KiB write with fsync took up to 0.5 seconds, and the old
test's time to print rose from 20 to 160 milliseconds with it. The new
test's run time did not change.

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

270 lines
8.7 KiB
Go

package uberbringer
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
// skipSync stands in for the flush of a subscription's state file to disk.
// On a busy disk a flush can take seconds, and a first start writes its
// state as soon as open arrives, before it reads the message behind it.
func skipSync(*os.File) error { return nil }
// TestServeWithSubscription runs the daemon with a subscription to a fake
// ntfy server: a message on the stream prints, /healthz lists the
// subscription as connected without changing its status code, and the
// state is saved at shutdown.
func TestServeWithSubscription(t *testing.T) {
printer := startFakePrinter(t)
var auth sync.Map
ntfyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth.Store(r.URL.Path, r.Header.Get("Authorization"))
if strings.HasSuffix(r.URL.Path, "/auth") {
fmt.Fprint(w, `{"success":true}`)
return
}
now := time.Now().Unix()
fmt.Fprintf(w, "{\"id\":\"open1\",\"time\":%d,\"event\":\"open\",\"topic\":\"alerts\"}\n", now)
fmt.Fprintf(w, "{\"id\":\"msg1\",\"time\":%d,\"event\":\"message\",\"topic\":\"alerts\",\"title\":\"Grüße vom Abo\",\"priority\":4}\n", now)
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
defer ntfyServer.Close()
dir := t.TempDir()
tokenFile := filepath.Join(dir, "ntfy.token")
if err := os.WriteFile(tokenFile, []byte("tk_fromfile\n"), 0o600); err != nil {
t.Fatal(err)
}
const secret = "end-to-end-secret-end-to-end-secret!"
path := filepath.Join(dir, "config.toml")
body := fmt.Sprintf(`
[api]
secret = %q
[printer]
address = "127.0.0.1"
port = %d
[log]
level = "error"
[ntfy]
state_dir = %q
[[ntfy.subscriptions]]
name = "home"
server = %q
allow_insecure = true
topics = ["alerts"]
token_file = %q
`, secret, printer.addr.Port, filepath.Join(dir, "state"), ntfyServer.URL, tokenFile)
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := config.Load(path)
if err != nil {
t.Fatal(err)
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
listen := func(context.Context, string) (net.Listener, error) { return ln, nil }
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
served := make(chan error, 1)
go func() { served <- run(ctx, cfg, BuildInfo{Version: "test"}, io.Discard, listen, skipSync) }()
waitFor(t, func() bool {
// "Grüße" in CP437: ü is 0x81, ß is 0xE1.
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e vom Abo"))
})
if got, _ := auth.Load("/alerts/json"); got != "Bearer tk_fromfile" {
t.Errorf("Authorization %q, want the token from the file", got)
}
var health struct {
Status string
Ntfy []struct {
Name, State string
Printed int
}
}
waitFor(t, func() bool {
resp, err := http.Get("http://" + ln.Addr().String() + "/healthz")
if err != nil {
return false
}
defer resp.Body.Close()
_ = json.NewDecoder(resp.Body).Decode(&health)
return len(health.Ntfy) == 1 && health.Ntfy[0].Printed == 1
})
if n := health.Ntfy[0]; n.Name != "home" || n.State != "connected" {
t.Errorf("ntfy health %+v", n)
}
cancel()
select {
case err := <-served:
if err != nil {
t.Fatalf("serve returned %v after shutdown", err)
}
case <-time.After(15 * time.Second):
t.Fatal("serve did not shut down")
}
data, err := os.ReadFile(filepath.Join(dir, "state", "ntfy-home.json"))
if err != nil || !bytes.Contains(data, []byte(`"msg1"`)) {
t.Errorf("state file %s, %v; want it to remember msg1", data, err)
}
}
// The daemon refuses to start with a credentials file it cannot read, or
// one that is empty.
func TestNewSubscribersErrors(t *testing.T) {
dir := t.TempDir()
empty := filepath.Join(dir, "empty")
if err := os.WriteFile(empty, []byte(" \n"), 0o600); err != nil {
t.Fatal(err)
}
cfg := config.Default()
cfg.Ntfy.StateDir = filepath.Join(dir, "state")
sub := config.DefaultSubscription()
sub.Name, sub.Server, sub.Topics = "home", "https://ntfy.sh", []string{"alerts"}
for _, tt := range []struct {
file, want string
}{
{filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"},
{empty, "is empty"},
} {
sub.TokenFile = tt.file
cfg.Ntfy.Subscriptions = []config.NtfySubscription{sub}
if _, err := newSubscribers(&cfg, slog.New(slog.DiscardHandler), skipSync); err == nil || !strings.Contains(err.Error(), tt.want) {
t.Errorf("token_file %s: err = %v, want %q", tt.file, err, tt.want)
}
}
}
// A credentials file others may read is accepted with a warning.
func TestReadSecretWarnsAboutPermissions(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Windows has no Unix permissions")
}
path := filepath.Join(t.TempDir(), "token")
if err := os.WriteFile(path, []byte("tk_secret\n"), 0o644); err != nil {
t.Fatal(err)
}
var logs bytes.Buffer
got, err := readSecret(path, "home", slog.New(slog.NewTextHandler(&logs, nil)))
if err != nil || got != "tk_secret" {
t.Fatalf("readSecret = %q, %v", got, err)
}
if out := logs.String(); !strings.Contains(out, "can be read by others") || strings.Contains(out, "tk_secret") {
t.Errorf("log %q, want a warning without the secret", out)
}
}
func TestQuietHours(t *testing.T) {
q, err := quietHours(config.NtfyQuiet{Start: "22:30", End: "06:45", Days: []string{"fri", "sat"},
MinPriority: 4, Action: "drop"}, "Europe/London")
if err != nil {
t.Fatal(err)
}
if q.Start != (ntfy.Clock{Hour: 22, Minute: 30}) || q.End != (ntfy.Clock{Hour: 6, Minute: 45}) ||
q.Location.String() != "Europe/London" || q.MinPriority != 4 || !q.Drop ||
len(q.Days) != 2 || q.Days[0] != time.Friday || q.Days[1] != time.Saturday {
t.Errorf("quiet %+v", q)
}
q, err = quietHours(config.DefaultQuiet(), "UTC")
if err != nil || q.Location != time.UTC || q.Drop || len(q.Days) != 7 {
t.Errorf("quiet %+v, %v", q, err)
}
}
// fakeQueue records the jobs submitted to it, or refuses them.
type fakeQueue struct {
jobs []receipt.Job
metas []printqueue.Meta
err error
}
func (q *fakeQueue) Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error) {
if q.err != nil {
return printqueue.Status{}, q.err
}
q.jobs = append(q.jobs, job)
q.metas = append(q.metas, meta)
return printqueue.Status{}, nil
}
func testEnv() modules.Env {
return modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
}
// The handler prints a message as a card with its source and ID, marks an
// update, prints a digest, skips what has nothing to print, and hands a
// full queue back for a retry. Its log lines carry no text.
func TestNtfyPrinter(t *testing.T) {
var logs bytes.Buffer
q := &fakeQueue{}
p := &ntfyPrinter{name: "home", jobs: q, env: testEnv, logger: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))}
ctx := context.Background()
m := ntfy.Message{ID: "msg1", Event: "message", Topic: "alerts", Title: "Disk almost full", Message: "SecretBody"}
if err := p.Message(ctx, m, true); err != nil {
t.Fatal(err)
}
if err := p.Message(ctx, ntfy.Message{ID: "b64", Event: "message", Message: "AAE=", Encoding: "base64"}, false); err != nil {
t.Fatal(err)
}
if err := p.Digest(ctx, ntfy.Digest{Rows: []ntfy.DigestRow{{ID: "x", Title: "SecretRow"}}, Count: 1, Until: testEnv().Now}); err != nil {
t.Fatal(err)
}
if len(q.jobs) != 2 {
t.Fatalf("%d jobs, want the card and the digest", len(q.jobs))
}
if q.metas[0] != (printqueue.Meta{Source: "ntfy:home", Ref: "msg1"}) || q.metas[1] != (printqueue.Meta{Source: "ntfy:home", Ref: "digest"}) {
t.Errorf("metas %+v", q.metas)
}
if title := q.jobs[0].Elements[0].Title; title != "Disk almost full (updated)" {
t.Errorf("card title %q, want the update marked", title)
}
q.err = printqueue.ErrQueueFull
if err := p.Message(ctx, m, false); !errors.Is(err, printqueue.ErrQueueFull) {
t.Errorf("err = %v, want the full queue back", err)
}
p.reportFallback("msg1", &modules.FallbackError{Cause: "panic: layout bug", Stack: "goroutine 1"})
p.reportFallback("msg2", nil)
out := logs.String()
if !strings.Contains(out, "ntfy card printed its fallback receipt") || !strings.Contains(out, "ref=msg1") ||
!strings.Contains(out, "goroutine 1") || strings.Contains(out, "msg2") {
t.Errorf("log %q, want the fallback logged with the ID", out)
}
for _, secret := range []string{"Disk almost full", "SecretBody", "SecretRow"} {
if strings.Contains(out, secret) {
t.Errorf("the log holds %q", secret)
}
}
}