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:
1 parent
2926a69598
commit
4eb620dde0
9 files changed
+105
-30
No files matched your search
+10
-2
@@ -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
|
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`
|
printed. Such a job is never sent again. Clients that switch on `status`
|
||||||
must handle it.
|
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
|
- A job with a `raw` element prints only with a token issued with
|
||||||
`uberbringer token --raw`. Every other token, every token issued so far
|
`uberbringer token --raw`. Every other token, every token issued so far
|
||||||
included, gets `403` `token_scope` for it and keeps every other route.
|
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.
|
when it ends.
|
||||||
- A message that replaces one the subscription printed is marked
|
- A message that replaces one the subscription printed is marked
|
||||||
`(updated)`, or left out with `ntfy.format.updates = "skip"`.
|
`(updated)`, or left out with `ntfy.format.updates = "skip"`.
|
||||||
- `state.dir` keeps each subscription's state across restarts.
|
- `state.dir` keeps each subscription's state across restarts. The
|
||||||
`install.sh` writes it into a new config and the systemd unit gains
|
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;
|
`StateDirectory=uberbringer`, so `/var/lib/uberbringer` is writable;
|
||||||
the Docker image sets it to that path, for a volume, and runs as user
|
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.
|
and group `10001`, so a mounted token file can be given to it.
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ Quiet hours are off unless the subscription has a
|
|||||||
|
|
||||||
| Key | Default | Meaning |
|
| Key | Default | Meaning |
|
||||||
|-----|---------|---------|
|
|-----|---------|---------|
|
||||||
| `dir` | none | The directory the [ntfy subscriptions](#ntfy-subscriptions) keep their state in, one `ntfy-<name>.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-<name>.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
|
### images
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -54,9 +54,10 @@ alerting better than restarting the container.
|
|||||||
## ntfy subscriptions
|
## ntfy subscriptions
|
||||||
|
|
||||||
[ntfy subscriptions](ntfy.md) keep their state in `/var/lib/uberbringer`,
|
[ntfy subscriptions](ntfy.md) keep their state in `/var/lib/uberbringer`,
|
||||||
which the image sets as `state.dir`. Mount a volume there: without one
|
which the image sets as `state.dir`. The daemon does not start if it
|
||||||
the state lives in the container, and a new container, after a pull or an
|
cannot write there. Mount a volume there: without one the state lives in
|
||||||
upgrade, forgets what was printed and what was held.
|
the container, and a new container, after a pull or an upgrade, forgets
|
||||||
|
what was printed and what was held.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" \
|
docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" \
|
||||||
|
|||||||
@@ -28,28 +28,18 @@ var weekdays = map[string]time.Weekday{
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newSubscribers returns a subscriber for each [[ntfy.subscriptions]]
|
// newSubscribers returns a subscriber for each [[ntfy.subscriptions]]
|
||||||
// table, which flushes its state file to disk with syncState. It reads the
|
// table, which keeps its state file in the state directory, checked
|
||||||
// credential files and makes sure the state directory can be written, so
|
// already, and flushes it to disk with syncState. It reads the credential
|
||||||
// that a mistake in either stops the daemon at startup.
|
// 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) {
|
func newSubscribers(cfg *config.Config, logger *slog.Logger, syncState func(*os.File) error) ([]*ntfy.Subscriber, error) {
|
||||||
subs := cfg.Ntfy.Subscriptions
|
subs := cfg.Ntfy.Subscriptions
|
||||||
if len(subs) == 0 {
|
if len(subs) == 0 {
|
||||||
return nil, nil
|
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))
|
subscribers := make([]*ntfy.Subscriber, 0, len(subs))
|
||||||
for i, sc := range subs {
|
for i, sc := range subs {
|
||||||
at := fmt.Sprintf("config ntfy.subscriptions[%d]", i)
|
at := fmt.Sprintf("config ntfy.subscriptions[%d]", i)
|
||||||
|
var err error
|
||||||
o := ntfy.Options{
|
o := ntfy.Options{
|
||||||
Name: sc.Name,
|
Name: sc.Name,
|
||||||
Server: sc.Server,
|
Server: sc.Server,
|
||||||
@@ -63,7 +53,7 @@ func newSubscribers(cfg *config.Config, logger *slog.Logger, syncState func(*os.
|
|||||||
BypassPriority: sc.BypassPriority,
|
BypassPriority: sc.BypassPriority,
|
||||||
Keepalive: sc.Keepalive,
|
Keepalive: sc.Keepalive,
|
||||||
SkipUpdates: cfg.Ntfy.Format.Updates == "skip",
|
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,
|
Sync: syncState,
|
||||||
Logger: logger,
|
Logger: logger,
|
||||||
Report: func(err error) { reportNtfy(sc.Name, "", err) },
|
Report: func(err error) { reportNtfy(sc.Name, "", err) },
|
||||||
|
|||||||
@@ -138,30 +138,28 @@ token_file = %q
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The daemon refuses to start with a state directory it cannot create, or
|
// The daemon refuses to start with a credentials file it cannot read or
|
||||||
// with a credentials file it cannot read or that is empty.
|
// that is empty.
|
||||||
func TestNewSubscribersErrors(t *testing.T) {
|
func TestNewSubscribersErrors(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
empty := filepath.Join(dir, "empty")
|
empty := filepath.Join(dir, "empty")
|
||||||
if err := os.WriteFile(empty, []byte(" \n"), 0o600); err != nil {
|
if err := os.WriteFile(empty, []byte(" \n"), 0o600); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
state := filepath.Join(dir, "state")
|
|
||||||
sub := config.DefaultSubscription()
|
sub := config.DefaultSubscription()
|
||||||
sub.Name, sub.Server, sub.Topics = "home", "https://ntfy.sh", []string{"alerts"}
|
sub.Name, sub.Server, sub.Topics = "home", "https://ntfy.sh", []string{"alerts"}
|
||||||
for _, tt := range []struct {
|
for _, tt := range []struct {
|
||||||
stateDir, tokenFile, want string
|
tokenFile, want string
|
||||||
}{
|
}{
|
||||||
{empty, "", "config state.dir"},
|
{filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"},
|
||||||
{state, filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"},
|
{empty, "is empty"},
|
||||||
{state, empty, "is empty"},
|
|
||||||
} {
|
} {
|
||||||
cfg := config.Default()
|
cfg := config.Default()
|
||||||
cfg.State.Dir = tt.stateDir
|
cfg.State.Dir = filepath.Join(dir, "state")
|
||||||
sub.TokenFile = tt.tokenFile
|
sub.TokenFile = tt.tokenFile
|
||||||
cfg.Ntfy.Subscriptions = []config.NtfySubscription{sub}
|
cfg.Ntfy.Subscriptions = []config.NtfySubscription{sub}
|
||||||
if _, err := newSubscribers(&cfg, slog.New(slog.DiscardHandler), skipSync); err == nil || !strings.Contains(err.Error(), tt.want) {
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,6 +72,9 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
|||||||
}
|
}
|
||||||
defer flushSentry()
|
defer flushSentry()
|
||||||
|
|
||||||
|
if err := prepareStateDir(cfg.State.Dir); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
subscribers, err := newSubscribers(cfg, logger, syncState)
|
subscribers, err := newSubscribers(cfg, logger, syncState)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -153,6 +156,27 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
|||||||
return err
|
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
|
// rendererOptions returns the receipt layout cfg describes: the printer
|
||||||
// profile, with any paper width override, the code page and the limits.
|
// profile, with any paper width override, the code page and the limits.
|
||||||
func rendererOptions(cfg *config.Config) (receipt.Options, error) {
|
func rendererOptions(cfg *config.Config) (receipt.Options, error) {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -202,6 +203,52 @@ func waitFor(t *testing.T, cond func() bool) {
|
|||||||
t.Fatal("condition not met within 10s")
|
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.
|
// idleFailingStore is a memory store whose idle checkpoint fails.
|
||||||
type idleFailingStore struct{ *printqueue.MemoryStore }
|
type idleFailingStore struct{ *printqueue.MemoryStore }
|
||||||
|
|
||||||
|
|||||||
@@ -993,6 +993,8 @@ func (c *Config) Validate() error {
|
|||||||
|
|
||||||
check(len(c.Ntfy.Subscriptions) == 0 || strings.TrimSpace(c.State.Dir) != "",
|
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"`)
|
`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
|
img := c.Images
|
||||||
check(img.Timeout > 0, "images.timeout must be positive")
|
check(img.Timeout > 0, "images.timeout must be positive")
|
||||||
|
|||||||
@@ -212,6 +212,11 @@ func TestLoadErrors(t *testing.T) {
|
|||||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n",
|
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n",
|
||||||
wantErr: "unknown keys: format.max_line",
|
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",
|
name: "bad log level",
|
||||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
|
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
|
||||||
|
|||||||
Reference in new issue
Block a user