Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FIX (docker): Support mounted storage permissions

Rostislav Dugin01496e173259
diff --git a/Dockerfile b/Dockerfile
index 534fabff..0df2fa7a 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -162,21 +162,12 @@ RUN --mount=type=bind,source=assets/tools,target=/ctx/tools,readonly \
RUN set -eux; \
groupmod -g 999 postgres; \
usermod -u 999 postgres; \
- chown -R postgres:postgres \
+ groupmod -n databasus postgres; \
+ usermod -l databasus -s /usr/sbin/nologin postgres; \
+ chown -R databasus:databasus \
/var/lib/postgresql /etc/postgresql /var/log/postgresql /run/postgresql; \
- mkdir -p /databasus-data/pgdata; \
- chown -R postgres:postgres /databasus-data/pgdata
-
-# PostgreSQL traverses the shared data root through the Databasus group.
-RUN set -eux; \
- groupadd -g 65532 databasus; \
- useradd -r -s /usr/sbin/nologin -u 65532 -g databasus databasus; \
- usermod -aG databasus postgres
-
-ENV DATABASUS_PUID=65532 \
- DATABASUS_PGID=65532 \
- POSTGRES_PUID=999 \
- POSTGRES_PGID=999
+ mkdir -p /databasus-data; \
+ chown databasus:databasus /databasus-data
WORKDIR /app
@@ -206,253 +197,10 @@ COPY --from=verification-agent-build /verification-agent-binaries/* ./agent-bina
# overwrite already-set variables.
COPY .env.example /.env
-# Create startup script
-COPY <<EOF /app/start.sh
-#!/bin/bash
-set -e
-export TMPDIR=/tmp
-
-if [ -d "/postgresus-data" ] && [ "\$(ls -A /postgresus-data 2>/dev/null)" ]; then
- echo ""
- echo "=========================================="
- echo "ERROR: Legacy volume detected!"
- echo "=========================================="
- echo ""
- echo "You are using the /postgresus-data folder. It seems you changed the image name from Postgresus to Databasus without changing the volume."
- echo ""
- echo "Please either:"
- echo " 1. Switch back to image rostislavdugin/postgresus:latest (supported until ~Dec 2026)"
- echo " 2. Read the migration guide: https://databasus.com/installation/#postgresus-migration"
- echo ""
- echo "=========================================="
- exit 1
-fi
-
-# ========= Configure service identities =========
-[ "\$(id -g postgres)" = "\$POSTGRES_PGID" ] || groupmod -g "\$POSTGRES_PGID" postgres
-[ "\$(id -g databasus)" = "\$DATABASUS_PGID" ] || groupmod -g "\$DATABASUS_PGID" databasus
-[ "\$(id -u postgres)" = "\$POSTGRES_PUID" ] || usermod -u "\$POSTGRES_PUID" postgres
-[ "\$(id -u databasus)" = "\$DATABASUS_PUID" ] || usermod -u "\$DATABASUS_PUID" databasus
-
-# PostgreSQL 17 binary paths
-PG_BIN="/usr/lib/postgresql/17/bin"
-
-# Generate runtime configuration for frontend
-echo "Generating runtime configuration..."
-
-# Detect if email is configured (both SMTP_HOST and DATABASUS_URL must be set)
-if [ -n "\${SMTP_HOST:-}" ] && [ -n "\${DATABASUS_URL:-}" ]; then
- IS_EMAIL_CONFIGURED="true"
-else
- IS_EMAIL_CONFIGURED="false"
-fi
-
-cat > /app/ui/build/runtime-config.js <<JSEOF
-// Runtime configuration injected at container startup
-// This file is generated dynamically and should not be edited manually
-window.__RUNTIME_CONFIG__ = {
- GITHUB_CLIENT_ID: '\${GITHUB_CLIENT_ID:-}',
- GOOGLE_CLIENT_ID: '\${GOOGLE_CLIENT_ID:-}',
- IS_EMAIL_CONFIGURED: '\$IS_EMAIL_CONFIGURED',
- CLOUDFLARE_TURNSTILE_SITE_KEY: '\${CLOUDFLARE_TURNSTILE_SITE_KEY:-}',
- CONTAINER_ARCH: '\${CONTAINER_ARCH:-unknown}'
-};
-JSEOF
-
-# Inject analytics script if provided (only if not already injected)
-if [ -n "\${ANALYTICS_SCRIPT:-}" ]; then
- if ! grep -q "rybbit.databasus.com" /app/ui/build/index.html 2>/dev/null; then
- echo "Injecting analytics script..."
- sed -i "s#</head># \${ANALYTICS_SCRIPT}\\
- </head>#" /app/ui/build/index.html
- fi
-fi
-
-# Ensure proper ownership of data directory
-echo "Setting up data directory permissions..."
-mkdir -p /databasus-data/{pgdata,pgsocket,temp,backups}
-chown databasus:databasus /databasus-data 2>/dev/null || true
-chmod g+x /databasus-data 2>/dev/null || true
-chown postgres:postgres /databasus-data/pgdata /databasus-data/pgsocket 2>/dev/null || true
-chown databasus:databasus /databasus-data/temp /databasus-data/backups 2>/dev/null || true
-chown databasus:databasus /databasus-data/secret.key /databasus-data/instance.json 2>/dev/null || true
-chmod 700 /databasus-data/temp /databasus-data/pgsocket 2>/dev/null || true
-
-# ========= Start Valkey (internal cache) =========
-echo "Configuring Valkey cache..."
-cat > /tmp/valkey.conf << 'VALKEY_CONFIG'
-port 6379
-bind 127.0.0.1
-protected-mode yes
-save ""
-maxmemory 256mb
-maxmemory-policy allkeys-lru
-VALKEY_CONFIG
-
-echo "Starting Valkey..."
-valkey-server /tmp/valkey.conf &
-VALKEY_PID=\$!
-
-echo "Waiting for Valkey to be ready..."
-for i in {1..30}; do
- if valkey-cli ping >/dev/null 2>&1; then
- echo "Valkey is ready!"
- break
- fi
- sleep 1
-done
-
-# Initialize PostgreSQL if not already initialized
-if [ ! -s "/databasus-data/pgdata/PG_VERSION" ]; then
- echo "Initializing PostgreSQL database..."
- gosu postgres \$PG_BIN/initdb -D /databasus-data/pgdata --encoding=UTF8 --locale=C.UTF-8
-
- # Configure PostgreSQL
- echo "port = 5437" >> /databasus-data/pgdata/postgresql.conf
- echo "listen_addresses = 'localhost'" >> /databasus-data/pgdata/postgresql.conf
- echo "shared_buffers = 256MB" >> /databasus-data/pgdata/postgresql.conf
- echo "max_connections = 100" >> /databasus-data/pgdata/postgresql.conf
-fi
-
-cat > /databasus-data/pgdata/pg_hba.conf.new << 'PG_HBA'
-local all postgres peer
-local all all reject
-local replication all reject
-host all all 127.0.0.1/32 scram-sha-256
-host all all ::1/128 scram-sha-256
-host replication all 127.0.0.1/32 reject
-host replication all ::1/128 reject
-PG_HBA
-chown postgres:postgres /databasus-data/pgdata/pg_hba.conf.new
-chmod 600 /databasus-data/pgdata/pg_hba.conf.new
-mv /databasus-data/pgdata/pg_hba.conf.new /databasus-data/pgdata/pg_hba.conf
-
-INTERNAL_POSTGRES_PASSWORD=\$(od -An -N32 -tx1 /dev/urandom | tr -d '[:space:]')
-
-# Function to start PostgreSQL and wait for it to be ready
-start_postgres() {
- echo "Starting PostgreSQL..."
- gosu postgres \$PG_BIN/postgres \\
- -D /databasus-data/pgdata \\
- -p 5437 \\
- -k /databasus-data/pgsocket \\
- -c password_encryption=scram-sha-256 &
- POSTGRES_PID=\$!
-
- echo "Waiting for PostgreSQL to be ready..."
- for i in {1..30}; do
- if gosu postgres \$PG_BIN/pg_isready -p 5437 -h /databasus-data/pgsocket >/dev/null 2>&1; then
- echo "PostgreSQL is ready!"
- return 0
- fi
- sleep 1
- done
- return 1
-}
-
-# Try to start PostgreSQL
-if ! start_postgres; then
- echo ""
- echo "=========================================="
- echo "PostgreSQL failed to start. Attempting WAL reset recovery..."
- echo "=========================================="
- echo ""
-
- # Kill any remaining postgres processes
- pkill -9 postgres 2>/dev/null || true
- sleep 2
-
- # Attempt pg_resetwal to recover from WAL corruption
- echo "Running pg_resetwal to reset WAL..."
- if gosu postgres \$PG_BIN/pg_resetwal -f /databasus-data/pgdata; then
- echo "WAL reset successful. Restarting PostgreSQL..."
-
- # Try starting PostgreSQL again after WAL reset
- if start_postgres; then
- echo "PostgreSQL recovered successfully after WAL reset!"
- else
- echo ""
- echo "=========================================="
- echo "ERROR: PostgreSQL failed to start even after WAL reset."
- echo "The database may be severely corrupted."
- echo ""
- echo "Options:"
- echo " 1. Delete the volume and start fresh (data loss)"
- echo " 2. Manually inspect /databasus-data/pgdata for issues"
- echo "=========================================="
- exit 1
- fi
- else
- echo ""
- echo "=========================================="
- echo "ERROR: pg_resetwal failed."
- echo "The database may be severely corrupted."
- echo ""
- echo "Options:"
- echo " 1. Delete the volume and start fresh (data loss)"
- echo " 2. Manually inspect /databasus-data/pgdata for issues"
- echo "=========================================="
- exit 1
- fi
-fi
-
-# Create database and set password for postgres user
-echo "Setting up database and user..."
-gosu postgres \$PG_BIN/psql \\
- -v ON_ERROR_STOP=1 \\
- -v internal_postgres_password="\$INTERNAL_POSTGRES_PASSWORD" \\
- -p 5437 \\
- -h /databasus-data/pgsocket \\
- -d postgres << 'SQL'
-
-ALTER USER postgres WITH PASSWORD :'internal_postgres_password';
-SELECT 'CREATE DATABASE databasus OWNER postgres'
-WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'databasus')
-\\gexec
-\\q
-SQL
-
-if [ -z "\${DATABASE_DSN+x}" ]; then
- export DATABASE_DSN="host=localhost user=postgres password=\$INTERNAL_POSTGRES_PASSWORD dbname=databasus port=5437 sslmode=disable"
-fi
-
-echo "Checking for legacy WAL backup configuration..."
-WAL_CHECK_COL=\$(gosu databasus env PGPASSWORD="\$INTERNAL_POSTGRES_PASSWORD" \\
- \$PG_BIN/psql -h localhost -p 5437 -U postgres -d databasus -tA \\
- -c "SELECT 1 FROM information_schema.columns WHERE table_name='postgresql_databases' AND column_name='backup_type' LIMIT 1" \\
- 2>/dev/null || true)
-
-if [ "\$WAL_CHECK_COL" = "1" ]; then
- WAL_CHECK_ROW=\$(gosu databasus env PGPASSWORD="\$INTERNAL_POSTGRES_PASSWORD" \\
- \$PG_BIN/psql -h localhost -p 5437 -U postgres -d databasus -tA \\
- -c "SELECT 1 FROM postgresql_databases WHERE backup_type='WAL_V1' LIMIT 1" \\
- 2>/dev/null || true)
- if [ "\$WAL_CHECK_ROW" = "1" ]; then
- echo ""
- echo "=========================================="
- echo "ERROR: Agent (WAL_V1) backup approach is no longer supported."
- echo "=========================================="
- echo ""
- echo "Please downgrade to version 3.42.0, remove all WAL-mode databases"
- echo "manually and then upgrade again. This safeguard exists to avoid"
- echo "corrupting already-set-up agents."
- echo ""
- echo "=========================================="
- exit 1
- fi
-fi
-echo "No legacy WAL backup data detected."
-
-# Start the main application
-echo "Starting Databasus application..."
-
-exec gosu databasus ./main
-EOF
+COPY --chmod=0755 docker/start.sh /app/start.sh
LABEL org.opencontainers.image.source="https://github.com/databasus/databasus"
-RUN chmod +x /app/start.sh
-
EXPOSE 4005
# Liveness probe: the runtime image ships no wget/curl, so the binary checks
diff --git a/backend/cmd/cleanup_test_db/main.go b/backend/cmd/cleanup_test_db/main.go
index a689e1ce..e1117688 100644
--- a/backend/cmd/cleanup_test_db/main.go
+++ b/backend/cmd/cleanup_test_db/main.go
@@ -12,9 +12,8 @@
// with "permission denied for schema public".
//
// Reads the test DSN through config (config.GetEnv() auto-swaps DatabaseDsn to
-// TestDatabaseDsn when IsTesting is true). IsTesting is detected from os.Args
-// containing the substring "test" - the binary path "cleanup_test_db" satisfies
-// that. Renaming the binary or its directory will break detection.
+// TestDatabaseDsn when IsTesting is true). The executable name cleanup_test_db
+// selects that mode.
package main
import (
@@ -48,7 +47,7 @@ func main() {
env := config.GetEnv()
if !env.IsTesting {
- log.Error("cleanup_test_db must run with IsTesting=true (binary name must contain 'test')")
+ log.Error("cleanup_test_db must run with IsTesting=true")
os.Exit(1)
}
diff --git a/backend/cmd/main.go b/backend/cmd/main.go
index ece913f4..19a9ca45 100644
--- a/backend/cmd/main.go
+++ b/backend/cmd/main.go
@@ -76,9 +76,19 @@ func main() {
return
}
+ commandLineOptions := parseCommandLineOptions()
ctx := context.Background()
log := logger.GetLogger()
+ if commandLineOptions.shouldTestStorage {
+ storageTestCommand := newStorageTestCommand(log, storageTestCommandWriters{
+ standardOutput: os.Stdout,
+ errorOutput: os.Stderr,
+ })
+ logger.ExitAfterFlush(storageTestCommand.SaveAndDeleteProbe(ctx))
+ return
+ }
+
cache_utils.TestCacheConnection()
log.Info("clearing cache")
@@ -113,7 +123,7 @@ func main() {
logger.ExitAfterFlush(1)
}
- resetPasswordIfRequested(ctx, log)
+ resetPasswordIfRequested(ctx, log, commandLineOptions)
go generateSwaggerDocs(log)
@@ -146,26 +156,48 @@ func main() {
startServerWithGracefulShutdown(log, ginApp)
}
-func resetPasswordIfRequested(ctx context.Context, log *slog.Logger) {
- audit_logs.SetupDependencies()
+type commandLineOptions struct {
+ shouldTestStorage bool
+ newPassword string
+ passwordResetEmail string
+}
+func parseCommandLineOptions() commandLineOptions {
+ shouldTestStorage := flag.Bool("test-storage", false, "Save and delete a local storage probe")
newPassword := flag.String("new-password", "", "Set a new password for the user")
- email := flag.String("email", "", "Email of the user to reset password")
-
+ passwordResetEmail := flag.String("email", "", "Email of the user to reset password")
flag.Parse()
- if *newPassword == "" {
+ return commandLineOptions{
+ shouldTestStorage: *shouldTestStorage,
+ newPassword: *newPassword,
+ passwordResetEmail: *passwordResetEmail,
+ }
+}
+
+func resetPasswordIfRequested(
+ ctx context.Context,
+ log *slog.Logger,
+ commandLineOptions commandLineOptions,
+) {
+ if commandLineOptions.newPassword == "" {
return
}
+ audit_logs.SetupDependencies()
log.InfoContext(ctx, "found reset password command, resetting password")
- if *email == "" {
+ if commandLineOptions.passwordResetEmail == "" {
log.InfoContext(ctx, "no email provided, pass one via --email=\"[email protected]\"")
logger.ExitAfterFlush(1)
}
- resetPassword(ctx, *email, *newPassword, log)
+ resetPassword(
+ ctx,
+ commandLineOptions.passwordResetEmail,
+ commandLineOptions.newPassword,
+ log,
+ )
}
func resetPassword(ctx context.Context, email, newPassword string, log *slog.Logger) {
diff --git a/backend/cmd/storage_command.go b/backend/cmd/storage_command.go
new file mode 100644
index 00000000..3b70bddc
--- /dev/null
+++ b/backend/cmd/storage_command.go
@@ -0,0 +1,128 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/google/uuid"
+
+ "databasus-backend/internal/config"
+ local_storage "databasus-backend/internal/features/storages/models/local"
+ "databasus-backend/internal/util/encryption"
+)
+
+const (
+ storagePermissionsDocumentationURL = "https://databasus.com/advanced-config/#docker-storage-permissions"
+ storageProbeContent = "databasus storage test"
+)
+
+type storageFileSaverAndDeleter interface {
+ SaveFile(
+ ctx context.Context,
+ encryptor encryption.FieldEncryptor,
+ logger *slog.Logger,
+ fileName string,
+ file io.Reader,
+ ) error
+ DeleteFile(
+ ctx context.Context,
+ encryptor encryption.FieldEncryptor,
+ logger *slog.Logger,
+ fileName string,
+ ) error
+}
+
+type storageTestCommandWriters struct {
+ standardOutput io.Writer
+ errorOutput io.Writer
+}
+
+type storageTestCommand struct {
+ storage storageFileSaverAndDeleter
+ fieldEncryptor encryption.FieldEncryptor
+ logger *slog.Logger
+ writers storageTestCommandWriters
+ temporaryFolder string
+ backupFolder string
+}
+
+func newStorageTestCommand(
+ logger *slog.Logger,
+ writers storageTestCommandWriters,
+) storageTestCommand {
+ environment := config.GetEnv()
+
+ return storageTestCommand{
+ storage: &local_storage.LocalStorage{},
+ fieldEncryptor: encryption.GetFieldEncryptor(),
+ logger: logger,
+ writers: writers,
+ temporaryFolder: environment.TempFolder,
+ backupFolder: environment.DataFolder,
+ }
+}
+
+func (c storageTestCommand) SaveAndDeleteProbe(ctx context.Context) int {
+ probeFileName := ".databasus-storage-test-" + uuid.NewString()
+ probeContent := strings.NewReader(storageProbeContent)
+
+ if err := c.storage.SaveFile(ctx, c.fieldEncryptor, c.logger, probeFileName, probeContent); err != nil {
+ c.removeTemporaryProbeAfterFailedSave(ctx, probeFileName)
+ c.reportFailure(ctx, "save a file through local storage", err)
+ return 1
+ }
+
+ if err := c.storage.DeleteFile(ctx, c.fieldEncryptor, c.logger, probeFileName); err != nil {
+ c.reportFailure(ctx, "delete a file through local storage", err)
+ return 1
+ }
+
+ if _, err := fmt.Fprintln(c.writers.standardOutput, "storage test passed"); err != nil {
+ return 1
+ }
+
+ return 0
+}
+
+func (c storageTestCommand) removeTemporaryProbeAfterFailedSave(ctx context.Context, probeFileName string) {
+ temporaryProbePath := filepath.Join(c.temporaryFolder, probeFileName)
+ if err := os.Remove(temporaryProbePath); err != nil && !os.IsNotExist(err) {
+ c.logger.WarnContext(
+ ctx,
+ "failed to remove storage test temporary file",
+ "path",
+ temporaryProbePath,
+ "error",
+ err,
+ )
+ }
+}
+
+func (c storageTestCommand) reportFailure(
+ ctx context.Context,
+ operation string,
+ operationError error,
+) {
+ _, writeError := fmt.Fprintf(
+ c.writers.errorOutput,
+ "ERROR: Databasus cannot write to local storage paths %s and %s as UID %d and GID %d.\n"+
+ "Required operation: %s.\n"+
+ "Set PUID and PGID or fix the mounted directory permissions: %s\n"+
+ "Details: %v\n",
+ c.temporaryFolder,
+ c.backupFolder,
+ os.Geteuid(),
+ os.Getegid(),
+ operation,
+ storagePermissionsDocumentationURL,
+ operationError,
+ )
+ if writeError != nil {
+ c.logger.ErrorContext(ctx, "failed to write storage test error", "error", writeError)
+ }
+}
diff --git a/backend/cmd/storage_command_test.go b/backend/cmd/storage_command_test.go
new file mode 100644
index 00000000..9ebc4614
--- /dev/null
+++ b/backend/cmd/storage_command_test.go
@@ -0,0 +1,144 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/encryption"
+)
+
+type fakeStorageFileSaverAndDeleter struct {
+ saveError error
+ deleteError error
+ savedFileName string
+ deletedFileName string
+ savedContent string
+ temporaryFolder string
+}
+
+func (f *fakeStorageFileSaverAndDeleter) SaveFile(
+ _ context.Context,
+ _ encryption.FieldEncryptor,
+ _ *slog.Logger,
+ fileName string,
+ file io.Reader,
+) error {
+ f.savedFileName = fileName
+
+ fileContent, err := io.ReadAll(file)
+ if err != nil {
+ return err
+ }
+ f.savedContent = string(fileContent)
+ if f.temporaryFolder != "" {
+ if err := os.WriteFile(
+ filepath.Join(f.temporaryFolder, fileName),
+ fileContent,
+ 0o600,
+ ); err != nil {
+ return err
+ }
+ }
+
+ return f.saveError
+}
+
+func (f *fakeStorageFileSaverAndDeleter) DeleteFile(
+ _ context.Context,
+ _ encryption.FieldEncryptor,
+ _ *slog.Logger,
+ fileName string,
+) error {
+ f.deletedFileName = fileName
+
+ return f.deleteError
+}
+
+func Test_StorageTestCommand_SavesAndDeletesProbe(t *testing.T) {
+ storage := &fakeStorageFileSaverAndDeleter{}
+ output := &bytes.Buffer{}
+ errorOutput := &bytes.Buffer{}
+ storageTestCommand := newTestStorageCommand(
+ storage,
+ storageTestCommandWriters{standardOutput: output, errorOutput: errorOutput},
+ "/storage/temp",
+ )
+
+ exitCode := storageTestCommand.SaveAndDeleteProbe(t.Context())
+
+ assert.Equal(t, 0, exitCode)
+ assert.True(t, strings.HasPrefix(storage.savedFileName, ".databasus-storage-test-"))
+ assert.Equal(t, storage.savedFileName, storage.deletedFileName)
+ assert.Equal(t, storageProbeContent, storage.savedContent)
+ assert.Equal(t, "storage test passed\n", output.String())
+ assert.Empty(t, errorOutput.String())
+}
+
+func Test_StorageTestCommand_WhenSaveFails_ReportsPermissionsAndRemovesTemporaryProbe(t *testing.T) {
+ temporaryFolder := t.TempDir()
+ storage := &fakeStorageFileSaverAndDeleter{
+ saveError: errors.New("permission denied"),
+ temporaryFolder: temporaryFolder,
+ }
+ output := &bytes.Buffer{}
+ errorOutput := &bytes.Buffer{}
+ storageTestCommand := newTestStorageCommand(
+ storage,
+ storageTestCommandWriters{standardOutput: output, errorOutput: errorOutput},
+ temporaryFolder,
+ )
+
+ exitCode := storageTestCommand.SaveAndDeleteProbe(t.Context())
+
+ assert.Equal(t, 1, exitCode)
+ assert.Empty(t, storage.deletedFileName)
+ assert.Empty(t, output.String())
+ assert.Contains(t, errorOutput.String(), "Required operation: save a file through local storage.")
+ assert.Contains(t, errorOutput.String(), temporaryFolder+" and /storage/backups")
+ assert.Contains(t, errorOutput.String(), storagePermissionsDocumentationURL)
+ assert.Contains(t, errorOutput.String(), "permission denied")
+ _, probeStatError := os.Stat(filepath.Join(temporaryFolder, storage.savedFileName))
+ assert.ErrorIs(t, probeStatError, os.ErrNotExist)
+}
+
+func Test_StorageTestCommand_WhenDeleteFails_ReportsDeleteFailure(t *testing.T) {
+ storage := &fakeStorageFileSaverAndDeleter{deleteError: errors.New("read-only filesystem")}
+ errorOutput := &bytes.Buffer{}
+ storageTestCommand := newTestStorageCommand(
+ storage,
+ storageTestCommandWriters{standardOutput: io.Discard, errorOutput: errorOutput},
+ "/storage/temp",
+ )
+
+ exitCode := storageTestCommand.SaveAndDeleteProbe(t.Context())
+
+ assert.Equal(t, 1, exitCode)
+ require.NotEmpty(t, storage.savedFileName)
+ assert.Equal(t, storage.savedFileName, storage.deletedFileName)
+ assert.Contains(t, errorOutput.String(), "Required operation: delete a file through local storage.")
+ assert.Contains(t, errorOutput.String(), "read-only filesystem")
+}
+
+func newTestStorageCommand(
+ storage storageFileSaverAndDeleter,
+ writers storageTestCommandWriters,
+ temporaryFolder string,
+) storageTestCommand {
+ return storageTestCommand{
+ storage: storage,
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ writers: writers,
+ temporaryFolder: temporaryFolder,
+ backupFolder: "/storage/backups",
+ }
+}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 4404c10e..892f5428 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -169,12 +169,7 @@ func loadEnvVariables() {
env.ShowDbInstallationVerificationLogs = true
}
- for _, arg := range os.Args {
- if strings.Contains(arg, "test") {
- env.IsTesting = true
- break
- }
- }
+ env.IsTesting = isTestProcess(os.Args)
if env.IsTesting {
if env.TestDatabaseDsn == "" {
@@ -267,6 +262,18 @@ func unsetEmptyEnvVars() {
}
}
+func isTestProcess(arguments []string) bool {
+ if len(arguments) == 0 {
+ return false
+ }
+
+ executableName := filepath.Base(arguments[0])
+ return strings.HasSuffix(executableName, ".test") ||
+ strings.HasSuffix(executableName, ".test.exe") ||
+ executableName == "cleanup_test_db" ||
+ executableName == "cleanup_test_db.exe"
+}
+
// slotLockConn holds the system-DB connection whose session owns this worker's
// advisory lock. It must live for the whole process: closing it (or letting it
// be garbage-collected) releases the lock and frees the slot for another worker
diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go
new file mode 100644
index 00000000..8ac24349
--- /dev/null
+++ b/backend/internal/config/config_test.go
@@ -0,0 +1,53 @@
+package config
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func Test_IsTestProcess_UsesExecutableNameOnly(t *testing.T) {
+ testCases := []struct {
+ name string
+ arguments []string
+ isTesting bool
+ }{
+ {
+ name: "Go test binary",
+ arguments: []string{"/tmp/config.test", "-test.v"},
+ isTesting: true,
+ },
+ {
+ name: "Windows Go test binary",
+ arguments: []string{`C:\\Temp\\config.test.exe`, "-test.v"},
+ isTesting: true,
+ },
+ {
+ name: "database cleanup command",
+ arguments: []string{"/tmp/cleanup_test_db"},
+ isTesting: true,
+ },
+ {
+ name: "storage command",
+ arguments: []string{"/app/databasus", "--test-storage"},
+ isTesting: false,
+ },
+ {
+ name: "unrelated argument containing test",
+ arguments: []string{"/app/databasus", "contest"},
+ isTesting: false,
+ },
+ {
+ name: "missing executable",
+ arguments: nil,
+ isTesting: false,
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ isTesting := isTestProcess(testCase.arguments)
+ assert.Equal(t, testCase.isTesting, isTesting)
+ })
+ }
+}
diff --git a/deploy/helm/README.md b/deploy/helm/README.md
index fa085791..f9c60115 100644
--- a/deploy/helm/README.md
+++ b/deploy/helm/README.md
@@ -374,6 +374,11 @@ The app does **not** automount the ServiceAccount token by default
A restricted-PSS values example wiring seccomp, no privilege escalation, AppArmor,
a dedicated ServiceAccount and a read-only root filesystem:
+Databasus, PostgreSQL and Valkey run under one non-root operating-system account
+named `databasus`. The image normally selects the numeric IDs from mounted data
+and falls back to `999:999`. If the volume requires different IDs, set `PUID`
+and `PGID` through `extraEnv`.
+
```yaml
# hardened-values.yaml
serviceAccount:
@@ -414,10 +419,10 @@ extraVolumeMounts:
```
> **Not supported by design:** `runAsNonRoot: true` and dropping **all**
-> capabilities. The entrypoint must start as root to remap service accounts,
-> volume `chown` and PostgreSQL `initdb`, then drops to a non-root user with
-> `gosu` (which requires `SETUID`/`SETGID`). See the note in `values.yaml`
-> next to `podSecurityContext`.
+> capabilities. The entrypoint must start as root to remap the `databasus`
+> account, attempt volume `chown` and run PostgreSQL `initdb`, then drops to
+> that account with `gosu` (which requires `SETUID`/`SETGID`). See the note in
+> `values.yaml` next to `podSecurityContext`.
## Upgrade
diff --git a/deploy/helm/values.yaml b/deploy/helm/values.yaml
index e908ad22..efce0065 100644
--- a/deploy/helm/values.yaml
+++ b/deploy/helm/values.yaml
@@ -77,8 +77,9 @@ service:
headless:
enabled: true
# Security context for the pod (e.g. fsGroup for volume permissions)
-# NOTE: The entrypoint runs as root to bootstrap PostgreSQL and Valkey,
-# then drops privileges to a non-root user via gosu. Do not set
+# NOTE: The entrypoint runs as root to select PUID/PGID, prepare volumes and
+# bootstrap PostgreSQL. Databasus, PostgreSQL and Valkey then run as the same
+# non-root `databasus` account through gosu. Do not set
# runAsNonRoot or runAsUser here -- it will prevent the container from starting.
podSecurityContext: {}
diff --git a/docker/start.sh b/docker/start.sh
new file mode 100755
index 00000000..eb89a5ae
--- /dev/null
+++ b/docker/start.sh
@@ -0,0 +1,627 @@
+#!/bin/bash
+set -e
+
+export TMPDIR=/tmp
+
+readonly permissions_documentation_url="https://databasus.com/advanced-config/#docker-storage-permissions"
+readonly postgres_binary_directory="/usr/lib/postgresql/17/bin"
+
+runtime_uid=""
+runtime_gid=""
+postgres_pid=""
+internal_postgres_password=""
+
+reject_legacy_postgresus_volume() {
+ if [ ! -d /postgresus-data ] || [ -z "$(ls -A /postgresus-data 2>/dev/null)" ]; then
+ return
+ fi
+
+ echo ""
+ echo "=========================================="
+ echo "ERROR: Legacy volume detected!"
+ echo "=========================================="
+ echo ""
+ echo "You are using the /postgresus-data folder. It seems you changed the image name from Postgresus to Databasus without changing the volume."
+ echo ""
+ echo "Please either:"
+ echo " 1. Switch back to image rostislavdugin/postgresus:latest (supported until ~Dec 2026)"
+ echo " 2. Read the migration guide: https://databasus.com/installation/#postgresus-migration"
+ echo ""
+ echo "=========================================="
+ exit 1
+}
+
+report_identity_error() {
+ local variable_name="$1"
+ local variable_value="$2"
+
+ echo "ERROR: ${variable_name} must be a non-zero decimal Linux ID no greater than 4294967294. Received: '${variable_value}'." >&2
+ echo "See ${permissions_documentation_url}" >&2
+ exit 1
+}
+
+validate_linux_id() {
+ local variable_name="$1"
+ local variable_value="$2"
+ local maximum_linux_id=4294967294
+ local normalized_id
+
+ if [[ ! "${variable_value}" =~ ^[0-9]+$ ]]; then
+ report_identity_error "${variable_name}" "${variable_value}"
+ fi
+
+ normalized_id="${variable_value#"${variable_value%%[!0]*}"}"
+ normalized_id="${normalized_id:-0}"
+ if [ "${normalized_id}" = "0" ] ||
+ ((${#normalized_id} > ${#maximum_linux_id})) ||
+ { ((${#normalized_id} == ${#maximum_linux_id})) && ((10#${normalized_id} > maximum_linux_id)); }; then
+ report_identity_error "${variable_name}" "${variable_value}"
+ fi
+
+ echo "${normalized_id}"
+}
+
+get_mounted_id() {
+ local stat_format="$1"
+ local mounted_path
+ local mounted_id
+ local -a mounted_paths=()
+
+ if [ -d /databasus-data/pgdata ]; then
+ mounted_paths+=(/databasus-data/pgdata)
+ fi
+ mounted_paths+=(/databasus-data/backups /databasus-data)
+
+ for mounted_path in "${mounted_paths[@]}"; do
+ if [ ! -e "${mounted_path}" ]; then
+ continue
+ fi
+
+ mounted_id="$(stat -c "${stat_format}" "${mounted_path}")"
+ if [ "${mounted_id}" != "0" ]; then
+ echo "${mounted_id}"
+ return
+ fi
+ done
+
+ echo 999
+}
+
+resolve_runtime_id() {
+ local variable_name="$1"
+ local stat_format="$2"
+ local variable_value
+
+ if [ "${!variable_name+x}" = "x" ]; then
+ variable_value="${!variable_name}"
+ validate_linux_id "${variable_name}" "${variable_value}"
+ return
+ fi
+
+ get_mounted_id "${stat_format}"
+}
+
+ensure_id_is_available() {
+ local account_database="$1"
+ local identity_kind="$2"
+ local selected_id="$3"
+ local owning_name
+
+ owning_name="$(getent "${account_database}" "${selected_id}" | cut -d: -f1 || true)"
+ if [ -z "${owning_name}" ] || [ "${owning_name}" = "databasus" ]; then
+ return
+ fi
+
+ echo "ERROR: Selected ${identity_kind} ${selected_id} belongs to account '${owning_name}', not 'databasus'." >&2
+ echo "Set PUID and PGID to unused IDs or fix the mounted directory ownership:" >&2
+ echo "${permissions_documentation_url}" >&2
+ exit 1
+}
+
+configure_runtime_identity() {
+ runtime_uid="$(resolve_runtime_id PUID %u)"
+ runtime_gid="$(resolve_runtime_id PGID %g)"
+
+ ensure_id_is_available passwd UID "${runtime_uid}"
+ ensure_id_is_available group GID "${runtime_gid}"
+
+ if [ "$(id -g databasus)" != "${runtime_gid}" ]; then
+ groupmod -g "${runtime_gid}" databasus
+ fi
+ if [ "$(id -u databasus)" != "${runtime_uid}" ]; then
+ usermod -u "${runtime_uid}" databasus
+ fi
+
+ echo "Using databasus runtime identity ${runtime_uid}:${runtime_gid}."
+}
+
+generate_frontend_runtime_configuration() {
+ local is_email_configured=false
+
+ if [ -n "${SMTP_HOST:-}" ] && [ -n "${DATABASUS_URL:-}" ]; then
+ is_email_configured=true
+ fi
+
+ echo "Generating runtime configuration..."
+ cat > /app/ui/build/runtime-config.js <<JSEOF
+// Runtime configuration injected at container startup
+// This file is generated dynamically and should not be edited manually
+window.__RUNTIME_CONFIG__ = {
+ GITHUB_CLIENT_ID: '${GITHUB_CLIENT_ID:-}',
+ GOOGLE_CLIENT_ID: '${GOOGLE_CLIENT_ID:-}',
+ IS_EMAIL_CONFIGURED: '${is_email_configured}',
+ CLOUDFLARE_TURNSTILE_SITE_KEY: '${CLOUDFLARE_TURNSTILE_SITE_KEY:-}',
+ CONTAINER_ARCH: '${CONTAINER_ARCH:-unknown}'
+};
+JSEOF
+
+ if [ -n "${ANALYTICS_SCRIPT:-}" ] &&
+ ! grep -q "rybbit.databasus.com" /app/ui/build/index.html 2>/dev/null; then
+ echo "Injecting analytics script..."
+ sed -i "s#</head># ${ANALYTICS_SCRIPT}\
+ </head>#" /app/ui/build/index.html
+ fi
+}
+
+report_storage_error() {
+ local storage_path="$1"
+ local required_operation="$2"
+
+ echo "ERROR: Databasus cannot write to ${storage_path} as UID ${runtime_uid} and GID ${runtime_gid}." >&2
+ echo "Required operation: ${required_operation}." >&2
+ echo "Set PUID and PGID or fix the mounted directory permissions:" >&2
+ echo "${permissions_documentation_url}" >&2
+ return 1
+}
+
+create_required_data_directories() {
+ local required_directory
+
+ for required_directory in \
+ /databasus-data \
+ /databasus-data/pgdata \
+ /databasus-data/pgsocket \
+ /databasus-data/temp \
+ /databasus-data/backups; do
+ if mkdir -p "${required_directory}" 2>/dev/null ||
+ gosu databasus mkdir -p "${required_directory}"; then
+ continue
+ fi
+
+ report_storage_error "${required_directory}" "create the directory"
+ return 1
+ done
+}
+
+normalize_data_permissions() {
+ chown "${runtime_uid}:${runtime_gid}" /databasus-data 2>/dev/null || true
+ chmod 0770 /databasus-data 2>/dev/null || true
+ chown "${runtime_uid}:${runtime_gid}" \
+ /databasus-data/pgdata \
+ /databasus-data/pgsocket \
+ /databasus-data/temp \
+ /databasus-data/backups 2>/dev/null || true
+ chmod 0700 \
+ /databasus-data/pgdata \
+ /databasus-data/pgsocket \
+ /databasus-data/temp 2>/dev/null || true
+ chmod 0770 /databasus-data/backups 2>/dev/null || true
+}
+
+can_read_and_open_file_for_writing() {
+ local checked_file="$1"
+
+ gosu databasus test -r "${checked_file}" &&
+ gosu databasus tee -a "${checked_file}" </dev/null >/dev/null
+}
+
+verify_existing_data_files() {
+ local existing_data_file
+
+ for existing_data_file in \
+ /databasus-data/secret.key \
+ /databasus-data/instance.json \
+ /databasus-data/databasus.log; do
+ if [ ! -e "${existing_data_file}" ]; then
+ continue
+ fi
+
+ chown "${runtime_uid}:${runtime_gid}" "${existing_data_file}" 2>/dev/null || true
+ chmod 0600 "${existing_data_file}" 2>/dev/null || true
+
+ if can_read_and_open_file_for_writing "${existing_data_file}"; then
+ continue
+ fi
+
+ report_storage_error "${existing_data_file}" "read and open the existing file for writing"
+ return 1
+ done
+}
+
+verify_directory_file_lifecycle() {
+ local checked_directory="$1"
+ local probe_path="${checked_directory}/.databasus-required-write-check-$$-$RANDOM"
+ local probe_content="$2"
+ local persisted_probe_content
+
+ if ! printf "%s" "${probe_content}" |
+ gosu databasus tee "${probe_path}" >/dev/null; then
+ gosu databasus rm -f "${probe_path}" 2>/dev/null || true
+ return 1
+ fi
+
+ persisted_probe_content="$(gosu databasus cat "${probe_path}" 2>/dev/null || true)"
+ if [ "${persisted_probe_content}" != "${probe_content}" ]; then
+ gosu databasus rm -f "${probe_path}" 2>/dev/null || true
+ return 1
+ fi
+
+ gosu databasus rm "${probe_path}"
+}
+
+verify_wal_queue_access() {
+ local wal_queue_directory=/databasus-data/backups/wal-queue
+ local queue_listing
+ local queue_directory
+ local queue_file
+ local inaccessible_queue_directory=""
+ local inaccessible_queue_file=""
+
+ if [ ! -d "${wal_queue_directory}" ]; then
+ return
+ fi
+
+ chown -R "${runtime_uid}:${runtime_gid}" "${wal_queue_directory}" 2>/dev/null || true
+ chmod -R u+rwX "${wal_queue_directory}" 2>/dev/null || true
+
+ queue_listing="$(mktemp)"
+ if ! gosu databasus find "${wal_queue_directory}" -type d -print0 > "${queue_listing}"; then
+ rm -f "${queue_listing}"
+ report_storage_error "${wal_queue_directory}" "traverse the existing WAL queue"
+ return 1
+ fi
+
+ while IFS= read -r -d "" queue_directory; do
+ if verify_directory_file_lifecycle "${queue_directory}" queue-check; then
+ continue
+ fi
+
+ inaccessible_queue_directory="${queue_directory}"
+ break
+ done < "${queue_listing}"
+ if [ -n "${inaccessible_queue_directory}" ]; then
+ rm -f "${queue_listing}"
+ report_storage_error "${inaccessible_queue_directory}" "create, read, and remove a WAL queue file"
+ return 1
+ fi
+
+ if ! gosu databasus find "${wal_queue_directory}" -type f -print0 > "${queue_listing}"; then
+ rm -f "${queue_listing}"
+ report_storage_error "${wal_queue_directory}" "traverse the existing WAL queue"
+ return 1
+ fi
+
+ while IFS= read -r -d "" queue_file; do
+ if can_read_and_open_file_for_writing "${queue_file}"; then
+ continue
+ fi
+
+ inaccessible_queue_file="${queue_file}"
+ break
+ done < "${queue_listing}"
+ if [ -n "${inaccessible_queue_file}" ]; then
+ rm -f "${queue_listing}"
+ report_storage_error "${inaccessible_queue_file}" "read and open the existing WAL queue file for writing"
+ return 1
+ fi
+
+ rm -f "${queue_listing}"
+}
+
+verify_service_directories() {
+ local required_write_directory
+
+ for required_write_directory in \
+ /databasus-data \
+ /databasus-data/pgdata \
+ /databasus-data/pgsocket; do
+ if verify_directory_file_lifecycle "${required_write_directory}" service-check; then
+ continue
+ fi
+
+ report_storage_error "${required_write_directory}" "create, read, and remove a required file"
+ return 1
+ done
+}
+
+prepare_and_verify_storage() {
+ echo "Setting up data directory permissions..."
+
+ create_required_data_directories
+ normalize_data_permissions
+ verify_existing_data_files
+ verify_wal_queue_access
+ verify_service_directories
+ gosu databasus /app/main --test-storage
+}
+
+configure_and_start_valkey() {
+ echo "Configuring Valkey cache..."
+ cat > /tmp/valkey.conf <<'VALKEY_CONFIG'
+port 6379
+bind 127.0.0.1
+protected-mode yes
+save ""
+maxmemory 256mb
+maxmemory-policy allkeys-lru
+VALKEY_CONFIG
+
+ echo "Starting Valkey..."
+ gosu databasus valkey-server /tmp/valkey.conf &
+
+ echo "Waiting for Valkey to be ready..."
+ local valkey_readiness_attempt
+ for ((valkey_readiness_attempt = 1; valkey_readiness_attempt <= 30; valkey_readiness_attempt++)); do
+ if gosu databasus valkey-cli ping >/dev/null 2>&1; then
+ echo "Valkey is ready!"
+ return
+ fi
+ sleep 1
+ done
+
+ echo "ERROR: Valkey did not become ready." >&2
+ return 1
+}
+
+initialize_postgresql_cluster() {
+ if [ -s /databasus-data/pgdata/PG_VERSION ]; then
+ return
+ fi
+
+ echo "Initializing PostgreSQL database..."
+ gosu databasus "${postgres_binary_directory}/initdb" \
+ -D /databasus-data/pgdata \
+ --encoding=UTF8 \
+ --locale=C.UTF-8 \
+ --username=postgres
+
+ {
+ echo "port = 5437"
+ echo "listen_addresses = 'localhost'"
+ echo "shared_buffers = 256MB"
+ echo "max_connections = 100"
+ } >> /databasus-data/pgdata/postgresql.conf
+}
+
+write_bootstrap_postgresql_authentication() {
+ gosu databasus tee /databasus-data/pgdata/pg_ident.conf.new >/dev/null <<'PG_IDENT'
+databasus_bootstrap databasus postgres
+PG_IDENT
+ gosu databasus chmod 0600 /databasus-data/pgdata/pg_ident.conf.new
+ gosu databasus mv \
+ /databasus-data/pgdata/pg_ident.conf.new \
+ /databasus-data/pgdata/pg_ident.conf
+
+ gosu databasus tee /databasus-data/pgdata/pg_hba.conf.new >/dev/null <<'PG_HBA'
+local all postgres peer map=databasus_bootstrap
+local all all reject
+local replication all reject
+host all all 127.0.0.1/32 scram-sha-256
+host all all ::1/128 scram-sha-256
+host replication all 127.0.0.1/32 reject
+host replication all ::1/128 reject
+PG_HBA
+ gosu databasus chmod 0600 /databasus-data/pgdata/pg_hba.conf.new
+ gosu databasus mv \
+ /databasus-data/pgdata/pg_hba.conf.new \
+ /databasus-data/pgdata/pg_hba.conf
+}
+
+start_postgresql() {
+ echo "Starting PostgreSQL..."
+ gosu databasus "${postgres_binary_directory}/postgres" \
+ -D /databasus-data/pgdata \
+ -p 5437 \
+ -k /databasus-data/pgsocket \
+ -c password_encryption=scram-sha-256 &
+ postgres_pid=$!
+
+ echo "Waiting for PostgreSQL to be ready..."
+ local postgres_readiness_attempt
+ for ((postgres_readiness_attempt = 1; postgres_readiness_attempt <= 30; postgres_readiness_attempt++)); do
+ if gosu databasus "${postgres_binary_directory}/pg_isready" \
+ -p 5437 -h /databasus-data/pgsocket >/dev/null 2>&1; then
+ echo "PostgreSQL is ready!"
+ return
+ fi
+ sleep 1
+ done
+
+ return 1
+}
+
+report_postgresql_recovery_failure() {
+ echo ""
+ echo "=========================================="
+ echo "ERROR: PostgreSQL failed to start even after WAL reset."
+ echo "The database may be severely corrupted."
+ echo ""
+ echo "Options:"
+ echo " 1. Delete the volume and start fresh (data loss)"
+ echo " 2. Manually inspect /databasus-data/pgdata for issues"
+ echo "=========================================="
+ return 1
+}
+
+start_postgresql_with_recovery() {
+ if start_postgresql; then
+ return
+ fi
+
+ echo ""
+ echo "=========================================="
+ echo "PostgreSQL failed to start. Attempting WAL reset recovery..."
+ echo "=========================================="
+ echo ""
+
+ kill -9 "${postgres_pid}" 2>/dev/null || true
+ sleep 2
+
+ echo "Running pg_resetwal to reset WAL..."
+ if ! gosu databasus "${postgres_binary_directory}/pg_resetwal" \
+ -f /databasus-data/pgdata; then
+ echo ""
+ echo "=========================================="
+ echo "ERROR: pg_resetwal failed."
+ echo "The database may be severely corrupted."
+ echo ""
+ echo "Options:"
+ echo " 1. Delete the volume and start fresh (data loss)"
+ echo " 2. Manually inspect /databasus-data/pgdata for issues"
+ echo "=========================================="
+ return 1
+ fi
+
+ echo "WAL reset successful. Restarting PostgreSQL..."
+ if ! start_postgresql; then
+ report_postgresql_recovery_failure
+ return 1
+ fi
+
+ echo "PostgreSQL recovered successfully after WAL reset!"
+}
+
+configure_postgresql_database() {
+ internal_postgres_password="$(od -An -N32 -tx1 /dev/urandom | tr -d '[:space:]')"
+
+ echo "Setting up database and user..."
+ gosu databasus "${postgres_binary_directory}/psql" \
+ -v ON_ERROR_STOP=1 \
+ -v internal_postgres_password="${internal_postgres_password}" \
+ -p 5437 \
+ -h /databasus-data/pgsocket \
+ -U postgres \
+ -d postgres <<'SQL'
+
+ALTER USER postgres WITH PASSWORD :'internal_postgres_password';
+SELECT 'CREATE DATABASE databasus OWNER postgres'
+WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'databasus')
+\gexec
+\q
+SQL
+}
+
+activate_runtime_postgresql_authentication() {
+ gosu databasus tee /databasus-data/pgdata/pg_hba.conf.new >/dev/null <<'PG_HBA'
+local all all reject
+local replication all reject
+host all all 127.0.0.1/32 scram-sha-256
+host all all ::1/128 scram-sha-256
+host replication all 127.0.0.1/32 reject
+host replication all ::1/128 reject
+PG_HBA
+ gosu databasus chmod 0600 /databasus-data/pgdata/pg_hba.conf.new
+ gosu databasus mv \
+ /databasus-data/pgdata/pg_hba.conf.new \
+ /databasus-data/pgdata/pg_hba.conf
+ gosu databasus /bin/sh -c ': > /databasus-data/pgdata/pg_ident.conf'
+ gosu databasus chmod 0600 /databasus-data/pgdata/pg_ident.conf
+ gosu databasus "${postgres_binary_directory}/pg_ctl" \
+ -D /databasus-data/pgdata reload
+}
+
+verify_postgresql_runtime_authentication() {
+ if gosu databasus "${postgres_binary_directory}/psql" \
+ -p 5437 \
+ -h /databasus-data/pgsocket \
+ -U postgres \
+ -d postgres \
+ -c 'SELECT 1' >/dev/null 2>&1; then
+ echo "ERROR: Embedded PostgreSQL still accepts Unix-socket login after bootstrap." >&2
+ return 1
+ fi
+
+ if ! gosu databasus env PGPASSWORD="${internal_postgres_password}" \
+ "${postgres_binary_directory}/psql" \
+ -h localhost \
+ -p 5437 \
+ -U postgres \
+ -d postgres \
+ -c 'SELECT 1' >/dev/null; then
+ echo "ERROR: Embedded PostgreSQL rejected its generated loopback credential." >&2
+ return 1
+ fi
+}
+
+configure_application_database_dsn() {
+ if [ -n "${DATABASE_DSN+x}" ]; then
+ return
+ fi
+
+ export DATABASE_DSN="host=localhost user=postgres password=${internal_postgres_password} dbname=databasus port=5437 sslmode=disable"
+}
+
+bootstrap_postgresql() {
+ initialize_postgresql_cluster
+ write_bootstrap_postgresql_authentication
+ start_postgresql_with_recovery
+ configure_postgresql_database
+ activate_runtime_postgresql_authentication
+ verify_postgresql_runtime_authentication
+ configure_application_database_dsn
+}
+
+reject_legacy_wal_configuration() {
+ local has_backup_type_column
+ local has_legacy_wal_database
+
+ echo "Checking for legacy WAL backup configuration..."
+ has_backup_type_column="$(gosu databasus env PGPASSWORD="${internal_postgres_password}" \
+ "${postgres_binary_directory}/psql" \
+ -h localhost -p 5437 -U postgres -d databasus -tA \
+ -c "SELECT 1 FROM information_schema.columns WHERE table_name='postgresql_databases' AND column_name='backup_type' LIMIT 1" \
+ 2>/dev/null || true)"
+
+ if [ "${has_backup_type_column}" != "1" ]; then
+ echo "No legacy WAL backup data detected."
+ return
+ fi
+
+ has_legacy_wal_database="$(gosu databasus env PGPASSWORD="${internal_postgres_password}" \
+ "${postgres_binary_directory}/psql" \
+ -h localhost -p 5437 -U postgres -d databasus -tA \
+ -c "SELECT 1 FROM postgresql_databases WHERE backup_type='WAL_V1' LIMIT 1" \
+ 2>/dev/null || true)"
+
+ if [ "${has_legacy_wal_database}" != "1" ]; then
+ echo "No legacy WAL backup data detected."
+ return
+ fi
+
+ echo ""
+ echo "=========================================="
+ echo "ERROR: Agent (WAL_V1) backup approach is no longer supported."
+ echo "=========================================="
+ echo ""
+ echo "Please downgrade to version 3.42.0, remove all WAL-mode databases"
+ echo "manually and then upgrade again. This safeguard exists to avoid"
+ echo "corrupting already-set-up agents."
+ echo ""
+ echo "=========================================="
+ return 1
+}
+
+main() {
+ reject_legacy_postgresus_volume
+ configure_runtime_identity
+ generate_frontend_runtime_configuration
+ configure_and_start_valkey
+ prepare_and_verify_storage
+ bootstrap_postgresql
+ reject_legacy_wal_configuration
+
+ echo "Starting Databasus application..."
+ exec gosu databasus ./main
+}
+
+main "$@"
diff --git a/e2e/docker-storage/run.sh b/e2e/docker-storage/run.sh
index b43c10f8..b2a0ae2e 100755
--- a/e2e/docker-storage/run.sh
+++ b/e2e/docker-storage/run.sh
@@ -32,7 +32,7 @@ cleanup() {
done < <(docker ps -a --filter "label=${harness_label}" --format '{{.ID}} {{.Names}}' 2>/dev/null)
if (("${#client_container_ids[@]}")); then
- docker rm -f "${client_container_ids[@]}" >/dev/null 2>&1 || true
+ docker rm -fv "${client_container_ids[@]}" >/dev/null 2>&1 || true
fi
mapfile -t volume_names < <(docker volume ls -q --filter "label=${harness_label}" 2>/dev/null)
@@ -44,7 +44,7 @@ cleanup() {
done
if (("${#server_container_ids[@]}")); then
- docker rm -f "${server_container_ids[@]}" >/dev/null 2>&1 || true
+ docker rm -fv "${server_container_ids[@]}" >/dev/null 2>&1 || true
fi
mapfile -t network_ids < <(docker network ls -q --filter "label=${harness_label}" 2>/dev/null)
@@ -72,7 +72,7 @@ wait_for_health() {
local container_name="$1"
local health_status
- for ((readiness_attempt = 1; readiness_attempt <= 90; readiness_attempt++)); do
+ for ((readiness_attempt = 1; readiness_attempt <= 120; readiness_attempt++)); do
health_status="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "${container_name}")"
if [[ "${health_status}" == "healthy" ]]; then
return
@@ -127,72 +127,162 @@ start_databasus() {
docker run --detach \
--name "${container_name}" \
--label "${harness_label}" \
+ --health-interval 1s \
+ --health-start-period 1s \
"$@" \
"${databasus_image}" >/dev/null
wait_for_health "${container_name}"
}
-probe_path() {
+start_failing_databasus() {
+ local container_name="$1"
+ shift
+
+ docker run --detach \
+ --name "${container_name}" \
+ --label "${harness_label}" \
+ "$@" \
+ "${databasus_image}" >/dev/null
+ wait_for_exit "${container_name}"
+}
+
+assert_storage_permission_failure() {
+ local container_name="$1"
+ local container_logs
+
+ container_logs="$(docker logs "${container_name}" 2>&1)"
+ grep -Eq 'ERROR: Databasus cannot write to .+ as UID [0-9]+ and GID [0-9]+\.' <<<"${container_logs}"
+ grep -Fq "Required operation:" <<<"${container_logs}"
+ grep -Fq "Set PUID and PGID or fix the mounted directory permissions:" <<<"${container_logs}"
+ grep -Fq "https://databasus.com/advanced-config/#docker-storage-permissions" <<<"${container_logs}"
+ grep -Fq "Valkey is ready!" <<<"${container_logs}"
+ ! grep -Fq "Starting PostgreSQL..." <<<"${container_logs}"
+ ! grep -Fq "Starting Databasus application..." <<<"${container_logs}"
+ assert_no_storage_probe_remains "${container_name}"
+}
+
+assert_no_storage_probe_remains() {
+ local container_name="$1"
+ local remaining_probe
+
+ remaining_probe="$(docker run --rm \
+ --label "${harness_label}" \
+ --volumes-from "${container_name}" \
+ --entrypoint /bin/sh \
+ "${databasus_image}" \
+ -c 'find /databasus-data/temp /databasus-data/backups \
+ -type f -name ".databasus-storage-test-*" -print -quit 2>/dev/null || true')"
+ if [ -n "${remaining_probe}" ]; then
+ echo "Storage probe remains after failed startup: ${remaining_probe}" >&2
+ return 1
+ fi
+}
+
+assert_storage_command_saves_and_deletes_probe() {
local container_name="$1"
- local account_name="$2"
- local mounted_path="$3"
- docker exec --user "${account_name}" "${container_name}" /bin/sh -eu -c '
- probe_path="$1/.databasus-filesystem-probe-$$"
- printf filesystem-probe > "$probe_path"
- [ "$(cat "$probe_path")" = filesystem-probe ]
- rm "$probe_path"
- [ ! -e "$probe_path" ]
- ' sh "${mounted_path}"
+ docker exec --user databasus "${container_name}" \
+ databasus --test-storage 2>&1 | grep -Fxq "storage test passed"
+}
+
+assert_single_runtime_identity() {
+ local container_name="$1"
+ local runtime_gid
+ local runtime_uid
+ local service_name
+ local service_pid
+
+ runtime_uid="$(docker exec "${container_name}" id -u databasus)"
+ runtime_gid="$(docker exec "${container_name}" id -g databasus)"
+ [[ "${runtime_uid}" != "0" ]]
+ [[ "${runtime_gid}" != "0" ]]
+
+ if docker exec "${container_name}" id postgres >/dev/null 2>&1; then
+ echo "The image still contains a postgres operating-system account" >&2
+ return 1
+ fi
+
+ [[ "$(docker exec "${container_name}" stat -c %u /proc/1)" == "${runtime_uid}" ]]
+ [[ "$(docker exec "${container_name}" stat -c %g /proc/1)" == "${runtime_gid}" ]]
+
+ for service_name in postgres valkey-server; do
+ service_pid="$(docker exec "${container_name}" /bin/sh -eu -c '
+ pidof "$1" | cut -d" " -f1
+ ' sh "${service_name}")"
+ [[ "$(docker exec "${container_name}" stat -c %u "/proc/${service_pid}")" == "${runtime_uid}" ]]
+ [[ "$(docker exec "${container_name}" stat -c %g "/proc/${service_pid}")" == "${runtime_gid}" ]]
+ done
}
-assert_service_boundaries() {
+assert_postgresql_runtime_authentication() {
local container_name="$1"
- docker exec --user databasus "${container_name}" test ! -r /databasus-data/pgdata/PG_VERSION
- docker exec --user databasus "${container_name}" test ! -x /databasus-data/pgsocket
+ grep -Fxq "local all all reject" < <(
+ docker exec "${container_name}" cat /databasus-data/pgdata/pg_hba.conf
+ )
+ [[ "$(docker exec "${container_name}" stat -c %a /databasus-data/pgdata/pg_hba.conf)" == "600" ]]
+ [[ "$(docker exec "${container_name}" stat -c %a /databasus-data/pgdata/pg_ident.conf)" == "600" ]]
+
+ if docker exec --user databasus "${container_name}" \
+ /usr/lib/postgresql/17/bin/psql \
+ -h /databasus-data/pgsocket -p 5437 -U postgres -d postgres \
+ -c 'SELECT 1' >/dev/null 2>&1; then
+ echo "PostgreSQL accepted a runtime Unix-socket login" >&2
+ return 1
+ fi
+
+ if docker exec --user databasus "${container_name}" \
+ env -u PGPASSWORD /usr/lib/postgresql/17/bin/psql \
+ -h localhost -p 5437 -U postgres -d postgres \
+ -c 'SELECT 1' >/dev/null 2>&1; then
+ echo "PostgreSQL accepted a loopback login without its generated password" >&2
+ return 1
+ fi
}
-probe_service_paths() {
+assert_running_container() {
local container_name="$1"
- probe_path "${container_name}" databasus /databasus-data/temp
- probe_path "${container_name}" databasus /databasus-data/backups
- probe_path "${container_name}" postgres /databasus-data/pgdata
- assert_service_boundaries "${container_name}"
+ assert_storage_command_saves_and_deletes_probe "${container_name}"
+ assert_single_runtime_identity "${container_name}"
+ assert_postgresql_runtime_authentication "${container_name}"
+}
+
+prepare_bind_tree() {
+ local data_root="$1"
+ local data_uid="$2"
+ local data_gid="$3"
+ local backup_uid="${4:-${data_uid}}"
+ local backup_gid="${5:-${data_gid}}"
+
+ mkdir -p "${data_root}"
+ docker run --rm --label "${harness_label}" --entrypoint /bin/sh \
+ --volume "${data_root}:/data" "${databasus_image}" -eu -c '
+ mkdir -p /data/pgdata /data/pgsocket /data/temp /data/backups
+ chown "$1:$2" /data /data/pgdata /data/pgsocket /data/temp
+ chown "$3:$4" /data/backups
+ chmod 0770 /data /data/backups
+ chmod 0700 /data/pgdata /data/pgsocket /data/temp
+ ' sh "${data_uid}" "${data_gid}" "${backup_uid}" "${backup_gid}"
}
run_default_ids() {
local container_name="databasus-storage-default-ids-${run_id}"
local volume_name="databasus-storage-default-ids-${run_id}"
- local rejected_remap_command="${case_root}/reject-identity-remap"
local image_environment
- local container_environment
- local identity_setting
image_environment="$(docker image inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "${databasus_image}")"
- for identity_setting in DATABASUS_PUID=65532 DATABASUS_PGID=65532 POSTGRES_PUID=999 POSTGRES_PGID=999; do
- grep -Fxq "${identity_setting}" <<<"${image_environment}"
- done
+ if grep -Eq '^(PUID|PGID|DATABASUS_PUID|DATABASUS_PGID|POSTGRES_PUID|POSTGRES_PGID)=' <<<"${image_environment}"; then
+ echo "The image publishes a runtime identity default" >&2
+ return 1
+ fi
- printf '#!/bin/sh\nexit 1\n' > "${rejected_remap_command}"
- chmod 0755 "${rejected_remap_command}"
docker volume create --label "${harness_label}" "${volume_name}" >/dev/null
- start_databasus "${container_name}" \
- --mount "type=bind,source=${rejected_remap_command},target=/usr/sbin/groupmod,readonly" \
- --mount "type=bind,source=${rejected_remap_command},target=/usr/sbin/usermod,readonly" \
- --volume "${volume_name}:/databasus-data"
-
- container_environment="$(docker exec "${container_name}" env)"
- for identity_setting in DATABASUS_PUID=65532 DATABASUS_PGID=65532 POSTGRES_PUID=999 POSTGRES_PGID=999; do
- grep -Fxq "${identity_setting}" <<<"${container_environment}"
- done
+ start_databasus "${container_name}" --volume "${volume_name}:/databasus-data"
- [[ "$(docker exec "${container_name}" id -u databasus)" == "65532" ]]
- [[ "$(docker exec "${container_name}" id -g databasus)" == "65532" ]]
- [[ "$(docker exec "${container_name}" id -u postgres)" == "999" ]]
- [[ "$(docker exec "${container_name}" id -g postgres)" == "999" ]]
- probe_service_paths "${container_name}"
+ [[ "$(docker exec "${container_name}" id -u databasus)" == "999" ]]
+ [[ "$(docker exec "${container_name}" id -g databasus)" == "999" ]]
+ assert_running_container "${container_name}"
}
run_custom_ids() {
@@ -201,27 +291,98 @@ run_custom_ids() {
docker volume create --label "${harness_label}" "${volume_name}" >/dev/null
start_databasus "${container_name}" \
- --env DATABASUS_PUID=25001 \
- --env DATABASUS_PGID=25002 \
- --env POSTGRES_PUID=26001 \
- --env POSTGRES_PGID=26002 \
+ --env PUID=25001 \
+ --env PGID=25002 \
--volume "${volume_name}:/databasus-data"
[[ "$(docker exec "${container_name}" id -u databasus)" == "25001" ]]
[[ "$(docker exec "${container_name}" id -g databasus)" == "25002" ]]
- [[ "$(docker exec "${container_name}" id -u postgres)" == "26001" ]]
- [[ "$(docker exec "${container_name}" id -g postgres)" == "26002" ]]
- probe_service_paths "${container_name}"
+ assert_running_container "${container_name}"
+}
+
+run_maximum_ids() {
+ local container_name="databasus-storage-maximum-ids-${run_id}"
+ local volume_name="databasus-storage-maximum-ids-${run_id}"
+
+ docker volume create --label "${harness_label}" "${volume_name}" >/dev/null
+ start_databasus "${container_name}" \
+ --env PUID=4294967294 \
+ --env PGID=4294967294 \
+ --volume "${volume_name}:/databasus-data"
+
+ [[ "$(docker exec "${container_name}" id -u databasus)" == "4294967294" ]]
+ [[ "$(docker exec "${container_name}" id -g databasus)" == "4294967294" ]]
+ assert_running_container "${container_name}"
+}
+
+run_automatic_ids() {
+ local container_name="databasus-storage-automatic-ids-${run_id}"
+ local data_root="${case_root}/automatic-ids"
+
+ prepare_bind_tree "${data_root}" 27501 27502
+ start_databasus "${container_name}" --volume "${data_root}:/databasus-data"
+
+ [[ "$(docker exec "${container_name}" id -u databasus)" == "27501" ]]
+ [[ "$(docker exec "${container_name}" id -g databasus)" == "27502" ]]
+ assert_running_container "${container_name}"
+}
+
+run_empty_pgdata_ids() {
+ local container_name="databasus-storage-empty-pgdata-ids-${run_id}"
+ local data_volume_name="databasus-storage-empty-pgdata-data-${run_id}"
+ local pgdata_volume_name="databasus-storage-empty-pgdata-${run_id}"
+
+ docker volume create --label "${harness_label}" "${data_volume_name}" >/dev/null
+ docker volume create --label "${harness_label}" "${pgdata_volume_name}" >/dev/null
+ docker run --rm --label "${harness_label}" --entrypoint /bin/chown \
+ --volume "${pgdata_volume_name}:/pgdata" "${databasus_image}" \
+ 27501:27502 /pgdata
+
+ start_databasus "${container_name}" \
+ --volume "${data_volume_name}:/databasus-data" \
+ --volume "${pgdata_volume_name}:/databasus-data/pgdata"
+
+ [[ "$(docker exec "${container_name}" id -u databasus)" == "27501" ]]
+ [[ "$(docker exec "${container_name}" id -g databasus)" == "27502" ]]
+ assert_running_container "${container_name}"
+}
+
+run_partial_ids() {
+ local container_name="databasus-storage-partial-ids-${run_id}"
+ local data_root="${case_root}/partial-ids"
+
+ prepare_bind_tree "${data_root}" 27501 27502
+ start_databasus "${container_name}" \
+ --env PUID=25001 \
+ --volume "${data_root}:/databasus-data"
+
+ [[ "$(docker exec "${container_name}" id -u databasus)" == "25001" ]]
+ [[ "$(docker exec "${container_name}" id -g databasus)" == "27502" ]]
+ assert_running_container "${container_name}"
+}
+
+run_invalid_ids() {
+ local invalid_value
+ local container_name
+
+ for invalid_value in "" 0 abc 4294967295 18446744073709551617; do
+ container_name="databasus-storage-invalid-id-${run_id}-${RANDOM}"
+ start_failing_databasus "${container_name}" --env "PUID=${invalid_value}"
+ docker logs "${container_name}" 2>&1 | grep -Fq "ERROR: PUID must be a non-zero decimal Linux ID"
+ done
+
+ container_name="databasus-storage-colliding-id-${run_id}"
+ start_failing_databasus "${container_name}" --env PUID=1
+ docker logs "${container_name}" 2>&1 | grep -Fq "belongs to account"
}
run_bind_root() {
local container_name="databasus-storage-bind-${run_id}"
local data_root="${case_root}/bind-root"
- mkdir -p "${data_root}"
- chmod 0770 "${data_root}"
+ prepare_bind_tree "${data_root}" 999 999
start_databasus "${container_name}" --volume "${data_root}:/databasus-data"
- probe_service_paths "${container_name}"
+ assert_running_container "${container_name}"
}
run_named_volume() {
@@ -230,7 +391,7 @@ run_named_volume() {
docker volume create --label "${harness_label}" "${volume_name}" >/dev/null
start_databasus "${container_name}" --volume "${volume_name}:/databasus-data"
- probe_service_paths "${container_name}"
+ assert_running_container "${container_name}"
}
run_split_mounts() {
@@ -246,44 +407,79 @@ run_split_mounts() {
docker volume create --label "${harness_label}" "${pgdata_volume_name}" >/dev/null
start_databasus "${container_name}" \
--volume "${data_volume_name}:/databasus-data" \
- --tmpfs /databasus-data/temp:rw,nosuid,size=64m,mode=0700,uid=65532,gid=65532 \
+ --tmpfs /databasus-data/temp:rw,nosuid,size=64m,mode=0700,uid=999,gid=999 \
--volume "${backup_volume_name}:/databasus-data/backups" \
--volume "${pgdata_volume_name}:/databasus-data/pgdata"
temporary_device_id="$(docker exec "${container_name}" stat -c %d /databasus-data/temp)"
backup_device_id="$(docker exec "${container_name}" stat -c %d /databasus-data/backups)"
[[ "${temporary_device_id}" != "${backup_device_id}" ]]
- probe_service_paths "${container_name}"
+ assert_running_container "${container_name}"
+}
+
+run_metadata_changes_denied() {
+ local container_name="databasus-storage-metadata-denied-${run_id}"
+ local data_root="${case_root}/metadata-denied"
+
+ prepare_bind_tree "${data_root}" 999 999
+ start_databasus "${container_name}" \
+ --cap-drop CHOWN \
+ --cap-drop FOWNER \
+ --env PUID=999 \
+ --env PGID=999 \
+ --volume "${data_root}:/databasus-data"
+ assert_running_container "${container_name}"
}
run_read_only() {
local container_name="databasus-storage-read-only-${run_id}"
local data_root="${case_root}/read-only"
- mkdir -p "${data_root}/pgdata" "${data_root}/pgsocket" "${data_root}/temp" "${data_root}/backups"
- docker run --rm --label "${harness_label}" --entrypoint /bin/sh \
- --volume "${data_root}:/data" "${databasus_image}" -c \
- 'chown 65532:65532 /data /data/temp /data/backups && chown 999:999 /data/pgdata /data/pgsocket && chmod 0770 /data /data/backups && chmod 0700 /data/pgdata /data/pgsocket /data/temp'
- docker run --detach \
- --name "${container_name}" \
- --label "${harness_label}" \
- --mount "type=bind,source=${data_root},target=/databasus-data,readonly" \
- "${databasus_image}" >/dev/null
- wait_for_exit "${container_name}"
- docker logs "${container_name}" 2>&1 | grep -Fqi "Read-only file system"
+ prepare_bind_tree "${data_root}" 999 999
+ start_failing_databasus "${container_name}" \
+ --env PUID=999 \
+ --env PGID=999 \
+ --mount "type=bind,source=${data_root},target=/databasus-data,readonly"
+ assert_storage_permission_failure "${container_name}"
}
-run_inaccessible_path() {
- local container_name="databasus-storage-inaccessible-${run_id}"
- local volume_name="databasus-storage-inaccessible-${run_id}"
+run_wrong_owner() {
+ local container_name="databasus-storage-wrong-owner-${run_id}"
+ local data_root="${case_root}/wrong-owner"
+
+ prepare_bind_tree "${data_root}" 999 999 27501 27502
+ start_failing_databasus "${container_name}" \
+ --cap-drop CHOWN \
+ --cap-drop FOWNER \
+ --env PUID=999 \
+ --env PGID=999 \
+ --volume "${data_root}:/databasus-data"
+ assert_storage_permission_failure "${container_name}"
+ docker logs "${container_name}" 2>&1 | grep -Fq \
+ "Required operation: save a file through local storage."
+}
- docker volume create --label "${harness_label}" "${volume_name}" >/dev/null
- start_databasus "${container_name}" --volume "${volume_name}:/databasus-data"
- docker exec "${container_name}" chmod 000 /databasus-data/backups
- if probe_path "${container_name}" databasus /databasus-data/backups >/dev/null 2>&1; then
- echo "Databasus wrote to an inaccessible backup path" >&2
- return 1
- fi
+run_unwritable_data_root() {
+ local container_name="databasus-storage-unwritable-root-${run_id}"
+ local data_root="${case_root}/unwritable-root"
+
+ prepare_bind_tree "${data_root}" 999 999
+ docker run --rm --label "${harness_label}" --entrypoint /bin/sh \
+ --volume "${data_root}:/data" "${databasus_image}" -eu -c '
+ chown 27501:27502 /data
+ chmod 0555 /data
+ '
+
+ start_failing_databasus "${container_name}" \
+ --cap-drop CHOWN \
+ --cap-drop DAC_OVERRIDE \
+ --cap-drop FOWNER \
+ --env PUID=999 \
+ --env PGID=999 \
+ --volume "${data_root}:/databasus-data"
+ assert_storage_permission_failure "${container_name}"
+ docker logs "${container_name}" 2>&1 | grep -Fq \
+ "Required operation: create, read, and remove a required file."
}
run_network_prerequisites() {
@@ -308,7 +504,6 @@ run_cifs() {
local server_volume_name="databasus-storage-cifs-server-${run_id}"
local data_volume_name="databasus-storage-cifs-data-${run_id}"
local backup_volume_name="databasus-storage-cifs-backup-${run_id}"
- local temporary_volume_name="databasus-storage-cifs-temp-${run_id}"
local server_address
run_network_prerequisites
@@ -317,7 +512,7 @@ run_cifs() {
docker volume create --label "${harness_label}" "${data_volume_name}" >/dev/null
docker run --rm --label "${harness_label}" --entrypoint /bin/sh \
--volume "${server_volume_name}:/shared" "${databasus_image}" -c \
- 'chown 25001:25002 /shared && chmod 0770 /shared'
+ 'chown 999:999 /shared && chmod 0770 /shared'
docker run --detach \
--name "${server_container_name}" \
--label "${harness_label}" \
@@ -326,36 +521,34 @@ run_cifs() {
--env NAME=Storage \
--env USER=storage-test \
--env PASS=storage-test-password \
- --env UID=25001 \
- --env GID=25002 \
+ --env UID=999 \
+ --env GID=999 \
--volume "${server_volume_name}:/shared" \
"${samba_fixture_image}" >/dev/null
wait_for_health "${server_container_name}"
server_address="$(docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${server_container_name}")"
- for volume_name in "${backup_volume_name}" "${temporary_volume_name}"; do
- docker volume create \
- --label "${harness_label}" \
- --driver local \
- --opt type=cifs \
- --opt "device=//${server_address}/Storage" \
- --opt "o=username=storage-test,password=storage-test-password,vers=3.0,uid=25001,gid=25002,file_mode=0660,dir_mode=0770" \
- "${volume_name}" >/dev/null
- done
+ docker volume create \
+ --label "${harness_label}" \
+ --driver local \
+ --opt type=cifs \
+ --opt "device=//${server_address}/Storage" \
+ --opt "o=username=storage-test,password=storage-test-password,vers=3.0,uid=0,gid=999,file_mode=0660,dir_mode=0770" \
+ "${backup_volume_name}" >/dev/null
start_databasus "${client_container_name}" \
- --env DATABASUS_PUID=25001 \
- --env DATABASUS_PGID=25002 \
- --env TMPDIR=/databasus-data/temp \
--volume "${data_volume_name}:/databasus-data" \
- --volume "${temporary_volume_name}:/databasus-data/temp" \
--volume "${backup_volume_name}:/databasus-data/backups"
- probe_path "${client_container_name}" databasus /databasus-data/temp
- probe_path "${client_container_name}" databasus /databasus-data/backups
- docker exec --user databasus "${client_container_name}" /bin/sh -c \
- "tr '\\0' '\\n' < /proc/1/environ | grep -Fxq TMPDIR=/tmp"
- assert_service_boundaries "${client_container_name}"
+ [[ "$(docker exec "${client_container_name}" stat -c %u /databasus-data/backups)" == "0" ]]
+ [[ "$(docker exec "${client_container_name}" stat -c %g /databasus-data/backups)" == "999" ]]
+ [[ "$(docker exec "${client_container_name}" stat -c %a /databasus-data/backups)" == "770" ]]
+ docker exec --user databasus "${client_container_name}" /bin/sh -eu -c '
+ printf fixed-mode > /databasus-data/backups/.fixed-mode-check
+ test "$(stat -c %a /databasus-data/backups/.fixed-mode-check)" = 660
+ rm /databasus-data/backups/.fixed-mode-check
+ '
+ assert_running_container "${client_container_name}"
}
run_nfs_root_squash() {
@@ -363,17 +556,19 @@ run_nfs_root_squash() {
local server_container_name="databasus-storage-nfs-server-${run_id}"
local client_container_name="databasus-storage-nfs-client-${run_id}"
local server_volume_name="databasus-storage-nfs-server-${run_id}"
- local data_volume_name="databasus-storage-nfs-data-${run_id}"
+ local pgdata_volume_name="databasus-storage-nfs-pgdata-${run_id}"
local client_volume_name="databasus-storage-nfs-client-${run_id}"
local server_address
run_network_prerequisites
docker network create --label "${harness_label}" "${network_name}" >/dev/null
docker volume create --label "${harness_label}" "${server_volume_name}" >/dev/null
- docker volume create --label "${harness_label}" "${data_volume_name}" >/dev/null
+ docker volume create --label "${harness_label}" "${pgdata_volume_name}" >/dev/null
docker run --rm --label "${harness_label}" --entrypoint /bin/sh \
--volume "${server_volume_name}:/nfsshare" "${databasus_image}" -c \
- 'chown 65532:65532 /nfsshare && chmod 0770 /nfsshare'
+ 'mkdir -p /nfsshare/pgdata /nfsshare/pgsocket /nfsshare/temp &&
+ chown -R 999:999 /nfsshare &&
+ chmod 0755 /nfsshare /nfsshare/pgdata /nfsshare/pgsocket /nfsshare/temp'
docker run --detach \
--name "${server_container_name}" \
--label "${harness_label}" \
@@ -401,15 +596,179 @@ run_nfs_root_squash() {
echo "root-squashed NFS accepted a client-root ownership change" >&2
return 1
fi
+
start_databasus "${client_container_name}" \
- --volume "${data_volume_name}:/databasus-data" \
- --volume "${client_volume_name}:/databasus-data/backups"
- probe_service_paths "${client_container_name}"
- docker rm -f "${client_container_name}" >/dev/null
+ --volume "${client_volume_name}:/databasus-data" \
+ --volume "${pgdata_volume_name}:/databasus-data/pgdata" \
+ --tmpfs /databasus-data/pgsocket:rw,nosuid,size=16m,mode=0700,uid=999,gid=999 \
+ --tmpfs /databasus-data/temp:rw,nosuid,size=64m,mode=0700,uid=999,gid=999
+ assert_running_container "${client_container_name}"
+ docker rm -fv "${client_container_name}" >/dev/null
start_databasus "${client_container_name}" \
- --volume "${data_volume_name}:/databasus-data" \
- --volume "${client_volume_name}:/databasus-data/backups"
- probe_service_paths "${client_container_name}"
+ --volume "${client_volume_name}:/databasus-data" \
+ --volume "${pgdata_volume_name}:/databasus-data/pgdata" \
+ --tmpfs /databasus-data/pgsocket:rw,nosuid,size=16m,mode=0700,uid=999,gid=999 \
+ --tmpfs /databasus-data/temp:rw,nosuid,size=64m,mode=0700,uid=999,gid=999
+ assert_running_container "${client_container_name}"
+}
+
+get_application_database_dsn() {
+ local container_name="$1"
+
+ docker exec --user databasus "${container_name}" /bin/sh -eu -c '
+ database_dsn="$(tr "\0" "\n" < /proc/1/environ | sed -n "s/^DATABASE_DSN=//p")"
+ if [ -z "${database_dsn}" ]; then
+ set -a
+ . /.env
+ set +a
+ database_dsn="${DATABASE_DSN}"
+ fi
+ printf "%s" "${database_dsn}"
+ '
+}
+
+write_upgrade_markers() {
+ local container_name="$1"
+ local release_tag="$2"
+ local database_dsn
+
+ database_dsn="$(get_application_database_dsn "${container_name}")"
+ docker exec -i "${container_name}" /usr/lib/postgresql/17/bin/psql \
+ "${database_dsn}" -v ON_ERROR_STOP=1 -v release_tag="${release_tag}" <<'SQL'
+CREATE TABLE IF NOT EXISTS filesystem_upgrade_markers (
+ release_tag text PRIMARY KEY
+);
+INSERT INTO filesystem_upgrade_markers (release_tag)
+VALUES (:'release_tag')
+ON CONFLICT (release_tag) DO NOTHING;
+SQL
+
+ docker exec "${container_name}" /bin/sh -eu -c '
+ printf "%s" "$1" > /databasus-data/backups/filesystem-upgrade-marker
+ ' sh "${release_tag}"
+ docker exec --user databasus "${container_name}" /bin/sh -eu -c '
+ printf "\nfilesystem-upgrade-log-marker:%s\n" "$1" >> /databasus-data/databasus.log
+ ' sh "${release_tag}"
+ docker exec --user databasus "${container_name}" /bin/sh -eu -c '
+ queue_directory="/databasus-data/backups/wal-queue/filesystem-upgrade/$1"
+ mkdir -p "${queue_directory}/pending-upload"
+ printf "filesystem-upgrade-wal-marker:%s" "$1" > "${queue_directory}/pending-upload/segment"
+ chmod 0700 \
+ /databasus-data/backups/wal-queue \
+ /databasus-data/backups/wal-queue/filesystem-upgrade \
+ "${queue_directory}" \
+ "${queue_directory}/pending-upload"
+ chmod 0600 "${queue_directory}/pending-upload/segment"
+ ' sh "${release_tag}"
+}
+
+prepare_upgrade_secret() {
+ local container_name="$1"
+ local release_tag="$2"
+ local database_dsn
+ local secret_value="filesystem-upgrade-secret-${release_tag}"
+
+ if docker exec "${container_name}" test -f /databasus-data/secret.key; then
+ docker exec "${container_name}" sha256sum /databasus-data/secret.key | cut -d' ' -f1
+ return
+ fi
+
+ database_dsn="$(get_application_database_dsn "${container_name}")"
+ docker exec "${container_name}" /usr/lib/postgresql/17/bin/psql \
+ "${database_dsn}" -v ON_ERROR_STOP=1 \
+ -c "INSERT INTO secret_keys (secret) VALUES ('${secret_value}')" >/dev/null
+ printf "%s" "${secret_value}" | sha256sum | cut -d' ' -f1
+}
+
+assert_upgrade_markers() {
+ local container_name="$1"
+ local release_tag="$2"
+ local secret_hash="$3"
+ local system_identifier="$4"
+ local log_size_before_update="$5"
+ local database_dsn
+ local log_size_after_update
+ local runtime_uid
+
+ database_dsn="$(get_application_database_dsn "${container_name}")"
+ [[ "$(docker exec "${container_name}" /usr/lib/postgresql/17/bin/psql \
+ "${database_dsn}" -tA -v ON_ERROR_STOP=1 \
+ -c "SELECT release_tag FROM filesystem_upgrade_markers WHERE release_tag='${release_tag}'")" == "${release_tag}" ]]
+ [[ "$(docker exec "${container_name}" cat /databasus-data/backups/filesystem-upgrade-marker)" == "${release_tag}" ]]
+ [[ "$(docker exec "${container_name}" sha256sum /databasus-data/secret.key | cut -d' ' -f1)" == "${secret_hash}" ]]
+ [[ "$(docker exec "${container_name}" /usr/lib/postgresql/17/bin/pg_controldata \
+ /databasus-data/pgdata | sed -n 's/^Database system identifier: *//p')" == "${system_identifier}" ]]
+ docker exec "${container_name}" grep -Fq \
+ "filesystem-upgrade-log-marker:${release_tag}" /databasus-data/databasus.log
+ runtime_uid="$(docker exec "${container_name}" id -u databasus)"
+ [[ "$(docker exec "${container_name}" stat -c %u /databasus-data/databasus.log)" == "${runtime_uid}" ]]
+ log_size_after_update="$(docker exec "${container_name}" stat -c %s /databasus-data/databasus.log)"
+ ((log_size_after_update > log_size_before_update))
+ docker exec --user databasus "${container_name}" /bin/sh -eu -c '
+ queue_directory="/databasus-data/backups/wal-queue/filesystem-upgrade/$1"
+ test "$(cat "${queue_directory}/pending-upload/segment")" = "filesystem-upgrade-wal-marker:$1"
+ printf resumed > "${queue_directory}/resume-check"
+ rm "${queue_directory}/resume-check"
+ ' sh "${release_tag}"
+ [[ "$(docker exec "${container_name}" find \
+ /databasus-data/backups/wal-queue -xdev ! -user "${runtime_uid}" -print -quit)" == "" ]]
+}
+
+run_upgrade() {
+ local release_tag="$1"
+ local release_image="databasus/databasus:${release_tag}"
+ local old_container_name="databasus-storage-upgrade-old-${release_tag}-${run_id}"
+ local new_container_name="databasus-storage-upgrade-new-${release_tag}-${run_id}"
+ local volume_name="databasus-storage-upgrade-${release_tag}-${run_id}"
+ local secret_hash
+ local system_identifier
+ local log_size_before_update
+
+ docker image inspect "${release_image}" >/dev/null 2>&1 || docker pull "${release_image}" >/dev/null
+ docker volume create --label "${harness_label}" "${volume_name}" >/dev/null
+ docker run --detach \
+ --name "${old_container_name}" \
+ --label "${harness_label}" \
+ --health-interval 1s \
+ --health-start-period 1s \
+ --volume "${volume_name}:/databasus-data" \
+ "${release_image}" >/dev/null
+ wait_for_health "${old_container_name}"
+ write_upgrade_markers "${old_container_name}" "${release_tag}"
+ secret_hash="$(prepare_upgrade_secret "${old_container_name}" "${release_tag}")"
+ log_size_before_update="$(docker exec "${old_container_name}" stat -c %s /databasus-data/databasus.log)"
+ system_identifier="$(docker exec "${old_container_name}" /usr/lib/postgresql/17/bin/pg_controldata \
+ /databasus-data/pgdata | sed -n 's/^Database system identifier: *//p')"
+ docker stop "${old_container_name}" >/dev/null
+
+ start_databasus "${new_container_name}" --volume "${volume_name}:/databasus-data"
+ assert_upgrade_markers \
+ "${new_container_name}" \
+ "${release_tag}" \
+ "${secret_hash}" \
+ "${system_identifier}" \
+ "${log_size_before_update}"
+ assert_running_container "${new_container_name}"
+}
+
+run_upgrades() {
+ local release_tag
+
+ for release_tag in v3.54.0 v3.55.0 v3.55.1 v3.56.0; do
+ run_upgrade "${release_tag}"
+ done
+}
+
+run_legacy_directory_guard() {
+ local container_name="databasus-storage-legacy-directory-${run_id}"
+ local volume_name="databasus-storage-legacy-directory-${run_id}"
+
+ docker volume create --label "${harness_label}" "${volume_name}" >/dev/null
+ docker run --rm --label "${harness_label}" --entrypoint /bin/sh \
+ --volume "${volume_name}:/legacy" "${databasus_image}" \
+ -c 'printf legacy > /legacy/marker'
+ start_failing_databasus "${container_name}" --volume "${volume_name}:/postgresus-data"
+ docker logs "${container_name}" 2>&1 | grep -Fq "ERROR: Legacy volume detected!"
}
run_case() {
@@ -420,14 +779,23 @@ run_case() {
build-only) docker image inspect "${databasus_image}" >/dev/null ;;
default-ids) run_default_ids ;;
custom-ids) run_custom_ids ;;
+ maximum-ids) run_maximum_ids ;;
+ automatic-ids) run_automatic_ids ;;
+ empty-pgdata-ids) run_empty_pgdata_ids ;;
+ partial-ids) run_partial_ids ;;
+ invalid-ids) run_invalid_ids ;;
bind-root) run_bind_root ;;
named-volume) run_named_volume ;;
split-mounts) run_split_mounts ;;
+ metadata-changes-denied) run_metadata_changes_denied ;;
read-only) run_read_only ;;
- inaccessible-path) run_inaccessible_path ;;
+ wrong-owner) run_wrong_owner ;;
+ unwritable-data-root) run_unwritable_data_root ;;
network-prerequisites) run_network_prerequisites ;;
cifs) run_cifs ;;
nfs-root-squash) run_nfs_root_squash ;;
+ upgrades) run_upgrades ;;
+ legacy-directory-guard) run_legacy_directory_guard ;;
*)
echo "unknown Docker filesystem case: ${case_name}" >&2
return 2
@@ -435,20 +803,12 @@ run_case() {
esac
}
-# Issue coverage:
-# #45, #64 and #224: bind and split mounts.
-# #141, #478 and #738: default and custom service IDs without default remapping.
-# #274: CIFS forced modes plus a private process TMPDIR.
-# #751: PostgreSQL traversal through the bind-mounted data root.
-# #763: CIFS numeric ownership.
-# #96 and #199 require an arbitrary container user, which cannot start both services.
-# #401 concerns application-level transfer policy, not container permissions.
-# #431 exercises the existing cross-device move fallback, not container permissions.
-
if [[ "${selected_case}" == all ]]; then
for case_name in \
- build-only default-ids custom-ids bind-root named-volume split-mounts \
- read-only inaccessible-path cifs nfs-root-squash; do
+ build-only default-ids custom-ids maximum-ids automatic-ids empty-pgdata-ids partial-ids invalid-ids \
+ bind-root named-volume split-mounts metadata-changes-denied read-only wrong-owner \
+ unwritable-data-root \
+ cifs nfs-root-squash upgrades legacy-directory-guard; do
run_case "${case_name}"
cleanup
case_root="$(mktemp -d /tmp/databasus-storage-test.XXXXXXXX)"
diff --git a/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/.openspec.yaml b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/.openspec.yaml
new file mode 100644
index 00000000..1a62d62b
--- /dev/null
+++ b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-09-06
diff --git a/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/design.md b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/design.md
new file mode 100644
index 00000000..8df65c04
--- /dev/null
+++ b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/design.md
@@ -0,0 +1,78 @@
+## Context
+
+See `proposal.md` for the motivation. The image currently creates distinct `postgres` and `databasus` accounts, publishes four identity variables, and remaps them before preparing mounted paths (`Dockerfile:162-179`, `Dockerfile:231-279`). PostgreSQL uses a private socket and peer authentication for startup administration, while the application connects through loopback with a generated password (`Dockerfile:281-367`). Local backup publication uses `LocalStorage.SaveFile`, including its rename and cross-filesystem fallback, and removal uses `LocalStorage.DeleteFile` (`backend/internal/features/storages/models/local/model.go`). The filesystem harness probes directories independently and assumes two accounts (`e2e/docker-storage/run.sh:135-215`).
+
+The implementation follows the root `AGENTS.md`, `backend/AGENTS.md`, and `website/AGENTS.md`.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Make mounted-data ownership determine the default runtime identity for existing installations.
+- Test the public local-storage save and delete operations at startup and in the filesystem suite.
+- Keep the bundled processes non-root after startup preparation.
+- Produce an error that gives operators the failed operation, path, effective IDs, and documentation link.
+
+**Non-Goals:**
+
+- Publish embedded PostgreSQL or Valkey outside the container.
+- Rename the PostgreSQL database role or change the metadata schema.
+- Add compatibility aliases for deleted variables.
+- Change backup encryption, naming, or retention behavior.
+
+## Decisions
+
+### Use one operating-system account for bundled processes
+
+The package-provided PostgreSQL account will become `databasus`, preserving numeric ID `999` as the fresh-install fallback. The application, PostgreSQL, and Valkey will all execute through that account. The PostgreSQL database role stays `postgres`.
+
+### Use `PUID` and `PGID` as the complete public identity interface
+
+Startup resolves each value independently. An explicit valid value wins. Otherwise it checks an existing PostgreSQL data directory, the backup mount, the data root, and then `999`. It skips root-owned candidates. The four separate variables are removed from the image and startup no longer reads them.
+
+### Treat metadata normalization as preparation, not proof
+
+Startup attempts `chown` and `chmod` on required paths. It then executes the actual operations under `databasus`. The backend `--test-storage` command exercises `LocalStorage.SaveFile` and `LocalStorage.DeleteFile`. Focused shell probes cover PostgreSQL paths, its socket directory, and Databasus control files.
+
+### Keep the Dockerfile declarative
+
+The `Dockerfile` will install packages, create the image account, copy runtime artifacts, and declare `docker/start.sh` as the entrypoint. The script will group identity resolution, mounted-storage preparation, service bootstrap, and final application execution into named functions. Its `main` function will show the runtime sequence without the escaping required by an inline Docker heredoc.
+
+### Exercise local storage through its public methods
+
+The main backend binary will accept `--test-storage`. It will create a unique probe name, call `LocalStorage.SaveFile`, then call `LocalStorage.DeleteFile`. Startup will start Valkey before invoking the command, while PostgreSQL and the Databasus application will remain stopped until storage validation passes. The command will report the failed operation, effective IDs, and documentation link. `LocalStorage.TestConnection` remains unchanged.
+
+Valkey-backed rate limiters, cache utilities, and the publish-subscribe manager will retain explicit client injection. Starting Valkey first avoids adding deferred client providers only for startup command dispatch.
+
+Configuration will recognize Go test binaries by their executable suffix and the `cleanup_test_db` command by its executable name. It will no longer infer test mode from arbitrary command-line arguments. This keeps `--test-storage` on production storage paths without requiring test database settings.
+
+### Limit peer authentication to PostgreSQL bootstrap
+
+Bootstrap writes a temporary identity map from operating-system user `databasus` to database role `postgres`. After setting the generated password and creating the metadata database, startup replaces the host authentication rules with socket rejection and reloads PostgreSQL. The application uses SCRAM over loopback.
+
+### Test upgrades with persistent artifacts
+
+Upgrade cases create data with each covered released image, stop it, start the candidate against the same persistent data, and verify a metadata marker, secret key, application log, backup marker, nested WAL queue, and PostgreSQL cluster marker. Startup recursively prepares an existing `backups/wal-queue` tree because its `0700` directories and `0600` segments must remain resumable when a released image used a different numeric account. It then traverses every queue directory and opens every segment for reading and writing under `databasus` before starting PostgreSQL or the Databasus application. Test names describe the storage behavior and contain no tracker references.
+
+## Risks / Trade-offs
+
+- [An automatically selected owner belongs to an unrelated image account] -> Reject collisions with another existing account and report the selected ID before services start.
+- [A mount reports usable permissions but publication still differs] -> Call `LocalStorage.SaveFile` under the final runtime identity.
+- [The startup probe conflicts with a real backup] -> Generate a unique probe name and delete only that file.
+- [`--test-storage` is mistaken for a test binary] -> Detect test processes from the executable name and cover the storage flag with a regression test.
+- [Storage validation fails after Valkey starts] -> Stop startup before PostgreSQL or the Databasus application and let container shutdown terminate Valkey.
+- [Bootstrap authentication remains enabled after an interrupted start] -> Rewrite the temporary rules on every start and replace them before launching the application.
+- [An update cannot use existing ownership and cannot change it] -> Stop with the exact operation, effective IDs, and the Advanced Config link.
+- [An update leaves nested WAL queues owned by the previous image account] -> Prepare that tree recursively, verify directory creation and file opens as `databasus`, and preserve queued bytes in the upgrade fixtures.
+- [Released images are unavailable during local development] -> Keep upgrade cases selectable and make the full CI job pull the pinned released tags before execution.
+
+## Migration Plan
+
+1. Build the image with one `databasus` account at `999:999` and the new startup resolver.
+2. Correct test-process detection, start Valkey before storage validation, and add the backend `--test-storage` command with focused tests.
+3. Replace the harness account assertions with public local-storage save, delete, and upgrade assertions.
+4. Update documentation and synchronize validated delta specs into the main specifications.
+5. Release notes will tell operators to remove the four deleted variables and use `PUID` and `PGID` only when automatic selection is unsuitable.
+6. Replace the inline entrypoint heredoc with `docker/start.sh` without changing its runtime behavior or filesystem compatibility matrix.
+
+Rollback uses the previous image against unchanged persistent volumes. The candidate does not rewrite backup contents, the secret key, or the PostgreSQL cluster beyond normal PostgreSQL startup and migrations.
diff --git a/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/proposal.md b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/proposal.md
new file mode 100644
index 00000000..26890548
--- /dev/null
+++ b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/proposal.md
@@ -0,0 +1,32 @@
+## Why
+
+The current Docker image assigns separate numeric identities to Databasus and its embedded services. This breaks writable bind mounts whose existing ownership matches an earlier image, and the filesystem suite does not exercise the same temporary-to-backup publication path that fails in production.
+
+## What Changes
+
+- Run Databasus, embedded PostgreSQL, and Valkey under one non-root operating-system account named `databasus`.
+- Support optional `PUID` and `PGID` overrides, with automatic ID selection from existing mounted data when they are absent.
+- **BREAKING**: delete `DATABASUS_PUID`, `DATABASUS_PGID`, `POSTGRES_PUID`, and `POSTGRES_PGID` without aliases or fallback handling.
+- Attempt ownership and mode normalization during startup, then decide compatibility through real read, write, publish, and delete operations if metadata changes are unavailable.
+- Add a `--test-storage` command-line flag that saves and deletes a unique file through the public local-storage methods.
+- Keep image construction in the `Dockerfile` and move runtime startup orchestration into `docker/start.sh`, where named functions make the sequence readable.
+- Preserve existing data across upgrades and preserve the deprecated Postgresus directory and `WAL_V1` startup guards.
+- Expand the Docker filesystem suite with real bind, named-volume, split-filesystem, CIFS, NFS, permission-failure, identity, upgrade, and embedded-service scenarios.
+- Update the six Advanced Config pages and Helm documentation for the single-account model and the `PUID`/`PGID` interface.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `docker-storage-compatibility`: Define the single runtime account, automatic identity selection, capability-based startup checks, actionable failures, and upgrade coverage.
+- `internal-postgresql-protection`: Use bootstrap-only peer mapping followed by socket rejection and SCRAM-authenticated loopback access.
+
+## Impact
+
+The change affects the root `Dockerfile`, `docker/start.sh`, backend command code, Docker filesystem tests and CI coverage, OpenSpec contracts, all six website Advanced Config translations, and Helm chart documentation. It answers to the root `AGENTS.md`, `backend/AGENTS.md`, and `website/AGENTS.md`.
+
+Out of scope: publishing the embedded PostgreSQL port, changing the PostgreSQL database role name, changing backup formats, or preserving the four deleted identity variables through compatibility shims.
diff --git a/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/specs/docker-storage-compatibility/spec.md b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/specs/docker-storage-compatibility/spec.md
new file mode 100644
index 00000000..8a290bf0
--- /dev/null
+++ b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/specs/docker-storage-compatibility/spec.md
@@ -0,0 +1,145 @@
+## ADDED Requirements
+
+### Requirement: Docker services share one configurable runtime identity
+
+The Docker image SHALL run Databasus, embedded PostgreSQL, and Valkey under one non-root operating-system account named `databasus`. Operators MAY set its numeric identity with `PUID` and `PGID`. Each supplied value SHALL be a non-zero decimal Linux ID within the supported system range.
+
+When an override is absent, startup SHALL select that ID independently from the existing PostgreSQL data owner, then the mounted backup or data-root owner, and finally `999`. Root ownership SHALL NOT be selected automatically.
+
+#### Scenario: Fresh installation uses the fallback identity
+
+- **WHEN** an operator starts the image without identity overrides or existing non-root ownership
+- **THEN** all bundled services run as user ID `999` and group ID `999` under the account name `databasus`
+
+#### Scenario: Existing data determines the identity
+
+- **WHEN** an existing PostgreSQL data directory has a non-root numeric owner and `PUID` or `PGID` is absent
+- **THEN** startup uses the corresponding owner ID before considering other mounts or the fallback
+
+#### Scenario: Operator supplies identity overrides
+
+- **WHEN** an operator supplies valid `PUID` and `PGID` values
+- **THEN** all bundled services run with those numeric IDs
+
+#### Scenario: Operator overrides one identity value
+
+- **WHEN** an operator supplies either `PUID` or `PGID` and mounted data provides the other numeric ID
+- **THEN** startup combines the explicit value with the automatically selected counterpart
+
+#### Scenario: Operator supplies an invalid identity
+
+- **WHEN** `PUID` or `PGID` is empty, non-numeric, zero, or outside the supported range
+- **THEN** the container exits before starting its services
+- **AND** the log identifies the invalid variable
+
+### Requirement: Startup validates storage through required operations
+
+Startup SHALL attempt to prepare the data root, PostgreSQL data, PostgreSQL socket, temporary, and backup paths with the selected identity and required modes. A failed ownership or mode change SHALL NOT stop startup when the selected account can still perform every required operation.
+
+Startup SHALL start Valkey and wait for readiness before running the main Databasus binary with `--test-storage` under the selected account. The command SHALL save a unique file through `LocalStorage.SaveFile` and remove it through `LocalStorage.DeleteFile`. Startup SHALL also verify the operations required for PostgreSQL data, its socket, and Databasus control files. A failed check SHALL stop startup before PostgreSQL or the Databasus application runs.
+
+#### Scenario: Filesystem denies metadata changes but permits operations
+
+- **WHEN** a mounted filesystem rejects ownership or mode changes but the selected account can perform all required operations
+- **THEN** the container starts successfully
+
+#### Scenario: Selected identity creates missing service directories
+
+- **WHEN** container root cannot create a required directory but the selected account can create it
+- **THEN** startup creates the directory as the selected account and continues
+
+#### Scenario: Backup publication is not permitted
+
+- **WHEN** the selected account cannot publish a file from the temporary path to the backup path
+- **THEN** the container exits before starting the application
+- **AND** the English error names the affected path, required operation, effective user and group IDs, and `https://databasus.com/advanced-config/#docker-storage-permissions`
+
+#### Scenario: Mounted path is read-only
+
+- **WHEN** any required mounted path is read-only
+- **THEN** the container exits before starting PostgreSQL or the Databasus application
+- **AND** the log provides the same identity and documentation details
+
+#### Scenario: Data root cannot create control files
+
+- **WHEN** temporary, backup, PostgreSQL data, and socket paths are writable but the data root cannot create a control file
+- **THEN** the container exits before starting PostgreSQL or the Databasus application
+- **AND** the English error identifies the data root and required operation
+
+### Requirement: Existing Docker data remains usable after an image update
+
+The current image SHALL start with persistent data created by versions `v3.54.0`, `v3.55.0`, `v3.55.1`, and `v3.56.0` when the mounted filesystem permits the selected account's required operations. Startup SHALL preserve the metadata database, secret key, application log, existing backup files, resumable nested WAL queues, and the existing PostgreSQL cluster. It SHALL prepare an existing WAL queue recursively and verify directory creation plus non-mutating file opens under the selected account before PostgreSQL or the Databasus application starts.
+
+#### Scenario: Existing installation is updated
+
+- **WHEN** an operator replaces one of the covered earlier images with the current image without adding identity settings
+- **THEN** the current container becomes healthy
+- **AND** the metadata database, secret key, application log, existing backup, nested WAL queue, and PostgreSQL data remain available
+
+## MODIFIED Requirements
+
+### Requirement: One filesystem suite runs locally and in CI
+
+The repository SHALL provide `make test-filesystems` as the single entry point for the Docker filesystem suite. It SHALL build or accept a local candidate image and run the same cases locally and in a dedicated GitHub Actions job. The job SHALL build and load its own candidate without publishing or transferring it.
+
+Each positive case SHALL start the real container and invoke `databasus --test-storage`, which uses the public local-storage save and delete methods. Each negative case SHALL assert the startup failure and its actionable error. Every case SHALL clean its containers, volumes, networks, mounts, and temporary files.
+
+#### Scenario: Developer runs the complete suite
+
+- **WHEN** a developer runs `make test-filesystems` without an image reference
+- **THEN** the target builds a local candidate and tests it
+
+#### Scenario: CI tests its candidate
+
+- **WHEN** the filesystem job builds and loads its candidate
+- **THEN** the suite tests that local image without pushing or pulling a candidate image
+
+#### Scenario: A case allocates Docker resources
+
+- **WHEN** the case succeeds or fails after resource allocation
+- **THEN** the harness removes every resource created by that case
+
+### Requirement: The matrix covers supported mount behavior
+
+The suite SHALL cover an ext4 bind-mounted data root, a Docker named volume, separate temporary, backup, and PostgreSQL mounts, automatic and explicit runtime IDs, rejected backup and data-root permission layouts, CIFS numeric ownership and forced file modes, writable NFS with root squash, and upgrades from the covered earlier images. It SHALL verify one non-root numeric identity for all bundled services, bootstrap and runtime PostgreSQL authentication, and restrictive modes for generated credential files.
+
+#### Scenario: Local Docker storage layouts
+
+- **WHEN** the candidate uses an ext4 bind mount, named volume, or separate mounts
+- **THEN** the container becomes healthy and the storage command saves and deletes its probe
+
+#### Scenario: Temporary and backup paths use different filesystems
+
+- **WHEN** the temporary and backup paths have different device IDs
+- **THEN** `LocalStorage.SaveFile` succeeds through its supported cross-filesystem path and `LocalStorage.DeleteFile` removes the probe
+
+#### Scenario: CIFS maps numeric ownership
+
+- **WHEN** a real CIFS fixture presents root ownership, numeric group ownership `999`, directory mode `0770`, and mount-enforced file modes
+- **THEN** the container becomes healthy and completes the storage command
+- **AND** startup skips the root user ID and writes through group `999`
+
+#### Scenario: NFS data storage denies ownership changes to container root
+
+- **WHEN** a root-squashed NFS data root has no backups directory, rejects ownership and mode changes, remains writable by the selected identity, and local mounts provide PostgreSQL and temporary storage
+- **THEN** the selected identity creates the backups directory and the container becomes healthy
+- **AND** the storage command succeeds without requiring ownership changes
+
+#### Scenario: Mounted path denies required access
+
+- **WHEN** a mounted path does not permit an operation required by the selected identity
+- **THEN** startup fails with the documented actionable error
+
+## REMOVED Requirements
+
+### Requirement: Docker service IDs have image defaults
+
+**Reason**: One runtime account and automatic mounted-data discovery replace four independent image defaults.
+
+**Migration**: Remove the four old variables. Set `PUID` and `PGID` only when automatic selection does not fit the mounted filesystem.
+
+### Requirement: Service accounts remain isolated
+
+**Reason**: Bundled services now use one non-root operating-system account.
+
+**Migration**: Set `PUID` and `PGID` only when automatic selection is unsuitable.
diff --git a/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/specs/internal-postgresql-protection/spec.md b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/specs/internal-postgresql-protection/spec.md
new file mode 100644
index 00000000..971db5b4
--- /dev/null
+++ b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/specs/internal-postgresql-protection/spec.md
@@ -0,0 +1,45 @@
+## MODIFIED Requirements
+
+### Requirement: The embedded PostgreSQL instance stays private under the shared runtime account
+
+The embedded PostgreSQL server SHALL run under the same non-root operating-system account as the Databasus application and Valkey. During bootstrap only, peer mapping SHALL allow that account to administer the PostgreSQL role named `postgres`. After bootstrap, Unix-socket database login SHALL be rejected. Loopback TCP connections SHALL require SCRAM authentication with the generated credential, and replication connections to the embedded cluster SHALL be rejected.
+
+The embedded PostgreSQL and Valkey ports SHALL remain unpublished by the image.
+
+#### Scenario: Application account opens the private socket
+
+- **WHEN** the Databasus application account attempts a Unix-socket database login after bootstrap
+- **THEN** PostgreSQL authentication rejects the connection
+
+#### Scenario: Shared runtime account performs startup administration
+
+- **WHEN** the shared `databasus` operating-system account connects as role `postgres` during startup
+- **THEN** the temporary peer mapping permits the administrative connection
+
+#### Scenario: Loopback TCP connection without the generated password
+
+- **WHEN** any process connects to the embedded PostgreSQL server over loopback TCP without the current generated password
+- **THEN** SCRAM authentication rejects the connection
+
+#### Scenario: Application uses the generated password
+
+- **WHEN** Databasus connects to the embedded PostgreSQL server over loopback with the generated password
+- **THEN** PostgreSQL accepts the connection
+
+#### Scenario: Replication connection to the embedded cluster
+
+- **WHEN** a client requests a replication connection to the embedded PostgreSQL server
+- **THEN** PostgreSQL rejects it
+
+## REMOVED Requirements
+
+### Requirement: PostgreSQL and application accounts cannot share a UID
+
+**Reason**: All bundled processes now use the same non-root operating-system account.
+
+**Migration**: Replace separate PostgreSQL and Databasus identity settings with optional `PUID` and `PGID` settings for the shared `databasus` account.
+
+## RENAMED Requirements
+
+- FROM: `### Requirement: The embedded PostgreSQL instance is isolated from the application account`
+- TO: `### Requirement: The embedded PostgreSQL instance stays private under the shared runtime account`
diff --git a/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/tasks.md b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/tasks.md
new file mode 100644
index 00000000..9cc51867
--- /dev/null
+++ b/openspec/changes/archive/2026-09-06-simplify-docker-runtime-user/tasks.md
@@ -0,0 +1,34 @@
+## 1. Storage command
+
+- [x] 1.1 Add `--test-storage` to the main backend binary; save a unique probe with `LocalStorage.SaveFile`, delete it with `LocalStorage.DeleteFile`, and verify focused command tests pass
+- [x] 1.2 Start Valkey before running the storage command, retain explicit Valkey client injection in cache utilities, rate limiters, and publish-subscribe setup, and verify storage failures still stop PostgreSQL and the Databasus application
+- [x] 1.3 Detect test mode from the executable name instead of arbitrary command-line arguments, verify `--test-storage` uses production configuration without test database settings, and remove the separate filesystem-check binary and lifecycle-specific model changes
+
+## 2. Container runtime identity and services
+
+- [x] 2.1 Replace the two image accounts and four identity variables with one `databasus` account plus validated optional `PUID` and `PGID`; verify mounted pgdata discovery, automatic, explicit, partial, invalid, and collision cases
+- [x] 2.2 Prepare mounted paths without treating failed `chown` or `chmod` as failure, then run real capability checks before PostgreSQL and the Databasus application; verify writable restricted mounts start and inaccessible mounts fail with the documented error
+- [x] 2.3 Run PostgreSQL and Valkey under `databasus`, use bootstrap-only peer mapping to role `postgres`, reject runtime socket login, and keep loopback SCRAM; verify process IDs and authentication cases in the container suite
+- [x] 2.4 Preserve existing secret, control-file, application-log, nested WAL-queue, PostgreSQL, and deprecated-directory behavior; verify the filesystem-related guard and upgrade fixtures pass
+- [x] 2.5 Move runtime startup into `docker/start.sh`, organize it around named functions and a short `main`, and keep the `Dockerfile` focused on image construction and entrypoint declaration
+
+## 3. Filesystem regression suite
+
+- [x] 3.1 Replace only the temporary-to-backup probes with `databasus --test-storage`, retain focused PostgreSQL, socket, and control-file checks, and verify ext4 bind, named-volume, and split-filesystem cases
+- [x] 3.2 Cover CIFS group `999` with mode `0770`, fixed file modes, and local temporary storage; verify publication succeeds without required metadata changes
+- [x] 3.3 Cover writable root-squashed NFS plus read-only, wrong-owner, and unwritable data-root failures; verify allowed operations start and rejected operations emit the exact actionable error
+- [x] 3.4 Add upgrade fixtures for `v3.54.0`, `v3.55.0`, `v3.55.1`, and `v3.56.0`; verify metadata, secret key, application log, backup marker, nested WAL queue, and PostgreSQL cluster survive
+- [x] 3.5 Remove tracker-number inventory and two-account assumptions from the harness; verify ShellCheck and Actionlint pass
+- [x] 3.6 Run ShellCheck against `docker/start.sh` and verify the copied script in the candidate image is byte-identical and executable
+
+## 4. Documentation and specifications
+
+- [x] 4.1 Update all six Advanced Config pages with the single-account model, `PUID`/`PGID`, automatic selection, failure message, migration note, and English documentation link; verify website lint and build pass
+- [x] 4.2 Update Helm README and values wording for the same identity model; verify no removed identity variable remains in user documentation
+- [x] 4.3 Synchronize the remaining delta specs into the main specs, leave the local-storage model contract unchanged, and verify `openspec validate --strict` passes
+
+## 5. Final verification
+
+- [x] 5.1 Run backend formatting, focused tests, full tests, and `make lint`; resolve every failure
+- [x] 5.2 Build the candidate image and run `make test-filesystems`; resolve every filesystem or upgrade regression
+- [x] 5.3 Run the mandatory post-implementation reviewer against the complete diff and module rules, resolve every `CHANGES REQUIRED` finding, and leave the working tree ready to commit
diff --git a/openspec/specs/docker-storage-compatibility/spec.md b/openspec/specs/docker-storage-compatibility/spec.md
index c6aa50a1..692950f0 100644
--- a/openspec/specs/docker-storage-compatibility/spec.md
+++ b/openspec/specs/docker-storage-compatibility/spec.md
@@ -6,29 +6,81 @@ Defines the supported Docker account settings and the real-container filesystem
## Requirements
-### Requirement: Docker service IDs have image defaults
+### Requirement: Docker services share one configurable runtime identity
-The Docker image SHALL declare `DATABASUS_PUID=65532`, `DATABASUS_PGID=65532`, `POSTGRES_PUID=999`, and `POSTGRES_PGID=999`. A container SHALL inherit these values without ordinary installation configuration. Operators SHALL be able to override each service account with free numeric IDs accepted by the image.
+The Docker image SHALL run Databasus, embedded PostgreSQL, and Valkey under one non-root operating-system account named `databasus`. Operators MAY set its numeric identity with `PUID` and `PGID`. Each supplied value SHALL be a non-zero decimal Linux ID within the supported system range.
-#### Scenario: Container uses image defaults
+When an override is absent, startup SHALL select that ID independently from the existing PostgreSQL data owner, then the mounted backup or data-root owner, and finally `999`. Root ownership SHALL NOT be selected automatically.
-- **WHEN** an operator starts the image without identity overrides
-- **THEN** the container environment contains the four image defaults
-- **AND** the Databasus and PostgreSQL accounts use those IDs
+#### Scenario: Fresh installation uses the fallback identity
-#### Scenario: Operator supplies free custom IDs
+- **WHEN** an operator starts the image without identity overrides or existing non-root ownership
+- **THEN** all bundled services run as user ID `999` and group ID `999` under the account name `databasus`
-- **WHEN** an operator supplies free numeric IDs through the four supported variables
-- **THEN** the container starts with each service account using its configured user and primary group IDs
+#### Scenario: Existing data determines the identity
-### Requirement: Service accounts remain isolated
+- **WHEN** an existing PostgreSQL data directory has a non-root numeric owner and `PUID` or `PGID` is absent
+- **THEN** startup uses the corresponding owner ID before considering other mounts or the fallback
-The Databasus and PostgreSQL accounts SHALL have distinct user IDs and primary groups. PostgreSQL MAY receive access needed to traverse the shared data root. The Databasus account SHALL NOT gain access to PostgreSQL private data or its private socket.
+#### Scenario: Operator supplies identity overrides
-#### Scenario: Databasus account reads PostgreSQL private paths
+- **WHEN** an operator supplies valid `PUID` and `PGID` values
+- **THEN** all bundled services run with those numeric IDs
-- **WHEN** the Databasus account attempts to read the embedded database tree or private socket
-- **THEN** filesystem permissions reject the operation
+#### Scenario: Operator overrides one identity value
+
+- **WHEN** an operator supplies either `PUID` or `PGID` and mounted data provides the other numeric ID
+- **THEN** startup combines the explicit value with the automatically selected counterpart
+
+#### Scenario: Operator supplies an invalid identity
+
+- **WHEN** `PUID` or `PGID` is empty, non-numeric, zero, or outside the supported range
+- **THEN** the container exits before starting its services
+- **AND** the log identifies the invalid variable
+
+### Requirement: Startup validates storage through required operations
+
+Startup SHALL attempt to prepare the data root, PostgreSQL data, PostgreSQL socket, temporary, and backup paths with the selected identity and required modes. A failed ownership or mode change SHALL NOT stop startup when the selected account can still perform every required operation.
+
+Startup SHALL start Valkey and wait for readiness before running the main Databasus binary with `--test-storage` under the selected account. The command SHALL save a unique file through `LocalStorage.SaveFile` and remove it through `LocalStorage.DeleteFile`. Startup SHALL also verify the operations required for PostgreSQL data, its socket, and Databasus control files. A failed check SHALL stop startup before PostgreSQL or the Databasus application runs.
+
+#### Scenario: Filesystem denies metadata changes but permits operations
+
+- **WHEN** a mounted filesystem rejects ownership or mode changes but the selected account can perform all required operations
+- **THEN** the container starts successfully
+
+#### Scenario: Selected identity creates missing service directories
+
+- **WHEN** container root cannot create a required directory but the selected account can create it
+- **THEN** startup creates the directory as the selected account and continues
+
+#### Scenario: Backup publication is not permitted
+
+- **WHEN** the selected account cannot publish a file from the temporary path to the backup path
+- **THEN** the container exits before starting the application
+- **AND** the English error names the affected path, required operation, effective user and group IDs, and `https://databasus.com/advanced-config/#docker-storage-permissions`
+
+#### Scenario: Mounted path is read-only
+
+- **WHEN** any required mounted path is read-only
+- **THEN** the container exits before starting PostgreSQL or the Databasus application
+- **AND** the log provides the same identity and documentation details
+
+#### Scenario: Data root cannot create control files
+
+- **WHEN** temporary, backup, PostgreSQL data, and socket paths are writable but the data root cannot create a control file
+- **THEN** the container exits before starting PostgreSQL or the Databasus application
+- **AND** the English error identifies the data root and required operation
+
+### Requirement: Existing Docker data remains usable after an image update
+
+The current image SHALL start with persistent data created by versions `v3.54.0`, `v3.55.0`, `v3.55.1`, and `v3.56.0` when the mounted filesystem permits the selected account's required operations. Startup SHALL preserve the metadata database, secret key, application log, existing backup files, resumable nested WAL queues, and the existing PostgreSQL cluster. It SHALL prepare an existing WAL queue recursively and verify directory creation plus non-mutating file opens under the selected account before PostgreSQL or the Databasus application starts.
+
+#### Scenario: Existing installation is updated
+
+- **WHEN** an operator replaces one of the covered earlier images with the current image without adding identity settings
+- **THEN** the current container becomes healthy
+- **AND** the metadata database, secret key, application log, existing backup, nested WAL queue, and PostgreSQL data remain available
### Requirement: Container preserves incompatible-data startup guards
@@ -50,7 +102,7 @@ The container SHALL refuse startup when it detects data at the deprecated Postgr
The repository SHALL provide `make test-filesystems` as the single entry point for the Docker filesystem suite. It SHALL build or accept a local candidate image and run the same cases locally and in a dedicated GitHub Actions job. The job SHALL build and load its own candidate without publishing or transferring it.
-Each positive case SHALL start the real container and perform create, write, read, and remove operations directly under the responsible service account. Each negative case SHALL assert the container or filesystem operation failure. Every case SHALL clean its containers, volumes, networks, mounts, and temporary files.
+Each positive case SHALL start the real container and invoke `databasus --test-storage`, which uses the public local-storage save and delete methods. Each negative case SHALL assert the startup failure and its actionable error. Every case SHALL clean its containers, volumes, networks, mounts, and temporary files.
#### Scenario: Developer runs the complete suite
@@ -69,27 +121,31 @@ Each positive case SHALL start the real container and perform create, write, rea
### Requirement: The matrix covers supported mount behavior
-The suite SHALL cover a bind-mounted data root, a Docker named volume, separate application, temporary, backup, and PostgreSQL mounts, default and custom service IDs, rejected permission layouts, CIFS numeric ownership, and NFS root squash. It SHALL test only the current candidate image and SHALL NOT include version-to-version upgrade fixtures.
-
-The repository SHALL keep an inventory of open and closed Docker filesystem and permission reports. Each report that crosses the shipped container boundary SHALL map to an executable case. Each exclusion SHALL state why the report does not exercise that boundary.
+The suite SHALL cover an ext4 bind-mounted data root, a Docker named volume, separate temporary, backup, and PostgreSQL mounts, automatic and explicit runtime IDs, rejected backup and data-root permission layouts, CIFS numeric ownership and forced file modes, writable NFS with root squash, and upgrades from the covered earlier images. It SHALL verify one non-root numeric identity for all bundled services, bootstrap and runtime PostgreSQL authentication, and restrictive modes for generated credential files.
#### Scenario: Local Docker storage layouts
-- **WHEN** the candidate uses a bind mount, named volume, or separate mounts
-- **THEN** the container becomes healthy and both service accounts can perform their required file operations
+- **WHEN** the candidate uses an ext4 bind mount, named volume, or separate mounts
+- **THEN** the container becomes healthy and the storage command saves and deletes its probe
+
+#### Scenario: Temporary and backup paths use different filesystems
+
+- **WHEN** the temporary and backup paths have different device IDs
+- **THEN** `LocalStorage.SaveFile` succeeds through its supported cross-filesystem path and `LocalStorage.DeleteFile` removes the probe
#### Scenario: CIFS maps numeric ownership
-- **WHEN** a real CIFS fixture presents a mounted path with the configured Databasus identity
-- **THEN** the container becomes healthy and the Databasus account can perform its required file operations
+- **WHEN** a real CIFS fixture presents root ownership, numeric group ownership `999`, directory mode `0770`, and mount-enforced file modes
+- **THEN** the container becomes healthy and completes the storage command
+- **AND** startup skips the root user ID and writes through group `999`
-#### Scenario: NFS backup storage denies ownership changes to container root
+#### Scenario: NFS data storage denies ownership changes to container root
-- **WHEN** a root-squashed NFS fixture is already writable by the configured service identities
-- **THEN** the container becomes healthy with its backup path on NFS
-- **AND** both accounts can perform their required file operations on their assigned mounts
+- **WHEN** a root-squashed NFS data root has no backups directory, rejects ownership and mode changes, remains writable by the selected identity, and local mounts provide PostgreSQL and temporary storage
+- **THEN** the selected identity creates the backups directory and the container becomes healthy
+- **AND** the storage command succeeds without requiring ownership changes
#### Scenario: Mounted path denies required access
-- **WHEN** a mounted path does not permit an operation required by its service account
-- **THEN** the container or the direct account-level probe fails
+- **WHEN** a mounted path does not permit an operation required by the selected identity
+- **THEN** startup fails with the documented actionable error
diff --git a/openspec/specs/internal-postgresql-protection/spec.md b/openspec/specs/internal-postgresql-protection/spec.md
index af557736..b8ba7a23 100644
--- a/openspec/specs/internal-postgresql-protection/spec.md
+++ b/openspec/specs/internal-postgresql-protection/spec.md
@@ -164,25 +164,32 @@ Scheduled healthchecks SHALL test a database already loaded by the system withou
- **WHEN** an HTTP caller requests a direct connection test
- **THEN** the system uses the workspace-authorized path rather than the trusted healthcheck path
-### Requirement: The embedded PostgreSQL instance is isolated from the application account
+### Requirement: The embedded PostgreSQL instance stays private under the shared runtime account
-The embedded PostgreSQL server SHALL create its Unix socket in a directory accessible only to the PostgreSQL operating-system account. Local socket authentication SHALL allow that account through peer authentication and SHALL reject other operating-system accounts. Loopback TCP connections SHALL require SCRAM authentication, and replication connections to the embedded cluster SHALL be rejected.
+The embedded PostgreSQL server SHALL run under the same non-root operating-system account as the Databasus application and Valkey. During bootstrap only, peer mapping SHALL allow that account to administer the PostgreSQL role named `postgres`. After bootstrap, Unix-socket database login SHALL be rejected. Loopback TCP connections SHALL require SCRAM authentication with the generated credential, and replication connections to the embedded cluster SHALL be rejected.
+
+The embedded PostgreSQL and Valkey ports SHALL remain unpublished by the image.
#### Scenario: Application account opens the private socket
-- **WHEN** the Databasus application account attempts to connect through the embedded Unix socket
-- **THEN** filesystem permissions or PostgreSQL authentication rejects the connection
+- **WHEN** the Databasus application account attempts a Unix-socket database login after bootstrap
+- **THEN** PostgreSQL authentication rejects the connection
-#### Scenario: PostgreSQL account performs startup administration
+#### Scenario: Shared runtime account performs startup administration
-- **WHEN** the PostgreSQL operating-system account connects through the private socket during startup
-- **THEN** peer authentication permits the administrative connection
+- **WHEN** the shared `databasus` operating-system account connects as role `postgres` during startup
+- **THEN** the temporary peer mapping permits the administrative connection
#### Scenario: Loopback TCP connection without the generated password
- **WHEN** any process connects to the embedded PostgreSQL server over loopback TCP without the current generated password
- **THEN** SCRAM authentication rejects the connection
+#### Scenario: Application uses the generated password
+
+- **WHEN** Databasus connects to the embedded PostgreSQL server over loopback with the generated password
+- **THEN** PostgreSQL accepts the connection
+
#### Scenario: Replication connection to the embedded cluster
- **WHEN** a client requests a replication connection to the embedded PostgreSQL server
@@ -221,24 +228,3 @@ An operator-supplied connection string that points back to the embedded database
- **WHEN** the operator explicitly supplies the previously published fixed connection string for the embedded database
- **THEN** the application cannot authenticate after startup rotates the internal role's password
- **AND** the operator must remove that explicit value so startup can supply the generated credential
-
-### Requirement: PostgreSQL and application accounts cannot share a UID
-
-Container startup SHALL reject a requested PostgreSQL UID that already belongs to another account in the image. A free custom UID SHALL remain supported.
-
-#### Scenario: PostgreSQL UID collides with the application account
-
-- **WHEN** the operator sets the PostgreSQL UID to the Databasus application account's UID
-- **THEN** the container exits with a non-zero status before starting PostgreSQL
-- **AND** the error identifies the conflicting account without exposing a secret
-
-#### Scenario: PostgreSQL UID collides with another system account
-
-- **WHEN** the requested PostgreSQL UID belongs to any non-PostgreSQL account in the image
-- **THEN** the container exits with a non-zero status
-
-#### Scenario: Free custom PostgreSQL UID
-
-- **WHEN** the operator supplies an unused UID and group ID for PostgreSQL
-- **THEN** the container starts successfully with PostgreSQL running under that UID
-- **AND** the Databasus application account still cannot access the private socket
diff --git a/website/app/(en)/advanced-config/page.tsx b/website/app/(en)/advanced-config/page.tsx
index bc2c17aa..0c3e13a6 100644
--- a/website/app/(en)/advanced-config/page.tsx
+++ b/website/app/(en)/advanced-config/page.tsx
@@ -401,29 +401,45 @@ export default function AdvancedConfigPage() {
<h2 id="docker-storage-permissions">Docker storage permissions</h2>
<p>
- Most installations should keep the baked IDs. Set these variables
- only when a bind mount, CIFS share or NFS export requires specific
- numeric ownership. Values must be base-10 integers from{" "}
- <code>1</code> through <code>4294967294</code>; empty values are
- rejected.
+ Databasus normally selects its numeric user and group IDs from an
+ existing pgdata directory, then from the backups mount or data
+ root, and finally uses <code>999</code>. Set <code>PUID</code> or{" "}
+ <code>PGID</code> only when that automatic choice does not fit your
+ bind mount, CIFS share, or NFS export. Values must be base-10
+ integers from <code>1</code> through <code>4294967294</code>.
</p>
<table>
- <thead><tr><th>Variable</th><th>Default</th><th>Account</th></tr></thead>
+ <thead><tr><th>Variable</th><th>Automatic value</th><th>Account</th></tr></thead>
<tbody>
- <tr><td><code>DATABASUS_PUID</code></td><td><code>65532</code></td><td>Databasus user</td></tr>
- <tr><td><code>DATABASUS_PGID</code></td><td><code>65532</code></td><td>Databasus primary group</td></tr>
- <tr><td><code>POSTGRES_PUID</code></td><td><code>999</code></td><td>PostgreSQL user</td></tr>
- <tr><td><code>POSTGRES_PGID</code></td><td><code>999</code></td><td>PostgreSQL primary group</td></tr>
+ <tr><td><code>PUID</code></td><td>Mounted owner or <code>999</code></td><td><code>databasus</code> user</td></tr>
+ <tr><td><code>PGID</code></td><td>Mounted group or <code>999</code></td><td><code>databasus</code> primary group</td></tr>
</tbody>
</table>
<p>
- Keep application-owned mounts separate from pgdata. The entrypoint
- starts as namespace root, prepares both accounts, then drops
- privileges with <code>gosu</code>. Use rootless Docker or a user
- namespace for host isolation; arbitrary Docker <code>user:</code>{" "}
- overrides are unsupported.
+ Databasus, PostgreSQL, and Valkey use the same non-root operating-system
+ account named <code>databasus</code>.
+ </p>
+
+ <p>
+ The entrypoint starts as root inside the container to select the
+ IDs and attempt <code>chown</code> and <code>chmod</code>. It then
+ checks the actual file lifecycle as <code>databasus</code>. A mount
+ can work even if it rejects metadata changes. An arbitrary Docker{" "}
+ <code>user:</code> override is not supported.
+ </p>
+
+ <pre><code>{`ERROR: Databasus cannot write to local storage paths /databasus-data/temp and /databasus-data/backups as UID 999 and GID 999.
+Required operation: save a file through local storage.
+Set PUID and PGID or fix the mounted directory permissions: https://databasus.com/advanced-config/#docker-storage-permissions
+Details: permission denied`}</code></pre>
+
+ <p>
+ The previous four service-specific identity variables were
+ deliberately removed. Remove them from your configuration when
+ upgrading. If the automatic IDs cannot access a mount, startup
+ stops with the failed operation and this documentation link.
</p>
<h2 id="telemetry">Telemetry</h2>
diff --git a/website/app/[lang]/advanced-config/content/es.tsx b/website/app/[lang]/advanced-config/content/es.tsx
index a63ff7bc..c180eb7a 100644
--- a/website/app/[lang]/advanced-config/content/es.tsx
+++ b/website/app/[lang]/advanced-config/content/es.tsx
@@ -414,29 +414,48 @@ export default function AdvancedConfigPage() {
<h2 id="docker-storage-permissions">Permisos del almacenamiento Docker</h2>
<p>
- La mayoría de las instalaciones debe conservar los ID de la imagen.
- Cámbielos solo si un bind mount o un recurso CIFS o NFS exige un
- propietario numérico concreto. Se aceptan enteros decimales de{" "}
- <code>1</code> a <code>4294967294</code>; los valores vacíos se
- rechazan.
+ Databasus suele tomar los ID numéricos del usuario y del grupo
+ del directorio pgdata existente, después del mount de copias de
+ seguridad o de la raíz de datos y, como último recurso, usa{" "}
+ <code>999</code>. Configure <code>PUID</code> o <code>PGID</code>{" "}
+ solo si esa selección automática no sirve para su bind mount,
+ recurso CIFS o exportación NFS. Deben ser enteros decimales de{" "}
+ <code>1</code> a <code>4294967294</code>.
</p>
<table>
- <thead><tr><th>Variable</th><th>Valor predeterminado</th><th>Cuenta</th></tr></thead>
+ <thead><tr><th>Variable</th><th>Valor automático</th><th>Cuenta</th></tr></thead>
<tbody>
- <tr><td><code>DATABASUS_PUID</code></td><td><code>65532</code></td><td>Usuario de Databasus</td></tr>
- <tr><td><code>DATABASUS_PGID</code></td><td><code>65532</code></td><td>Grupo principal de Databasus</td></tr>
- <tr><td><code>POSTGRES_PUID</code></td><td><code>999</code></td><td>Usuario de PostgreSQL</td></tr>
- <tr><td><code>POSTGRES_PGID</code></td><td><code>999</code></td><td>Grupo principal de PostgreSQL</td></tr>
+ <tr><td><code>PUID</code></td><td>Propietario del mount o <code>999</code></td><td>Usuario <code>databasus</code></td></tr>
+ <tr><td><code>PGID</code></td><td>Grupo del mount o <code>999</code></td><td>Grupo principal <code>databasus</code></td></tr>
</tbody>
</table>
<p>
- Mantenga los mounts de la aplicación separados de pgdata. El
- entrypoint empieza como root dentro de su namespace, prepara
- ambas cuentas y reduce privilegios con <code>gosu</code>. Use
- Docker rootless o un user namespace para aislar el host; no se
- admiten valores arbitrarios de Docker <code>user:</code>.
+ Databasus, PostgreSQL y Valkey usan la misma cuenta del sistema
+ operativo sin privilegios root, llamada <code>databasus</code>.
+ </p>
+
+ <p>
+ El entrypoint comienza como root dentro del contenedor para
+ elegir los ID e intentar ejecutar <code>chown</code> y{" "}
+ <code>chmod</code>. Después comprueba todo el ciclo de archivos
+ como <code>databasus</code>. Un mount puede funcionar aunque
+ rechace cambios de propietario o modo. No se admite un valor
+ arbitrario de Docker <code>user:</code>.
+ </p>
+
+ <pre><code>{`ERROR: Databasus cannot write to local storage paths /databasus-data/temp and /databasus-data/backups as UID 999 and GID 999.
+Required operation: save a file through local storage.
+Set PUID and PGID or fix the mounted directory permissions: https://databasus.com/advanced-config/#docker-storage-permissions
+Details: permission denied`}</code></pre>
+
+ <p>
+ Las cuatro variables anteriores para servicios separados se
+ eliminaron de forma deliberada. Quítelas de la configuración al
+ actualizar. Si los ID elegidos automáticamente no pueden acceder
+ a un mount, el inicio se detiene e indica la operación fallida y
+ el enlace a esta documentación.
</p>
<h2 id="telemetry">Telemetría</h2>
diff --git a/website/app/[lang]/advanced-config/content/fr.tsx b/website/app/[lang]/advanced-config/content/fr.tsx
index 632f4013..d7342cee 100644
--- a/website/app/[lang]/advanced-config/content/fr.tsx
+++ b/website/app/[lang]/advanced-config/content/fr.tsx
@@ -417,29 +417,50 @@ export default function AdvancedConfigPage() {
<h2 id="docker-storage-permissions">Permissions du stockage Docker</h2>
<p>
- La plupart des installations doivent conserver les ID intégrés à
- l&apos;image. Modifiez-les uniquement si un bind mount ou un
- partage CIFS ou NFS impose un propriétaire numérique précis. Les
- entiers décimaux de <code>1</code> à <code>4294967294</code> sont
- acceptés ; les valeurs vides sont refusées.
+ Databasus prend normalement les ID numériques de l&apos;utilisateur
+ et du groupe dans le répertoire pgdata existant, puis dans le
+ mount des sauvegardes ou la racine des données. À défaut, il
+ utilise <code>999</code>. Définissez <code>PUID</code> ou{" "}
+ <code>PGID</code> uniquement si ce choix automatique ne convient
+ pas à votre bind mount, partage CIFS ou export NFS. Les valeurs
+ doivent être des entiers décimaux de <code>1</code> à{" "}
+ <code>4294967294</code>.
</p>
<table>
- <thead><tr><th>Variable</th><th>Valeur par défaut</th><th>Compte</th></tr></thead>
+ <thead><tr><th>Variable</th><th>Valeur automatique</th><th>Compte</th></tr></thead>
<tbody>
- <tr><td><code>DATABASUS_PUID</code></td><td><code>65532</code></td><td>Utilisateur Databasus</td></tr>
- <tr><td><code>DATABASUS_PGID</code></td><td><code>65532</code></td><td>Groupe principal Databasus</td></tr>
- <tr><td><code>POSTGRES_PUID</code></td><td><code>999</code></td><td>Utilisateur PostgreSQL</td></tr>
- <tr><td><code>POSTGRES_PGID</code></td><td><code>999</code></td><td>Groupe principal PostgreSQL</td></tr>
+ <tr><td><code>PUID</code></td><td>Propriétaire du mount ou <code>999</code></td><td>Utilisateur <code>databasus</code></td></tr>
+ <tr><td><code>PGID</code></td><td>Groupe du mount ou <code>999</code></td><td>Groupe principal <code>databasus</code></td></tr>
</tbody>
</table>
<p>
- Séparez les mounts de l&apos;application de pgdata. L&apos;entrypoint
- démarre comme root dans son namespace, prépare les deux comptes,
- puis réduit ses privilèges avec <code>gosu</code>. Utilisez Docker
- rootless ou un user namespace pour isoler l&apos;hôte ; les valeurs
- Docker <code>user:</code> arbitraires ne sont pas prises en charge.
+ Databasus, PostgreSQL et Valkey utilisent le même compte du
+ système d&apos;exploitation sans privilèges root, nommé{" "}
+ <code>databasus</code>.
+ </p>
+
+ <p>
+ L&apos;entrypoint démarre comme root dans le conteneur pour choisir
+ les ID et tenter <code>chown</code> et <code>chmod</code>. Il
+ vérifie ensuite tout le cycle des fichiers sous le compte{" "}
+ <code>databasus</code>. Un mount peut fonctionner même s&apos;il
+ refuse les changements de propriétaire ou de mode. Une valeur
+ Docker <code>user:</code> arbitraire n&apos;est pas prise en charge.
+ </p>
+
+ <pre><code>{`ERROR: Databasus cannot write to local storage paths /databasus-data/temp and /databasus-data/backups as UID 999 and GID 999.
+Required operation: save a file through local storage.
+Set PUID and PGID or fix the mounted directory permissions: https://databasus.com/advanced-config/#docker-storage-permissions
+Details: permission denied`}</code></pre>
+
+ <p>
+ Les quatre anciennes variables propres aux différents services
+ ont été supprimées volontairement. Retirez-les de votre
+ configuration lors de la mise à jour. Si les ID automatiques ne
+ peuvent pas accéder à un mount, le démarrage s&apos;arrête et
+ indique l&apos;opération en échec ainsi que le lien vers cette page.
</p>
<h2 id="telemetry">Télémétrie</h2>
diff --git a/website/app/[lang]/advanced-config/content/pt.tsx b/website/app/[lang]/advanced-config/content/pt.tsx
index 627a0aed..bd8dfe77 100644
--- a/website/app/[lang]/advanced-config/content/pt.tsx
+++ b/website/app/[lang]/advanced-config/content/pt.tsx
@@ -407,29 +407,48 @@ export default function AdvancedConfigPage() {
<h2 id="docker-storage-permissions">Permissões do armazenamento Docker</h2>
<p>
- A maioria das instalações deve manter os IDs da imagem. Altere-os
- apenas quando um bind mount ou compartilhamento CIFS ou NFS exigir
- propriedade numérica específica. São aceitos inteiros decimais de{" "}
- <code>1</code> a <code>4294967294</code>; valores vazios são
- rejeitados.
+ O Databasus normalmente usa os IDs numéricos do usuário e do
+ grupo do diretório pgdata existente, depois do mount de backups
+ ou da raiz de dados e, por fim, usa <code>999</code>. Defina{" "}
+ <code>PUID</code> ou <code>PGID</code> apenas quando essa escolha
+ automática não servir para seu bind mount, compartilhamento CIFS
+ ou exportação NFS. Os valores devem ser inteiros decimais de{" "}
+ <code>1</code> a <code>4294967294</code>.
</p>
<table>
- <thead><tr><th>Variável</th><th>Padrão</th><th>Conta</th></tr></thead>
+ <thead><tr><th>Variável</th><th>Valor automático</th><th>Conta</th></tr></thead>
<tbody>
- <tr><td><code>DATABASUS_PUID</code></td><td><code>65532</code></td><td>Usuário do Databasus</td></tr>
- <tr><td><code>DATABASUS_PGID</code></td><td><code>65532</code></td><td>Grupo principal do Databasus</td></tr>
- <tr><td><code>POSTGRES_PUID</code></td><td><code>999</code></td><td>Usuário do PostgreSQL</td></tr>
- <tr><td><code>POSTGRES_PGID</code></td><td><code>999</code></td><td>Grupo principal do PostgreSQL</td></tr>
+ <tr><td><code>PUID</code></td><td>Proprietário do mount ou <code>999</code></td><td>Usuário <code>databasus</code></td></tr>
+ <tr><td><code>PGID</code></td><td>Grupo do mount ou <code>999</code></td><td>Grupo principal <code>databasus</code></td></tr>
</tbody>
</table>
<p>
- Mantenha os mounts do aplicativo separados do pgdata. O entrypoint
- começa como root dentro do namespace, prepara as duas contas e
- reduz privilégios com <code>gosu</code>. Use Docker rootless ou
- um user namespace para isolar o host; valores arbitrários de
- Docker <code>user:</code> não são aceitos.
+ Databasus, PostgreSQL e Valkey usam a mesma conta do sistema
+ operacional sem privilégios root chamada <code>databasus</code>.
+ </p>
+
+ <p>
+ O entrypoint começa como root dentro do contêiner para escolher
+ os IDs e tentar executar <code>chown</code> e <code>chmod</code>.
+ Em seguida, ele verifica todo o ciclo de arquivos como{" "}
+ <code>databasus</code>. Um mount pode funcionar mesmo que recuse
+ mudanças de proprietário ou modo. Um valor arbitrário de Docker{" "}
+ <code>user:</code> não é aceito.
+ </p>
+
+ <pre><code>{`ERROR: Databasus cannot write to local storage paths /databasus-data/temp and /databasus-data/backups as UID 999 and GID 999.
+Required operation: save a file through local storage.
+Set PUID and PGID or fix the mounted directory permissions: https://databasus.com/advanced-config/#docker-storage-permissions
+Details: permission denied`}</code></pre>
+
+ <p>
+ As quatro variáveis anteriores específicas de cada serviço foram
+ removidas de propósito. Remova-as da configuração ao atualizar.
+ Se os IDs automáticos não conseguirem acessar um mount, a
+ inicialização será interrompida e mostrará a operação que falhou
+ e o link para esta documentação.
</p>
<h2 id="telemetry">Telemetria</h2>
diff --git a/website/app/[lang]/advanced-config/content/ru.tsx b/website/app/[lang]/advanced-config/content/ru.tsx
index 63f9d4f6..c2fa5b31 100644
--- a/website/app/[lang]/advanced-config/content/ru.tsx
+++ b/website/app/[lang]/advanced-config/content/ru.tsx
@@ -404,31 +404,49 @@ export default function AdvancedConfigPage() {
<h2 id="docker-storage-permissions">Права Docker-хранилища</h2>
<p>
- Для большинства установок подходят ID из образа. Меняйте их,
- только если bind mount, CIFS или NFS требуют конкретного числового
- владельца. Допустимы десятичные значения от <code>1</code> до{" "}
- <code>4294967294</code>; пустые значения отклоняются.
+ Обычно Databasus берет числовые ID пользователя и группы у
+ существующего каталога pgdata, затем проверяет mount с бекапами
+ и корневой каталог данных. Если подходящего владельца нет,
+ используется <code>999</code>. Задавайте <code>PUID</code> или{" "}
+ <code>PGID</code>, только когда автоматический выбор не подходит
+ для вашего bind mount, CIFS или NFS. Допустимы десятичные значения
+ от <code>1</code> до <code>4294967294</code>.
</p>
<table>
- <thead><tr><th>Переменная</th><th>По умолчанию</th><th>Учетная запись</th></tr></thead>
+ <thead><tr><th>Переменная</th><th>Автоматическое значение</th><th>Учетная запись</th></tr></thead>
<tbody>
- <tr><td><code>DATABASUS_PUID</code></td><td><code>65532</code></td><td>Пользователь Databasus</td></tr>
- <tr><td><code>DATABASUS_PGID</code></td><td><code>65532</code></td><td>Основная группа Databasus</td></tr>
- <tr><td><code>POSTGRES_PUID</code></td><td><code>999</code></td><td>Пользователь PostgreSQL</td></tr>
- <tr><td><code>POSTGRES_PGID</code></td><td><code>999</code></td><td>Основная группа PostgreSQL</td></tr>
+ <tr><td><code>PUID</code></td><td>Владелец mount или <code>999</code></td><td>Пользователь <code>databasus</code></td></tr>
+ <tr><td><code>PGID</code></td><td>Группа mount или <code>999</code></td><td>Основная группа <code>databasus</code></td></tr>
</tbody>
</table>
<p>
- Не объединяйте точки монтирования приложения с pgdata. Сценарий
- запуска работает с правами root внутри пространства имен,
- настраивает обе учетные записи и сбрасывает привилегии через{" "}
- <code>gosu</code>. Для изоляции на хосте используйте Docker без
- прав root или пространство имен пользователей; произвольное
+ Databasus, PostgreSQL и Valkey работают под одной учетной записью
+ ОС без прав root с именем <code>databasus</code>.
+ </p>
+
+ <p>
+ Entrypoint запускается с правами root внутри контейнера, выбирает
+ ID и пробует выполнить <code>chown</code> и <code>chmod</code>.
+ После этого он проверяет полный цикл работы с файлами от имени{" "}
+ <code>databasus</code>. Mount может работать, даже если файловая
+ система запрещает менять владельца или режим. Произвольное
значение Docker <code>user:</code> не поддерживается.
</p>
+ <pre><code>{`ERROR: Databasus cannot write to local storage paths /databasus-data/temp and /databasus-data/backups as UID 999 and GID 999.
+Required operation: save a file through local storage.
+Set PUID and PGID or fix the mounted directory permissions: https://databasus.com/advanced-config/#docker-storage-permissions
+Details: permission denied`}</code></pre>
+
+ <p>
+ Четыре прежние переменные для отдельных сервисов удалены
+ сознательно. При обновлении уберите их из конфигурации. Если
+ автоматически выбранным ID не хватает прав, контейнер остановится
+ и укажет неудавшуюся операцию вместе со ссылкой на эту инструкцию.
+ </p>
+
<h2 id="telemetry">Телеметрия</h2>
<p>
diff --git a/website/app/[lang]/advanced-config/content/zh.tsx b/website/app/[lang]/advanced-config/content/zh.tsx
index a194a872..c1ac72fc 100644
--- a/website/app/[lang]/advanced-config/content/zh.tsx
+++ b/website/app/[lang]/advanced-config/content/zh.tsx
@@ -386,24 +386,38 @@ export default function AdvancedConfigPage() {
<h2 id="docker-storage-permissions">Docker 存储权限</h2>
<p>
- 大多数安装应保留镜像内置 ID。只有 bind mount、CIFS 或 NFS 共享要求特定数字所有者时才需要修改。可用值是{" "}
- <code>1</code> 到 <code>4294967294</code> 的十进制整数;空值会被拒绝。
+ Databasus 通常先使用现有 pgdata 目录的用户和组 ID,再检查备份 mount 或数据根目录,最后使用{" "}
+ <code>999</code>。只有自动选择不适合你的 bind mount、CIFS 共享或 NFS 导出时,才需要设置{" "}
+ <code>PUID</code> 或 <code>PGID</code>。值必须是从 <code>1</code> 到{" "}
+ <code>4294967294</code> 的十进制整数。
</p>
<table>
- <thead><tr><th>变量</th><th>默认值</th><th>账户</th></tr></thead>
+ <thead><tr><th>变量</th><th>自动值</th><th>账户</th></tr></thead>
<tbody>
- <tr><td><code>DATABASUS_PUID</code></td><td><code>65532</code></td><td>Databasus 用户</td></tr>
- <tr><td><code>DATABASUS_PGID</code></td><td><code>65532</code></td><td>Databasus 主组</td></tr>
- <tr><td><code>POSTGRES_PUID</code></td><td><code>999</code></td><td>PostgreSQL 用户</td></tr>
- <tr><td><code>POSTGRES_PGID</code></td><td><code>999</code></td><td>PostgreSQL 主组</td></tr>
+ <tr><td><code>PUID</code></td><td>mount 所有者或 <code>999</code></td><td><code>databasus</code> 用户</td></tr>
+ <tr><td><code>PGID</code></td><td>mount 组或 <code>999</code></td><td><code>databasus</code> 主组</td></tr>
</tbody>
</table>
<p>
- 请将应用 mount 与 pgdata 分开。Entrypoint 会先以 namespace 内的 root 身份启动,准备两个账户,再通过{" "}
- <code>gosu</code> 降低权限。若要隔离宿主机,请使用 rootless Docker 或 user namespace;不支持任意 Docker{" "}
- <code>user:</code> 覆盖。
+ Databasus、PostgreSQL 和 Valkey 使用同一个名为 <code>databasus</code> 的无 root 权限操作系统账户。
+ </p>
+
+ <p>
+ Entrypoint 先以容器内的 root 身份启动,用于选择 ID 并尝试执行 <code>chown</code> 和{" "}
+ <code>chmod</code>。随后,它会以 <code>databasus</code> 身份检查完整的文件生命周期。即使 mount
+ 拒绝更改所有者或模式,只要实际文件操作成功,容器仍可运行。不支持任意 Docker <code>user:</code> 覆盖。
+ </p>
+
+ <pre><code>{`ERROR: Databasus cannot write to local storage paths /databasus-data/temp and /databasus-data/backups as UID 999 and GID 999.
+Required operation: save a file through local storage.
+Set PUID and PGID or fix the mounted directory permissions: https://databasus.com/advanced-config/#docker-storage-permissions
+Details: permission denied`}</code></pre>
+
+ <p>
+ 之前用于不同服务的四个变量已被有意删除。升级时请从配置中移除这些变量。如果自动选择的 ID
+ 无法访问 mount,启动会停止,并显示失败的操作以及本文档链接。
</p>
<h2 id="telemetry">遥测</h2>