Files
uberbringer/internal/pkg/ntfy/fake_test.go
T
57_WolveandClaude Opus 5.5 fb76284129
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s
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>
2026-11-30 17:50:23 -06:00

472 lines
11 KiB
Go

package ntfy
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
)
// fakeServer is an ntfy server in memory, for tests in a synctest bubble.
// It answers the stream and the credentials check through RoundTrip: an
// open event, then the stored messages since the request's since, then
// each message as it is published, with keepalives in between. Like ntfy,
// since takes messages dated at or after it.
type fakeServer struct {
keepalive time.Duration
// skew is how far the server's clock is ahead of the host's.
skew time.Duration
// authFails makes the credentials check fail as an unreachable server
// does, and authSkew puts its answer's Date this far off the server's
// clock.
authFails bool
authSkew time.Duration
// noDate leaves the Date header out of the stream's answer, and
// dateSkew puts it this far off the server's clock, as a proxy in front
// of it with a clock of its own does.
noDate bool
dateSkew time.Duration
// openNoTime leaves the open event without a time.
openNoTime bool
mu sync.Mutex
messages []Message
conns map[*fakeConn]bool
requests []*http.Request
streamAt []time.Time
answers []fakeAnswer
authStatus int
nextID int
}
// fakeAnswer is an answer other than the stream, for a request to it.
type fakeAnswer struct {
status int
retryAfter string
}
func newFakeServer() *fakeServer {
return &fakeServer{keepalive: 45 * time.Second, conns: make(map[*fakeConn]bool)}
}
func (f *fakeServer) RoundTrip(req *http.Request) (*http.Response, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.requests = append(f.requests, req)
if strings.HasSuffix(req.URL.Path, "/auth") {
if f.authFails {
return nil, errors.New("connection refused")
}
status := f.authStatus
if status == 0 {
status = http.StatusOK
}
resp := answer(req, status, "")
resp.Header.Set("Date", time.Now().Add(f.skew+f.authSkew).UTC().Format(http.TimeFormat))
return resp, nil
}
f.streamAt = append(f.streamAt, time.Now())
if len(f.answers) > 0 {
a := f.answers[0]
f.answers = f.answers[1:]
return answer(req, a.status, a.retryAfter), nil
}
if err := req.Context().Err(); err != nil {
return nil, err
}
path := strings.TrimSuffix(strings.TrimPrefix(req.URL.Path, "/"), "/json")
c := &fakeConn{
f: f,
ctx: req.Context(),
topics: strings.Split(path, ","),
wake: make(chan struct{}, 1),
closed: make(chan struct{}),
next: len(f.messages),
keepalive: time.Now().Add(f.keepalive),
}
if p := req.URL.Query().Get("priority"); p != "" {
for _, s := range strings.Split(p, ",") {
n, _ := strconv.Atoi(s)
c.priorities = append(c.priorities, n)
}
}
open := Message{ID: f.id(), Time: time.Now().Add(f.skew).Unix(), Event: EventOpen, Topic: path}
if f.openNoTime {
open.Time = 0
}
c.queue = append(c.queue, open)
if s := req.URL.Query().Get("since"); s != "" {
since, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return answer(req, http.StatusBadRequest, ""), nil
}
for _, m := range f.messages {
if m.Time >= since && c.wants(m) {
c.queue = append(c.queue, m)
}
}
}
f.conns[c] = true
h := http.Header{}
if !f.noDate {
h.Set("Date", time.Now().Add(f.skew+f.dateSkew).UTC().Format(http.TimeFormat))
}
return &http.Response{StatusCode: http.StatusOK, Header: h, Body: c, Request: req}, nil
}
func answer(req *http.Request, status int, retryAfter string) *http.Response {
h := http.Header{}
if retryAfter != "" {
h.Set("Retry-After", retryAfter)
}
return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(`{"success":true}`)), Request: req}
}
// id returns a new message ID. f.mu is held.
func (f *fakeServer) id() string {
f.nextID++
return fmt.Sprintf("m%05d", f.nextID)
}
// publish stores m, dated now, and sends it to the open connections. It
// returns m as stored.
func (f *fakeServer) publish(m Message) Message {
f.mu.Lock()
defer f.mu.Unlock()
if m.ID == "" {
m.ID = f.id()
}
if m.Time == 0 {
m.Time = time.Now().Add(f.skew).Unix()
}
if m.Event == "" {
m.Event = EventMessage
}
if m.Topic == "" {
m.Topic = "alerts"
}
f.messages = append(f.messages, m)
f.wakeAll()
return m
}
// drop ends every open connection, as a server restart does.
func (f *fakeServer) drop() {
f.mu.Lock()
defer f.mu.Unlock()
for c := range f.conns {
c.ended = true
}
f.wakeAll()
}
// stall makes every open connection go silent.
func (f *fakeServer) stall() {
f.mu.Lock()
defer f.mu.Unlock()
for c := range f.conns {
c.stalled = true
}
}
// answerNext answers the next requests to the stream with as.
func (f *fakeServer) answerNext(as ...fakeAnswer) {
f.mu.Lock()
defer f.mu.Unlock()
f.answers = append(f.answers, as...)
}
// setAuth sets the status the credentials check answers with.
func (f *fakeServer) setAuth(status int) {
f.mu.Lock()
defer f.mu.Unlock()
f.authStatus = status
}
// streams returns the requests to the stream, in order.
func (f *fakeServer) streams() []*http.Request {
f.mu.Lock()
defer f.mu.Unlock()
var out []*http.Request
for _, r := range f.requests {
if strings.HasSuffix(r.URL.Path, "/json") {
out = append(out, r)
}
}
return out
}
// streamTimes returns when each request to the stream came.
func (f *fakeServer) streamTimes() []time.Time {
f.mu.Lock()
defer f.mu.Unlock()
return slices.Clone(f.streamAt)
}
// open returns how many connections are open.
func (f *fakeServer) open() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.conns)
}
// wakeAll wakes every connection. f.mu is held.
func (f *fakeServer) wakeAll() {
for c := range f.conns {
select {
case c.wake <- struct{}{}:
default:
}
}
}
// fakeConn is one stream, read by the subscriber.
type fakeConn struct {
f *fakeServer
ctx context.Context
topics []string
priorities []int
wake chan struct{}
closed chan struct{}
closeOnce sync.Once
// Guarded by f.mu.
queue []Message
next int
ended bool
stalled bool
keepalive time.Time
buf []byte
}
// wants reports whether the connection's topics and priorities take m.
func (c *fakeConn) wants(m Message) bool {
if !slices.Contains(c.topics, m.Topic) {
return false
}
return len(c.priorities) == 0 || slices.Contains(c.priorities, m.Priority())
}
// line returns the next line to send, if one is ready, and whether the
// stream has ended.
func (c *fakeConn) line() (line []byte, ended bool, wait time.Duration) {
c.f.mu.Lock()
defer c.f.mu.Unlock()
if c.ended {
return nil, true, 0
}
if c.stalled {
return nil, false, -1
}
for len(c.queue) == 0 && c.next < len(c.f.messages) {
m := c.f.messages[c.next]
c.next++
if c.wants(m) {
c.queue = append(c.queue, m)
}
}
if len(c.queue) > 0 {
m := c.queue[0]
c.queue = c.queue[1:]
data, _ := json.Marshal(m)
return append(data, '\n'), false, 0
}
now := time.Now()
if !now.Before(c.keepalive) {
c.keepalive = now.Add(c.f.keepalive)
data, _ := json.Marshal(Message{ID: c.f.id(), Time: now.Add(c.f.skew).Unix(), Event: EventKeepalive, Topic: strings.Join(c.topics, ",")})
return append(data, '\n'), false, 0
}
return nil, false, c.keepalive.Sub(now)
}
func (c *fakeConn) Read(p []byte) (int, error) {
for len(c.buf) == 0 {
line, ended, wait := c.line()
if ended {
return 0, io.EOF
}
if line != nil {
c.buf = line
break
}
var timer <-chan time.Time
if wait >= 0 {
timer = time.After(wait)
}
select {
case <-c.wake:
case <-timer:
case <-c.ctx.Done():
return 0, c.ctx.Err()
case <-c.closed:
return 0, errors.New("read on closed body")
}
}
n := copy(p, c.buf)
c.buf = c.buf[n:]
return n, nil
}
func (c *fakeConn) Close() error {
c.closeOnce.Do(func() {
close(c.closed)
c.f.mu.Lock()
delete(c.f.conns, c)
c.f.mu.Unlock()
})
return nil
}
// errBusy stands for a full print queue.
var errBusy = errors.New("print queue is full")
// recorder is a Handler that records what it is given. fail makes the
// next calls fail with errBusy.
type recorder struct {
mu sync.Mutex
cards []card
digests []Digest
fail int
}
// card is a message the recorder printed.
type card struct {
m Message
updated bool
at time.Time
}
func (h *recorder) Message(_ context.Context, m Message, updated bool) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.fail > 0 {
h.fail--
return errBusy
}
h.cards = append(h.cards, card{m: m, updated: updated, at: time.Now()})
return nil
}
func (h *recorder) Digest(_ context.Context, d Digest) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.fail > 0 {
h.fail--
return errBusy
}
d.Rows = slices.Clone(d.Rows)
h.digests = append(h.digests, d)
return nil
}
func (h *recorder) failNext(n int) {
h.mu.Lock()
defer h.mu.Unlock()
h.fail = n
}
// printed returns the IDs of the messages printed on cards, in order.
func (h *recorder) printed() []string {
h.mu.Lock()
defer h.mu.Unlock()
var ids []string
for _, c := range h.cards {
ids = append(ids, c.m.ID)
}
return ids
}
func (h *recorder) cardList() []card {
h.mu.Lock()
defer h.mu.Unlock()
return slices.Clone(h.cards)
}
func (h *recorder) digestList() []Digest {
h.mu.Lock()
defer h.mu.Unlock()
return slices.Clone(h.digests)
}
// testOptions returns the options of a subscription to topic alerts of f,
// keeping its state in dir.
func testOptions(f *fakeServer, dir string) Options {
return Options{
Name: "home",
Server: "https://ntfy.example.com",
Topics: []string{"alerts"},
Token: "tk_testtoken",
MinPriority: 1,
MaxBacklog: time.Hour,
RateLimit: 5,
RateWindow: 10 * time.Minute,
BypassPriority: 5,
Keepalive: 45 * time.Second,
StateFile: filepath.Join(dir, "ntfy-home.json"),
Transport: f,
}
}
// start runs a subscriber with options o and handler h in the background.
// The func it returns stops it and waits for Run to return.
func start(t *testing.T, o Options, h Handler) (*Subscriber, func()) {
t.Helper()
s, err := New(o)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
if err := s.Run(ctx, h); err != nil {
t.Errorf("Run = %v, want nil", err)
}
}()
return s, func() {
cancel()
<-done
}
}
// logBuffer collects log output safely across goroutines.
type logBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *logBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *logBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
// debugLogger returns a logger that writes every level to b.
func debugLogger(b *logBuffer) *slog.Logger {
return slog.New(slog.NewTextHandler(b, &slog.HandlerOptions{Level: slog.LevelDebug}))
}