diff --git a/CHANGELOG.md b/CHANGELOG.md index 13949cf..2f9fa0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,12 @@ version may break callers; such changes are listed under **Breaking**. while it was sending the job to the printer, so the receipt may have printed. Such a job is never sent again. Clients that switch on `status` must handle it. +- The Docker image sets `state.dir`, and the daemon now checks at start + that it can write there, with or without ntfy subscriptions, so a + container that cannot write `/var/lib/uberbringer` no longer starts: + one started with `--read-only` and no volume there, or with a bind mount + owned by root. Mount a named volume there, or a directory owned by + `10001:10001` (`docs/docker.md`). - A job with a `raw` element prints only with a token issued with `uberbringer token --raw`. Every other token, every token issued so far included, gets `403` `token_scope` for it and keeps every other route. @@ -68,8 +74,10 @@ version may break callers; such changes are listed under **Breaking**. when it ends. - A message that replaces one the subscription printed is marked `(updated)`, or left out with `ntfy.format.updates = "skip"`. - - `state.dir` keeps each subscription's state across restarts. - `install.sh` writes it into a new config and the systemd unit gains + - `state.dir` keeps each subscription's state across restarts. The + daemon checks at start that it can write there, with or without + subscriptions, and refuses one of only spaces. `install.sh` writes it + into a new config and the systemd unit gains `StateDirectory=uberbringer`, so `/var/lib/uberbringer` is writable; the Docker image sets it to that path, for a volume, and runs as user and group `10001`, so a mounted token file can be given to it. diff --git a/docs/configuration.md b/docs/configuration.md index 18548eb..91cbf80 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -180,7 +180,7 @@ Quiet hours are off unless the subscription has a | Key | Default | Meaning | |-----|---------|---------| -| `dir` | none | The directory the [ntfy subscriptions](#ntfy-subscriptions) keep their state in, one `ntfy-.json` file each, readable by the daemon's user only. Required with a subscription. `install.sh` and the Docker image set it to `/var/lib/uberbringer` | +| `dir` | none | The directory the [ntfy subscriptions](#ntfy-subscriptions) keep their state in, one `ntfy-.json` file each, readable by the daemon's user only. Required with a subscription, and never only spaces. When it is set, the daemon creates it, readable by its user only, if it is missing, and does not start if it cannot write there. `install.sh` and the Docker image set it to `/var/lib/uberbringer` | ### images diff --git a/docs/docker.md b/docs/docker.md index 9135fbd..da6da88 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -54,9 +54,10 @@ alerting better than restarting the container. ## ntfy subscriptions [ntfy subscriptions](ntfy.md) keep their state in `/var/lib/uberbringer`, -which the image sets as `state.dir`. Mount a volume there: without one -the state lives in the container, and a new container, after a pull or an -upgrade, forgets what was printed and what was held. +which the image sets as `state.dir`. The daemon does not start if it +cannot write there. Mount a volume there: without one the state lives in +the container, and a new container, after a pull or an upgrade, forgets +what was printed and what was held. ```sh docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" \ diff --git a/internal/app/uberbringer/ntfy.go b/internal/app/uberbringer/ntfy.go index 568be38..00a18ae 100644 --- a/internal/app/uberbringer/ntfy.go +++ b/internal/app/uberbringer/ntfy.go @@ -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) }, diff --git a/internal/app/uberbringer/ntfy_test.go b/internal/app/uberbringer/ntfy_test.go index da61a68..766c65d 100644 --- a/internal/app/uberbringer/ntfy_test.go +++ b/internal/app/uberbringer/ntfy_test.go @@ -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) } } } diff --git a/internal/app/uberbringer/serve.go b/internal/app/uberbringer/serve.go index 6c4859d..f3c43a6 100644 --- a/internal/app/uberbringer/serve.go +++ b/internal/app/uberbringer/serve.go @@ -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) { diff --git a/internal/app/uberbringer/serve_test.go b/internal/app/uberbringer/serve_test.go index 8acea26..f759897 100644 --- a/internal/app/uberbringer/serve_test.go +++ b/internal/app/uberbringer/serve_test.go @@ -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 } diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index 8d9ad11..055be0c 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -993,6 +993,8 @@ func (c *Config) Validate() error { check(len(c.Ntfy.Subscriptions) == 0 || strings.TrimSpace(c.State.Dir) != "", `state.dir is required when an ntfy subscription is configured, e.g. "/var/lib/uberbringer"`) + check(len(c.Ntfy.Subscriptions) > 0 || c.State.Dir == "" || strings.TrimSpace(c.State.Dir) != "", + `state.dir is blank: name a directory, e.g. "/var/lib/uberbringer", or leave it out`) img := c.Images check(img.Timeout > 0, "images.timeout must be positive") diff --git a/internal/pkg/config/config_test.go b/internal/pkg/config/config_test.go index ca774f4..60ed6d2 100644 --- a/internal/pkg/config/config_test.go +++ b/internal/pkg/config/config_test.go @@ -212,6 +212,11 @@ func TestLoadErrors(t *testing.T) { body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n", wantErr: "unknown keys: format.max_line", }, + { + name: "blank state dir", + body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[state]\ndir = \" \"\n", + wantErr: "state.dir is blank", + }, { name: "bad log level", body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",