Check state.dir at start, with or without subscriptions

Breaking: the Docker image sets state.dir, so a container that cannot
write /var/lib/uberbringer, one started --read-only without a volume
there or with a bind mount owned by root, no longer starts, ntfy
subscriptions or not: mount a named volume or a directory owned by
10001:10001.

The daemon created state.dir and checked that it could write there only
when an ntfy subscription was configured, since only subscriptions kept
files in it. The job store will keep its database there too, so the
check now runs once at start whenever state.dir is set: the directory
is created 0700 if it is missing, and one that cannot be made or
written stops the start with an error naming state.dir, before any
subscription is made. A state.dir of only spaces is refused whether or
not a subscription is configured, rather than made as a directory of
that name. Without state.dir nothing changes.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 16:39:48 -06:00
1 parent 2926a69598
commit 4eb620dde0
9 files changed
+105 -30

No files matched your search

+5 -15
View File
@@ -28,28 +28,18 @@ var weekdays = map[string]time.Weekday{
}
// newSubscribers returns a subscriber for each [[ntfy.subscriptions]]
// table, which flushes its state file to disk with syncState. It reads the
// credential files and makes sure the state directory can be written, so
// that a mistake in either stops the daemon at startup.
// table, which keeps its state file in the state directory, checked
// already, and flushes it to disk with syncState. It reads the credential
// files, so that a mistake in one stops the daemon at startup.
func newSubscribers(cfg *config.Config, logger *slog.Logger, syncState func(*os.File) error) ([]*ntfy.Subscriber, error) {
subs := cfg.Ntfy.Subscriptions
if len(subs) == 0 {
return nil, nil
}
dir := cfg.State.Dir
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, fmt.Errorf("config state.dir: %w", err)
}
probe, err := os.CreateTemp(dir, ".write-check-*")
if err != nil {
return nil, fmt.Errorf("config state.dir: %s cannot be written: %w", dir, err)
}
_ = probe.Close()
_ = os.Remove(probe.Name())
subscribers := make([]*ntfy.Subscriber, 0, len(subs))
for i, sc := range subs {
at := fmt.Sprintf("config ntfy.subscriptions[%d]", i)
var err error
o := ntfy.Options{
Name: sc.Name,
Server: sc.Server,
@@ -63,7 +53,7 @@ func newSubscribers(cfg *config.Config, logger *slog.Logger, syncState func(*os.
BypassPriority: sc.BypassPriority,
Keepalive: sc.Keepalive,
SkipUpdates: cfg.Ntfy.Format.Updates == "skip",
StateFile: filepath.Join(dir, "ntfy-"+sc.Name+".json"),
StateFile: filepath.Join(cfg.State.Dir, "ntfy-"+sc.Name+".json"),
Sync: syncState,
Logger: logger,
Report: func(err error) { reportNtfy(sc.Name, "", err) },
+7 -9
View File
@@ -138,30 +138,28 @@ token_file = %q
}
}
// The daemon refuses to start with a state directory it cannot create, or
// with a credentials file it cannot read or that is empty.
// The daemon refuses to start with a credentials file it cannot read or
// 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)
}
state := filepath.Join(dir, "state")
sub := config.DefaultSubscription()
sub.Name, sub.Server, sub.Topics = "home", "https://ntfy.sh", []string{"alerts"}
for _, tt := range []struct {
stateDir, tokenFile, want string
tokenFile, want string
}{
{empty, "", "config state.dir"},
{state, filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"},
{state, empty, "is empty"},
{filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"},
{empty, "is empty"},
} {
cfg := config.Default()
cfg.State.Dir = tt.stateDir
cfg.State.Dir = filepath.Join(dir, "state")
sub.TokenFile = tt.tokenFile
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("state.dir %s, token_file %s: err = %v, want %q", tt.stateDir, tt.tokenFile, err, tt.want)
t.Errorf("token_file %s: err = %v, want %q", tt.tokenFile, err, tt.want)
}
}
}
+24
View File
@@ -72,6 +72,9 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
}
defer flushSentry()
if err := prepareStateDir(cfg.State.Dir); err != nil {
return err
}
subscribers, err := newSubscribers(cfg, logger, syncState)
if err != nil {
return err
@@ -153,6 +156,27 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
return err
}
// prepareStateDir creates the state directory dir, readable by the
// daemon's user only, if it is missing, and makes sure files can be
// written in it, so that a mistake stops the daemon at start. An empty dir
// means there is none.
func prepareStateDir(dir string) error {
if dir == "" {
return nil
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return fmt.Errorf("config state.dir: %w", err)
}
probe, err := os.CreateTemp(dir, ".write-check-*")
if err != nil {
return fmt.Errorf("config state.dir: %s cannot be written: %w", dir, err)
}
// The probe has done its work once created.
_ = probe.Close()
_ = os.Remove(probe.Name())
return nil
}
// rendererOptions returns the receipt layout cfg describes: the printer
// profile, with any paper width override, the code page and the limits.
func rendererOptions(cfg *config.Config) (receipt.Options, error) {
+47
View File
@@ -12,6 +12,7 @@ import (
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
@@ -202,6 +203,52 @@ func waitFor(t *testing.T, cond func() bool) {
t.Fatal("condition not met within 10s")
}
// testConfig returns a valid config for a printer at port, logging errors
// only.
func testConfig(port int) *config.Config {
cfg := config.Default()
cfg.API.Secret = "end-to-end-secret-end-to-end-secret!"
cfg.Printer.Address, cfg.Printer.Port = "127.0.0.1", port
cfg.Log.Level = "error"
return &cfg
}
// noListen stands in for the listener of a daemon that must not get as
// far as opening it.
func noListen(t *testing.T) listenFunc {
return func(context.Context, string) (net.Listener, error) {
t.Error("the daemon opened its listener")
return nil, errors.New("no listener in this test")
}
}
// A state directory that cannot be made or written stops the start, with
// or without subscriptions.
func TestRunRefusesAStateDirItCannotUse(t *testing.T) {
file := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(file, nil, 0o600); err != nil {
t.Fatal(err)
}
dirs := map[string]string{"a file": file, "under a file": filepath.Join(file, "state")}
if runtime.GOOS != "windows" && os.Geteuid() != 0 {
readOnly := filepath.Join(t.TempDir(), "read-only")
if err := os.Mkdir(readOnly, 0o500); err != nil {
t.Fatal(err)
}
dirs["read-only"] = readOnly
}
for name, dir := range dirs {
t.Run(name, func(t *testing.T) {
cfg := testConfig(9100)
cfg.State.Dir = dir
err := run(context.Background(), cfg, BuildInfo{Version: "test"}, io.Discard, noListen(t), skipSync)
if err == nil || !strings.Contains(err.Error(), "config state.dir") {
t.Errorf("run = %v, want an error naming state.dir", err)
}
})
}
}
// idleFailingStore is a memory store whose idle checkpoint fails.
type idleFailingStore struct{ *printqueue.MemoryStore }