From 9e055150fc3c61cf40a7fb315d2b86a17a14afb9 Mon Sep 17 00:00:00 2001 From: SamTV12345 Date: Sun, 15 Nov 2026 14:06:31 +0100 Subject: [PATCH 1/2] feat(docker): run the server as an unprivileged user The image ran the server as root. It now runs as 65532:65532, which owns the two directories the server writes to: - /var: the SQLite database (var/etherpad.db) and the update state, as before; - /data: settings.json (ETHERPAD_SETTINGS_PATH=/data), also as saved in the admin UI. / is not writable for the user any more. settings.json is read from ETHERPAD_SETTINGS_PATH when that holds one, otherwise from the working directory as before, so a file mounted at /settings.json keeps working. The admin UI reads the same file the server read and saves into ETHERPAD_SETTINGS_PATH (before, it could read and write another file than the one the server started with). `config get` loads the settings like `config show`, instead of showing defaults only. A /var volume from an older image belongs to root; the README shows the one-time chown. The kubernetes job runs the pods with runAsNonRoot and checks the user and the writable directories. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012RMvvMtnCwj6ycD9fwLYVu --- .github/workflows/build.yml | 3 +++ Dockerfile | 16 +++++++++--- Dockerfile.build | 16 +++++++++--- README.md | 41 ++++++++++++++++++++++--------- lib/settings/Settings.go | 2 +- lib/settings/cli.go | 1 + lib/settings/settingsfile.go | 33 +++++++++++++++++++++++++ lib/settings/settingsfile_test.go | 41 +++++++++++++++++++++++++++++++ lib/settings/viper.go | 5 ++-- lib/ws/AdminMessageHandler.go | 11 ++------- test/kubernetes/manifests.yaml | 5 ++++ 11 files changed, 142 insertions(+), 32 deletions(-) create mode 100644 lib/settings/settingsfile.go create mode 100644 lib/settings/settingsfile_test.go diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 74b6b972..b324fdad 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -415,6 +415,9 @@ jobs: test "$(readlink /app)" = /etherpad-go ls / > /dev/null ! command -v wget && ! command -v nc + test "$(id -u)" = 65532 + touch /var/probe /data/probe + ! touch /probe 2>/dev/null ' - name: Create kind cluster run: | diff --git a/Dockerfile b/Dockerfile index 7911898b..393e9e0f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,26 +28,34 @@ RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o app . FROM alpine:3.24 AS busybox # The shell's tools for looking around the container (issue 413), on -# purpose without network tools (wget, nc, ...): the server runs as root. -ARG SHELL_APPLETS="sh ls cat less head tail grep find vi env ps df du pwd echo test readlink mkdir cp mv rm chmod" +# purpose without network tools (wget, nc, ...). +ARG SHELL_APPLETS="sh ls cat less head tail grep find vi env ps df du pwd echo test readlink id touch mkdir cp mv rm chmod" RUN apk add --no-cache busybox-static \ && mkdir -p /rootfs/bin \ && cp /bin/busybox.static /rootfs/bin/busybox \ && for applet in $SHELL_APPLETS; do ln -s /bin/busybox /rootfs/bin/$applet; done \ - && ln -s /etherpad-go /rootfs/app + && ln -s /etherpad-go /rootfs/app \ + && mkdir -p /writable/var /writable/data FROM scratch AS runtime EXPOSE 3000 ENV NODE_ENV=production -ENV ETHERPAD_SETTINGS_PATH=/ +# The server runs as an unprivileged user. It writes to /var (the SQLite +# database var/etherpad.db and the update state) and to /data (settings.json +# saved in the admin UI); both belong to that user. A volume on /var from +# an image before this one belongs to root; hand it over once with +# docker run --rm -v :/var alpine chown -R 65532:65532 /var +ENV ETHERPAD_SETTINGS_PATH=/data # Named like in the README, and on PATH: `docker exec # etherpad-go config show`, or a shell (busybox) with `docker exec -it # sh` (busybox: sh, ls, cat, vi, ...). /app stays as a link for deployments that start /app. COPY --from=backend /app/app /etherpad-go COPY --from=busybox /rootfs / +COPY --from=busybox --chown=65532:65532 /writable/ / COPY --from=cache /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ ENV PATH="/:/bin" +USER 65532:65532 ENTRYPOINT ["/etherpad-go"] diff --git a/Dockerfile.build b/Dockerfile.build index 970d784e..8651ef3c 100644 --- a/Dockerfile.build +++ b/Dockerfile.build @@ -21,26 +21,34 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="-s -w FROM alpine:3.24 AS busybox # The shell's tools for looking around the container (issue 413), on -# purpose without network tools (wget, nc, ...): the server runs as root. -ARG SHELL_APPLETS="sh ls cat less head tail grep find vi env ps df du pwd echo test readlink mkdir cp mv rm chmod" +# purpose without network tools (wget, nc, ...). +ARG SHELL_APPLETS="sh ls cat less head tail grep find vi env ps df du pwd echo test readlink id touch mkdir cp mv rm chmod" RUN apk add --no-cache busybox-static \ && mkdir -p /rootfs/bin \ && cp /bin/busybox.static /rootfs/bin/busybox \ && for applet in $SHELL_APPLETS; do ln -s /bin/busybox /rootfs/bin/$applet; done \ - && ln -s /etherpad-go /rootfs/app + && ln -s /etherpad-go /rootfs/app \ + && mkdir -p /writable/var /writable/data FROM scratch AS runtime EXPOSE 3000 ENV NODE_ENV=production -ENV ETHERPAD_SETTINGS_PATH=/ +# The server runs as an unprivileged user. It writes to /var (the SQLite +# database var/etherpad.db and the update state) and to /data (settings.json +# saved in the admin UI); both belong to that user. A volume on /var from +# an image before this one belongs to root; hand it over once with +# docker run --rm -v :/var alpine chown -R 65532:65532 /var +ENV ETHERPAD_SETTINGS_PATH=/data # Named like in the README, and on PATH: `docker exec # etherpad-go config show`, or a shell (busybox) with `docker exec -it # sh` (busybox: sh, ls, cat, vi, ...). /app stays as a link for deployments that start /app. COPY --from=backend /app/app /etherpad-go COPY --from=busybox /rootfs / +COPY --from=busybox --chown=65532:65532 /writable/ / COPY --from=cache /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ ENV PATH="/:/bin" +USER 65532:65532 ENTRYPOINT ["/etherpad-go"] diff --git a/README.md b/README.md index 2dd1ef1d..24f2fe1f 100644 --- a/README.md +++ b/README.md @@ -74,13 +74,7 @@ Get a specific configuration value: ./etherpad-go config get ``` -In the Docker image the binary is `etherpad-go` on the `PATH`, and the image has a small shell -(busybox): - -```bash -docker exec etherpad-go config show -docker exec -it sh -``` +In the Docker image the same commands work through `docker exec` (see [Docker](#docker)). For customization, copy: @@ -145,19 +139,42 @@ Prebuilt images are available via GitHub Container Registry: ghcr.io/ether/etherpad-go: ``` -To open a shell in a running container: +To open a shell in a running container (busybox: `ls`, `cat`, `less`, `grep`, `vi`, …, no +network tools): + +```sh +docker exec -it etherpad_go sh +``` + +The configuration CLI is the image's `etherpad-go`, on the `PATH`: ```sh -docker exec -it etherpad_go /bin/sh +docker exec etherpad_go etherpad-go config show +docker exec etherpad_go etherpad-go config get port ``` -The configuration CLI is available in the same image: +### Files and the user in the image + +The server runs as the unprivileged user `65532`. It writes to two directories, which belong to +that user: + +| Directory | What | Mount a volume here for | +|---|---|---| +| `/var` | the SQLite database (`var/etherpad.db`, the default) and the update state | SQLite | +| `/data` | `settings.json` (`ETHERPAD_SETTINGS_PATH=/data`), also as saved in the admin UI | settings | + +A `settings.json` mounted at `/settings.json` is still read, as long as there is none in `/data`. +Settings saved in the admin UI go to `/data/settings.json`, which is then the one read. + +Upgrading from an image that ran as root: a volume on `/var` belongs to root, and the server +stops with `attempt to write a readonly database`. Hand it over once: ```sh -docker exec etherpad_go /app config show -docker exec etherpad_go /app config get port +docker run --rm -v :/var alpine chown -R 65532:65532 /var ``` +With Postgres or MySQL and no volume, nothing changes. + ### Several instances / Kubernetes With PostgreSQL or MySQL, several Etherpad-Go instances can share one database diff --git a/lib/settings/Settings.go b/lib/settings/Settings.go index 2110c246..b6e54b8d 100644 --- a/lib/settings/Settings.go +++ b/lib/settings/Settings.go @@ -490,7 +490,7 @@ type Options struct { func InitSettings(logger *zap.SugaredLogger) { var pathToRoot string - var envPathToSettings = os.Getenv("ETHERPAD_SETTINGS_PATH") + var envPathToSettings = os.Getenv(SettingsPathEnv) if envPathToSettings != "" { pathToRoot = envPathToSettings } diff --git a/lib/settings/cli.go b/lib/settings/cli.go index a6673432..6b8846ba 100644 --- a/lib/settings/cli.go +++ b/lib/settings/cli.go @@ -25,6 +25,7 @@ func HandleConfigCommand(logger *zap.SugaredLogger) { case "env": configEnv() case "get": + InitSettings(logger) configGet(os.Args[3:]) case "init": configInit() diff --git a/lib/settings/settingsfile.go b/lib/settings/settingsfile.go new file mode 100644 index 00000000..d9463ac3 --- /dev/null +++ b/lib/settings/settingsfile.go @@ -0,0 +1,33 @@ +package settings + +import ( + "os" + "path/filepath" +) + +// SettingsPathEnv names the directory of settings.json (the Docker image +// sets /data, which its user can write). +const SettingsPathEnv = "ETHERPAD_SETTINGS_PATH" + +// SettingsFile is the settings.json read for dir (ETHERPAD_SETTINGS_PATH, +// or the server's root in the admin UI): the one in dir when dir holds +// one, otherwise settings.json in the working directory (a file mounted +// there keeps working). +func SettingsFile(dir string) string { + if dir != "" { + p := filepath.Join(dir, "settings.json") + if _, err := os.Stat(p); err == nil { + return p + } + } + return "settings.json" +} + +// SettingsWriteFile is where the admin UI saves settings.json for dir: in +// dir (SettingsFile then reads it from there), or the working directory. +func SettingsWriteFile(dir string) string { + if dir != "" { + return filepath.Join(dir, "settings.json") + } + return "settings.json" +} diff --git a/lib/settings/settingsfile_test.go b/lib/settings/settingsfile_test.go new file mode 100644 index 00000000..cc9bcb7e --- /dev/null +++ b/lib/settings/settingsfile_test.go @@ -0,0 +1,41 @@ +package settings + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSettingsFile(t *testing.T) { + wd := t.TempDir() + dir := t.TempDir() + t.Chdir(wd) + + assert.Equal(t, "settings.json", SettingsFile(""), "no directory: the working directory") + assert.Equal(t, "settings.json", SettingsWriteFile("")) + + // A directory without a settings.json: still the one in the working + // directory (a file mounted at /settings.json), but saves go to dir. + require.NoError(t, os.WriteFile(filepath.Join(wd, "settings.json"), []byte("{}"), 0o644)) + assert.Equal(t, "settings.json", SettingsFile(dir)) + assert.Equal(t, filepath.Join(dir, "settings.json"), SettingsWriteFile(dir)) + + // Once saved there, it is the one read. + require.NoError(t, os.WriteFile(filepath.Join(dir, "settings.json"), []byte("{}"), 0o644)) + assert.Equal(t, filepath.Join(dir, "settings.json"), SettingsFile(dir)) + assert.Equal(t, filepath.Join(dir, "settings.json"), SettingsWriteFile(dir)) +} + +func TestReadConfigReadsTheSettingsPath(t *testing.T) { + t.Chdir(t.TempDir()) + dir := t.TempDir() + t.Setenv(SettingsPathEnv, dir) + require.NoError(t, os.WriteFile(filepath.Join(dir, "settings.json"), + []byte(`{ "title": "From the settings path", /* comment */ }`), 0o644)) + s, err := ReadConfig() + require.NoError(t, err) + assert.Equal(t, "From the settings path", s.Title) +} diff --git a/lib/settings/viper.go b/lib/settings/viper.go index bcbe906b..4c89cc44 100644 --- a/lib/settings/viper.go +++ b/lib/settings/viper.go @@ -23,10 +23,11 @@ func ReadConfig() (*Settings, error) { viper.SetConfigType("json") // settings.json may hold comments, trailing commas and ${VAR:default} // values, like etherpad-lite's; viper reads plain JSON. - if raw, err := os.ReadFile("settings.json"); err == nil { + file := SettingsFile(os.Getenv(SettingsPathEnv)) + if raw, err := os.ReadFile(file); err == nil { prepared, err := PrepareSettingsJSON(raw) if err != nil { - return nil, fmt.Errorf("settings.json: %w", err) + return nil, fmt.Errorf("%s: %w", file, err) } if err := viper.ReadConfig(bytes.NewReader(prepared)); err != nil { return nil, err diff --git a/lib/ws/AdminMessageHandler.go b/lib/ws/AdminMessageHandler.go index 56da1e2b..508b01b6 100644 --- a/lib/ws/AdminMessageHandler.go +++ b/lib/ws/AdminMessageHandler.go @@ -75,7 +75,7 @@ func (h AdminMessageHandler) HandleMessage(message admin.EventMessage, retrieved if !retrievedSettings.ShowSettingsInAdminPage { resp[1] = map[string]interface{}{"results": "NOT_ALLOWED"} } else { - raw, err := os.ReadFile(settingsFilePath(retrievedSettings)) + raw, err := os.ReadFile(settings.SettingsFile(retrievedSettings.Root)) if err != nil && !os.IsNotExist(err) { h.Logger.Errorf("Reading the settings file: %v", err) } @@ -535,7 +535,7 @@ func (h AdminMessageHandler) HandleMessage(message admin.EventMessage, retrieved c.SafeSend(responseBytes) return } - settingsPath := settingsFilePath(retrievedSettings) + settingsPath := settings.SettingsWriteFile(retrievedSettings.Root) if err := writeFileAtomic(settingsPath, []byte(settingsJSON)); err != nil { h.Logger.Errorf("Error saving settings: %v", err) resp := make([]interface{}, 2) @@ -1033,13 +1033,6 @@ func (h AdminMessageHandler) compactDamagedPad(padId string, missing []int, late return repaired.Check() } -func settingsFilePath(s *settings.Settings) string { - if s.Root != "" { - return s.Root + "/settings.json" - } - return "settings.json" -} - // writeFileAtomic replaces path in one step: a crash while writing leaves the // old file, never a truncated one. func writeFileAtomic(path string, data []byte) error { diff --git a/test/kubernetes/manifests.yaml b/test/kubernetes/manifests.yaml index 87583143..ee8fd02a 100644 --- a/test/kubernetes/manifests.yaml +++ b/test/kubernetes/manifests.yaml @@ -66,6 +66,11 @@ spec: - name: etherpad image: etherpad-go:k8s-test imagePullPolicy: Never + # The image runs as an unprivileged user; refuse to start as root. + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + capabilities: { drop: [ALL] } env: - name: POD_IP valueFrom: From eb82649e9567afd312a0cdb79bc524a7b516c4c8 Mon Sep 17 00:00:00 2001 From: SamTV12345 Date: Sun, 15 Nov 2026 18:29:40 +0100 Subject: [PATCH 2/2] fix(settings): own variable for settings.json, refuse unreadable files Review fixes for the unprivileged image: - ETHERPAD_SETTINGS_FILE names settings.json (the image: /data/settings.json); ETHERPAD_SETTINGS_PATH stays the root (/ in the image), so /APIKEY.txt and relative favicon paths resolve as before. - The read and save locations are settled once at start (Settings. SettingsFile/SettingsSaveFile) and used by the start and the admin UI alike: the UI no longer shows one file and saves another, e.g. next to the executable, that the next start does not read. - Only a missing settings.json counts as missing. A file that is there but cannot be reached (no permission) stops the start, instead of starting on defaults without the configured requireAuthentication; so does a settings.json that does not parse (before, the server went on with empty settings). - config get/show read the settings without the server's setup, so a query creates no database directory. - README: a host directory bind-mounted at /var or /data keeps its owner and must be writable for 65532. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012RMvvMtnCwj6ycD9fwLYVu --- Dockerfile | 9 ++- Dockerfile.build | 9 ++- README.md | 20 ++++-- lib/settings/Settings.go | 9 ++- lib/settings/cli.go | 13 +++- lib/settings/settingsfile.go | 65 ++++++++++++------- lib/settings/settingsfile_test.go | 77 +++++++++++++++++------ lib/settings/viper.go | 15 +++-- lib/test/ws/admin_message_handler_test.go | 6 +- lib/test/ws/admin_settings_file_test.go | 3 +- lib/ws/AdminMessageHandler.go | 13 +++- 11 files changed, 172 insertions(+), 67 deletions(-) diff --git a/Dockerfile b/Dockerfile index 393e9e0f..407f8d98 100644 --- a/Dockerfile +++ b/Dockerfile @@ -43,10 +43,13 @@ EXPOSE 3000 ENV NODE_ENV=production # The server runs as an unprivileged user. It writes to /var (the SQLite # database var/etherpad.db and the update state) and to /data (settings.json -# saved in the admin UI); both belong to that user. A volume on /var from -# an image before this one belongs to root; hand it over once with +# saved in the admin UI); both belong to that user in the image. A volume +# or host directory mounted there must be writable for 65532: one from an +# image before this one belongs to root; hand it over once with # docker run --rm -v :/var alpine chown -R 65532:65532 /var -ENV ETHERPAD_SETTINGS_PATH=/data +# The root (assets, /APIKEY.txt, relative favicon paths) stays /. +ENV ETHERPAD_SETTINGS_PATH=/ +ENV ETHERPAD_SETTINGS_FILE=/data/settings.json # Named like in the README, and on PATH: `docker exec # etherpad-go config show`, or a shell (busybox) with `docker exec -it # sh` (busybox: sh, ls, cat, vi, ...). /app stays as a link for deployments that start /app. diff --git a/Dockerfile.build b/Dockerfile.build index 8651ef3c..83eaf25a 100644 --- a/Dockerfile.build +++ b/Dockerfile.build @@ -36,10 +36,13 @@ EXPOSE 3000 ENV NODE_ENV=production # The server runs as an unprivileged user. It writes to /var (the SQLite # database var/etherpad.db and the update state) and to /data (settings.json -# saved in the admin UI); both belong to that user. A volume on /var from -# an image before this one belongs to root; hand it over once with +# saved in the admin UI); both belong to that user in the image. A volume +# or host directory mounted there must be writable for 65532: one from an +# image before this one belongs to root; hand it over once with # docker run --rm -v :/var alpine chown -R 65532:65532 /var -ENV ETHERPAD_SETTINGS_PATH=/data +# The root (assets, /APIKEY.txt, relative favicon paths) stays /. +ENV ETHERPAD_SETTINGS_PATH=/ +ENV ETHERPAD_SETTINGS_FILE=/data/settings.json # Named like in the README, and on PATH: `docker exec # etherpad-go config show`, or a shell (busybox) with `docker exec -it # sh` (busybox: sh, ls, cat, vi, ...). /app stays as a link for deployments that start /app. diff --git a/README.md b/README.md index 24f2fe1f..e1daf206 100644 --- a/README.md +++ b/README.md @@ -156,15 +156,27 @@ docker exec etherpad_go etherpad-go config get port ### Files and the user in the image The server runs as the unprivileged user `65532`. It writes to two directories, which belong to -that user: +that user in the image: | Directory | What | Mount a volume here for | |---|---|---| | `/var` | the SQLite database (`var/etherpad.db`, the default) and the update state | SQLite | -| `/data` | `settings.json` (`ETHERPAD_SETTINGS_PATH=/data`), also as saved in the admin UI | settings | +| `/data` | `settings.json` (`ETHERPAD_SETTINGS_FILE=/data/settings.json`), also as saved in the admin UI | settings | -A `settings.json` mounted at `/settings.json` is still read, as long as there is none in `/data`. -Settings saved in the admin UI go to `/data/settings.json`, which is then the one read. +The ownership in the image only covers the directories themselves and a named Docker volume +created from them. **A host directory you bind-mount at `/var` or `/data` keeps its own owner** +and must be writable for `65532`, or the server cannot open SQLite or save settings from the +admin UI: + +```sh +sudo chown -R 65532:65532 ./etherpad-data +``` + +A `settings.json` mounted at `/settings.json` is still read, as long as `/data/settings.json` does +not exist. Settings saved in the admin UI go to `/data/settings.json`, which is then the one read. +`/APIKEY.txt` and relative favicon paths are still looked up in `/`. If a settings file exists +but cannot be read (no permission), the server does not start rather than fall back to the +defaults. Upgrading from an image that ran as root: a volume on `/var` belongs to root, and the server stops with `attempt to write a readonly database`. Hand it over once: diff --git a/lib/settings/Settings.go b/lib/settings/Settings.go index b6e54b8d..c25b5ad0 100644 --- a/lib/settings/Settings.go +++ b/lib/settings/Settings.go @@ -433,7 +433,11 @@ type Settings struct { Plugins map[string]PluginSettings `json:"plugins" mapstructure:"plugins"` // Untracked fields - Root string `json:"-"` + Root string `json:"-"` + // SettingsFile is the settings.json read at start ("" for none) and + // SettingsSaveFile the one the admin UI saves to (settingsFiles). + SettingsFile string `json:"-" mapstructure:"-"` + SettingsSaveFile string `json:"-" mapstructure:"-"` GitVersion string `json:"-"` RandomVersionString string `json:"-"` } @@ -515,7 +519,8 @@ func InitSettings(logger *zap.SugaredLogger) { setting, err := ReadConfig() if err != nil { - logger.Errorf("Error during reading the config " + err.Error()) + // Never start on defaults instead: they do not require a login. + logger.Fatalf("Error during reading the config: %v", err) return } diff --git a/lib/settings/cli.go b/lib/settings/cli.go index 6b8846ba..d743cce6 100644 --- a/lib/settings/cli.go +++ b/lib/settings/cli.go @@ -18,14 +18,14 @@ func HandleConfigCommand(logger *zap.SugaredLogger) { ApplyRegistryDefaults() switch os.Args[2] { case "show": - InitSettings(logger) + readConfigForCLI() configShow() case "dump": configDump() case "env": configEnv() case "get": - InitSettings(logger) + readConfigForCLI() configGet(os.Args[3:]) case "init": configInit() @@ -37,6 +37,15 @@ func HandleConfigCommand(logger *zap.SugaredLogger) { os.Exit(0) } +// readConfigForCLI loads the settings like the server, without its setup +// (no database directory is created). +func readConfigForCLI() { + if _, err := ReadConfig(); err != nil { + fmt.Fprintln(os.Stderr, "Error reading the config:", err) + os.Exit(1) + } +} + func configShow() { fmt.Printf( "%-35s %-35s %-20s %-20s %s\n", diff --git a/lib/settings/settingsfile.go b/lib/settings/settingsfile.go index d9463ac3..6d64c681 100644 --- a/lib/settings/settingsfile.go +++ b/lib/settings/settingsfile.go @@ -1,33 +1,52 @@ package settings import ( + "errors" + "fmt" "os" - "path/filepath" ) -// SettingsPathEnv names the directory of settings.json (the Docker image -// sets /data, which its user can write). -const SettingsPathEnv = "ETHERPAD_SETTINGS_PATH" +const ( + // SettingsPathEnv is the server's root: assets, APIKEY.txt and relative + // favicon paths are looked up there. + SettingsPathEnv = "ETHERPAD_SETTINGS_PATH" + // SettingsFileEnv is the settings.json to read and to save from the + // admin UI (the Docker image: /data/settings.json, which its + // unprivileged user can write). Unset: settings.json in the working + // directory. + SettingsFileEnv = "ETHERPAD_SETTINGS_FILE" +) -// SettingsFile is the settings.json read for dir (ETHERPAD_SETTINGS_PATH, -// or the server's root in the admin UI): the one in dir when dir holds -// one, otherwise settings.json in the working directory (a file mounted -// there keeps working). -func SettingsFile(dir string) string { - if dir != "" { - p := filepath.Join(dir, "settings.json") - if _, err := os.Stat(p); err == nil { - return p - } - } - return "settings.json" -} +const workingDirSettings = "settings.json" -// SettingsWriteFile is where the admin UI saves settings.json for dir: in -// dir (SettingsFile then reads it from there), or the working directory. -func SettingsWriteFile(dir string) string { - if dir != "" { - return filepath.Join(dir, "settings.json") +// settingsFiles are the settings.json the server reads ("" when there is +// none) and the one the admin UI saves to. Reading and saving go by the +// same rule: +// +// - ETHERPAD_SETTINGS_FILE set: that file; while it does not exist yet, +// settings.json in the working directory is read (a file mounted at +// /settings.json keeps working) and the first save creates it; +// - otherwise settings.json in the working directory, for both. +// +// Only a missing file counts as missing: any other error (no permission, +// say) is returned, so the server does not start on defaults, without the +// authentication its settings ask for. +func settingsFiles() (read, save string, err error) { + save = workingDirSettings + if f := os.Getenv(SettingsFileEnv); f != "" { + save = f + } + for _, candidate := range []string{save, workingDirSettings} { + _, statErr := os.Stat(candidate) + if statErr == nil { + return candidate, save, nil + } + if !errors.Is(statErr, os.ErrNotExist) { + return "", save, fmt.Errorf("settings file %s: %w", candidate, statErr) + } + if candidate == workingDirSettings { + break + } } - return "settings.json" + return "", save, nil } diff --git a/lib/settings/settingsfile_test.go b/lib/settings/settingsfile_test.go index cc9bcb7e..3881b700 100644 --- a/lib/settings/settingsfile_test.go +++ b/lib/settings/settingsfile_test.go @@ -9,33 +9,72 @@ import ( "github.com/stretchr/testify/require" ) -func TestSettingsFile(t *testing.T) { +func TestSettingsFiles(t *testing.T) { wd := t.TempDir() - dir := t.TempDir() t.Chdir(wd) + file := filepath.Join(t.TempDir(), "settings.json") - assert.Equal(t, "settings.json", SettingsFile(""), "no directory: the working directory") - assert.Equal(t, "settings.json", SettingsWriteFile("")) + read, save, err := settingsFiles() + require.NoError(t, err) + assert.Equal(t, "", read, "none yet") + assert.Equal(t, "settings.json", save, "unset: the working directory") + + require.NoError(t, os.WriteFile("settings.json", []byte("{}"), 0o644)) + read, save, err = settingsFiles() + require.NoError(t, err) + assert.Equal(t, "settings.json", read) + assert.Equal(t, "settings.json", save, "read and saved in the same place") - // A directory without a settings.json: still the one in the working - // directory (a file mounted at /settings.json), but saves go to dir. - require.NoError(t, os.WriteFile(filepath.Join(wd, "settings.json"), []byte("{}"), 0o644)) - assert.Equal(t, "settings.json", SettingsFile(dir)) - assert.Equal(t, filepath.Join(dir, "settings.json"), SettingsWriteFile(dir)) + // ETHERPAD_SETTINGS_FILE not there yet: the working directory's file is + // read (one mounted at /settings.json), the first save creates it. + t.Setenv(SettingsFileEnv, file) + read, save, err = settingsFiles() + require.NoError(t, err) + assert.Equal(t, "settings.json", read) + assert.Equal(t, file, save) + + require.NoError(t, os.WriteFile(file, []byte("{}"), 0o644)) + read, save, err = settingsFiles() + require.NoError(t, err) + assert.Equal(t, file, read) + assert.Equal(t, file, save) + + // ETHERPAD_SETTINGS_PATH (the root for assets, APIKEY.txt and the + // favicon) has no say in where settings.json is. + t.Setenv(SettingsPathEnv, t.TempDir()) + read, _, err = settingsFiles() + require.NoError(t, err) + assert.Equal(t, file, read) +} + +// A settings file that is there but cannot be reached must stop the +// start: falling back to defaults would drop requireAuthentication. +func TestSettingsFilesRefusesUnreadable(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads every directory") + } + t.Chdir(t.TempDir()) + locked := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(locked, "settings.json"), []byte(`{"requireAuthentication": true}`), 0o644)) + require.NoError(t, os.Chmod(locked, 0o000)) + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + t.Setenv(SettingsFileEnv, filepath.Join(locked, "settings.json")) - // Once saved there, it is the one read. - require.NoError(t, os.WriteFile(filepath.Join(dir, "settings.json"), []byte("{}"), 0o644)) - assert.Equal(t, filepath.Join(dir, "settings.json"), SettingsFile(dir)) - assert.Equal(t, filepath.Join(dir, "settings.json"), SettingsWriteFile(dir)) + _, _, err := settingsFiles() + assert.ErrorIs(t, err, os.ErrPermission) + _, err = ReadConfig() + assert.Error(t, err) } -func TestReadConfigReadsTheSettingsPath(t *testing.T) { +func TestReadConfigReadsTheSettingsFile(t *testing.T) { t.Chdir(t.TempDir()) - dir := t.TempDir() - t.Setenv(SettingsPathEnv, dir) - require.NoError(t, os.WriteFile(filepath.Join(dir, "settings.json"), - []byte(`{ "title": "From the settings path", /* comment */ }`), 0o644)) + file := filepath.Join(t.TempDir(), "settings.json") + t.Setenv(SettingsFileEnv, file) + require.NoError(t, os.WriteFile(file, + []byte(`{ "title": "From the settings file", /* comment */ }`), 0o644)) s, err := ReadConfig() require.NoError(t, err) - assert.Equal(t, "From the settings path", s.Title) + assert.Equal(t, "From the settings file", s.Title) + assert.Equal(t, file, s.SettingsFile) + assert.Equal(t, file, s.SettingsSaveFile) } diff --git a/lib/settings/viper.go b/lib/settings/viper.go index 4c89cc44..9672eb04 100644 --- a/lib/settings/viper.go +++ b/lib/settings/viper.go @@ -2,7 +2,6 @@ package settings import ( "bytes" - "errors" "fmt" "os" "strings" @@ -23,8 +22,15 @@ func ReadConfig() (*Settings, error) { viper.SetConfigType("json") // settings.json may hold comments, trailing commas and ${VAR:default} // values, like etherpad-lite's; viper reads plain JSON. - file := SettingsFile(os.Getenv(SettingsPathEnv)) - if raw, err := os.ReadFile(file); err == nil { + file, saveFile, err := settingsFiles() + if err != nil { + return nil, err + } + if file != "" { + raw, err := os.ReadFile(file) + if err != nil { + return nil, fmt.Errorf("settings file %s: %w", file, err) + } prepared, err := PrepareSettingsJSON(raw) if err != nil { return nil, fmt.Errorf("%s: %w", file, err) @@ -32,8 +38,6 @@ func ReadConfig() (*Settings, error) { if err := viper.ReadConfig(bytes.NewReader(prepared)); err != nil { return nil, err } - } else if !errors.Is(err, os.ErrNotExist) { - return nil, err } // Older settings files (and etherpad-lite's template) wrote @@ -74,6 +78,7 @@ func ReadConfig() (*Settings, error) { // An unknown mode must not log addresses. s.IPLogging = IPLoggingAnonymous } + s.SettingsFile, s.SettingsSaveFile = file, saveFile return &s, nil } diff --git a/lib/test/ws/admin_message_handler_test.go b/lib/test/ws/admin_message_handler_test.go index 8303295a..5b001c33 100644 --- a/lib/test/ws/admin_message_handler_test.go +++ b/lib/test/ws/admin_message_handler_test.go @@ -702,7 +702,7 @@ func testSaveSettings(t *testing.T, ds testutils.TestDataStore) { hub := ws.NewHub() settingsToLoad := settings.Displayed settingsToLoad.ShowSettingsInAdminPage = true - settingsToLoad.Root = t.TempDir() + settingsToLoad.SettingsSaveFile = filepath.Join(t.TempDir(), "settings.json") client := &ws.Client{ Hub: hub, Conn: ds.MockWebSocket, @@ -784,7 +784,7 @@ func testSettingsReadOnlyInCluster(t *testing.T, ds testutils.TestDataStore) { settingsToLoad := settings.Displayed settingsToLoad.DBType = "postgres" settingsToLoad.Cluster.Mode = "on" - settingsToLoad.Root = t.TempDir() + settingsToLoad.SettingsSaveFile = filepath.Join(t.TempDir(), "settings.json") settingsToLoad.ShowSettingsInAdminPage = true client := &ws.Client{ Hub: hub, @@ -816,6 +816,6 @@ func testSettingsReadOnlyInCluster(t *testing.T, ds testutils.TestDataStore) { assert.Nil(t, result["success"]) assert.Contains(t, result["error"], "read-only in a cluster") - _, statErr := os.Stat(filepath.Join(settingsToLoad.Root, "settings.json")) + _, statErr := os.Stat(settingsToLoad.SettingsSaveFile) assert.True(t, os.IsNotExist(statErr), "no settings.json may be written") } diff --git a/lib/test/ws/admin_settings_file_test.go b/lib/test/ws/admin_settings_file_test.go index 4ef1fc68..af97f518 100644 --- a/lib/test/ws/admin_settings_file_test.go +++ b/lib/test/ws/admin_settings_file_test.go @@ -42,7 +42,8 @@ func adminAsk(t *testing.T, ds testutils.TestDataStore, event string, data any) func testAdminSettingsFile(t *testing.T, ds testutils.TestDataStore) { dir := t.TempDir() - ds.Settings.Root = dir + ds.Settings.SettingsFile = filepath.Join(dir, "settings.json") + ds.Settings.SettingsSaveFile = filepath.Join(dir, "settings.json") ds.Settings.ShowSettingsInAdminPage = true ds.Settings.TrustProxy = true pw := "db-secret" diff --git a/lib/ws/AdminMessageHandler.go b/lib/ws/AdminMessageHandler.go index 508b01b6..e5b7bf63 100644 --- a/lib/ws/AdminMessageHandler.go +++ b/lib/ws/AdminMessageHandler.go @@ -75,7 +75,13 @@ func (h AdminMessageHandler) HandleMessage(message admin.EventMessage, retrieved if !retrievedSettings.ShowSettingsInAdminPage { resp[1] = map[string]interface{}{"results": "NOT_ALLOWED"} } else { - raw, err := os.ReadFile(settings.SettingsFile(retrievedSettings.Root)) + // The file the server started with, or the one a save + // creates when there was none. + file := retrievedSettings.SettingsFile + if file == "" { + file = retrievedSettings.SettingsSaveFile + } + raw, err := os.ReadFile(file) if err != nil && !os.IsNotExist(err) { h.Logger.Errorf("Reading the settings file: %v", err) } @@ -535,7 +541,10 @@ func (h AdminMessageHandler) HandleMessage(message admin.EventMessage, retrieved c.SafeSend(responseBytes) return } - settingsPath := settings.SettingsWriteFile(retrievedSettings.Root) + settingsPath := retrievedSettings.SettingsSaveFile + if settingsPath == "" { + settingsPath = "settings.json" + } if err := writeFileAtomic(settingsPath, []byte(settingsJSON)); err != nil { h.Logger.Errorf("Error saving settings: %v", err) resp := make([]interface{}, 2)