Skip to content

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

IMPROVE (security): Harden embedded PostgreSQL isolation

Rostislav Dugin61fe8dd8769d
diff --git a/Dockerfile b/Dockerfile
index 2ba4d899..1e9ac8ef 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -234,6 +234,12 @@ PGID=\${PGID:-999}
CURRENT_UID=\$(id -u postgres)
CURRENT_GID=\$(id -g postgres)
+PUID_OWNER=\$(getent passwd "\$PUID" | cut -d: -f1 || true)
+
+if [ -n "\$PUID_OWNER" ] && [ "\$PUID_OWNER" != "postgres" ]; then
+ echo "ERROR: PUID \$PUID is already assigned to user \$PUID_OWNER. Choose an unused UID for postgres."
+ exit 1
+fi
if [ "\$CURRENT_GID" != "\$PGID" ]; then
echo "Adjusting postgres group GID from \$CURRENT_GID to \$PGID..."
@@ -282,6 +288,7 @@ fi
# Ensure proper ownership of data directory
echo "Setting up data directory permissions..."
mkdir -p /databasus-data/pgdata
+mkdir -p /databasus-data/pgsocket
mkdir -p /databasus-data/temp
mkdir -p /databasus-data/backups
chown databasus:databasus /databasus-data
@@ -289,11 +296,13 @@ chown databasus:databasus /databasus-data
# bind-mounted host directory can arrive without a group traversal bit.
chmod g+x /databasus-data
chown -R postgres:postgres /databasus-data/pgdata
+chown postgres:postgres /databasus-data/pgsocket
chown -R databasus:databasus /databasus-data/temp /databasus-data/backups
# Upgrade path: secret.key and instance.json may be owned by root or postgres
# from older images. Re-own them so the non-root main process can read/write.
chown databasus:databasus /databasus-data/secret.key /databasus-data/instance.json 2>/dev/null || true
chmod 700 /databasus-data/temp
+chmod 700 /databasus-data/pgsocket
# ========= Start Valkey (internal cache) =========
echo "Configuring Valkey cache..."
@@ -325,28 +334,40 @@ if [ ! -s "/databasus-data/pgdata/PG_VERSION" ]; then
gosu postgres \$PG_BIN/initdb -D /databasus-data/pgdata --encoding=UTF8 --locale=C.UTF-8
# Configure PostgreSQL
- echo "host all all 127.0.0.1/32 md5" >> /databasus-data/pgdata/pg_hba.conf
- echo "local all all trust" >> /databasus-data/pgdata/pg_hba.conf
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..."
- # -k /tmp: create Unix socket and lock file in /tmp instead of /var/run/postgresql/.
- # On NAS systems (e.g. TrueNAS Scale), the ZFS-backed Docker overlay filesystem
- # ignores chown/chmod on directories from image layers, so PostgreSQL gets
- # "Permission denied" when creating .s.PGSQL.5437.lock in /var/run/postgresql/.
- # All internal connections use TCP (-h localhost), so the socket location does not matter.
- gosu postgres \$PG_BIN/postgres -D /databasus-data/pgdata -p 5437 -k /tmp &
+ 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 localhost >/dev/null 2>&1; then
+ 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
@@ -403,26 +424,38 @@ fi
# Create database and set password for postgres user
echo "Setting up database and user..."
-gosu postgres \$PG_BIN/psql -p 5437 -h localhost -d postgres << 'SQL'
-
--- We use stub password, because internal DB is not exposed outside container
-ALTER USER postgres WITH PASSWORD 'Q1234567';
+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
+
# ========= Refuse to start if legacy WAL backup data exists =========
# The agent-based WAL_V1 backup type was removed. Existing installs with
# WAL-mode databases must downgrade, manually remove them and then upgrade.
echo "Checking for legacy WAL backup configuration..."
-WAL_CHECK_DSN="postgres://postgres:Q1234567@localhost:5437/databasus"
-
-WAL_CHECK_COL=\$(gosu databasus \$PG_BIN/psql "\$WAL_CHECK_DSN" -tA -c "SELECT 1 FROM information_schema.columns WHERE table_name='postgresql_databases' AND column_name='backup_type' LIMIT 1" 2>/dev/null || true)
+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 \$PG_BIN/psql "\$WAL_CHECK_DSN" -tA -c "SELECT 1 FROM postgresql_databases WHERE backup_type='WAL_V1' LIMIT 1" 2>/dev/null || true)
+ 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 "=========================================="
diff --git a/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go
index 97596f54..d3db88f7 100644
--- a/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go
+++ b/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go
@@ -367,7 +367,7 @@ func (uc *CreatePostgresqlBackupUsecase) buildPgDumpArgs(pg *pgtypes.PostgresqlL
"-h", pg.Host,
"-p", strconv.Itoa(pg.Port),
"-U", pg.Username,
- "-d", *pg.Database,
+ "-d", postgresql_shared.BuildDatabaseNameConninfo(*pg.Database),
"--verbose",
}
diff --git a/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc_test.go b/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc_test.go
new file mode 100644
index 00000000..9baf80b4
--- /dev/null
+++ b/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc_test.go
@@ -0,0 +1,40 @@
+package usecases_logical_postgresql
+
+import (
+ "io"
+ "log/slog"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ pgtypes "databasus-backend/internal/features/databases/databases/postgresql/logical"
+ "databasus-backend/internal/util/tools"
+)
+
+func Test_BuildPgDumpArgs_TreatsDuplicateParameterAsLiteralDatabaseName(t *testing.T) {
+ databaseName := "postgres dbname=databasus"
+ postgresDatabase := &pgtypes.PostgresqlLogicalDatabase{
+ Version: tools.PostgresqlVersion17,
+ Host: "localhost",
+ Port: 5437,
+ Username: "postgres",
+ Database: &databaseName,
+ }
+
+ usecase := &CreatePostgresqlBackupUsecase{
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ }
+ args := usecase.buildPgDumpArgs(postgresDatabase)
+
+ databaseArgumentIndex := -1
+ for argumentIndex, argument := range args {
+ if argument == "-d" {
+ databaseArgumentIndex = argumentIndex + 1
+ break
+ }
+ }
+
+ require.Less(t, databaseArgumentIndex, len(args))
+ require.GreaterOrEqual(t, databaseArgumentIndex, 0)
+ require.Equal(t, "dbname='postgres dbname=databasus'", args[databaseArgumentIndex])
+}
diff --git a/backend/internal/features/databases/controller.go b/backend/internal/features/databases/controller.go
index 66b81fcc..f47e91f7 100644
--- a/backend/internal/features/databases/controller.go
+++ b/backend/internal/features/databases/controller.go
@@ -255,9 +255,11 @@ func (c *DatabaseController) TestDatabaseConnection(ctx *gin.Context) {
// @Success 200
// @Failure 400 {object} map[string]string
// @Failure 401
+// @Failure 403 {object} map[string]string
+// @Failure 500 {object} map[string]string
// @Router /databases/test-connection-direct [post]
func (c *DatabaseController) TestDatabaseConnectionDirect(ctx *gin.Context) {
- _, ok := users_middleware.GetUserFromContext(ctx)
+ user, ok := users_middleware.GetUserFromContext(ctx)
if !ok {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
return
@@ -269,7 +271,7 @@ func (c *DatabaseController) TestDatabaseConnectionDirect(ctx *gin.Context) {
return
}
- if err := c.databaseService.TestDatabaseConnectionDirect(ctx.Request.Context(), &request); err != nil {
+ if err := c.databaseService.TestDatabaseConnectionDirect(ctx.Request.Context(), user, &request); err != nil {
respondConnectionTestError(ctx, err)
return
}
@@ -277,9 +279,22 @@ func (c *DatabaseController) TestDatabaseConnectionDirect(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "connection successful"})
}
-// respondConnectionTestError writes a 400 carrying the machine-readable code for a classified
-// connection failure (physical PostgreSQL), or a plain error message for any other failure.
func respondConnectionTestError(ctx *gin.Context, err error) {
+ if errors.Is(err, ErrInsufficientPermissionsToTestDatabaseConnection) {
+ ctx.JSON(http.StatusForbidden, gin.H{"error": ErrInsufficientPermissionsToTestDatabaseConnection.Error()})
+ return
+ }
+
+ if errors.Is(err, ErrDatabaseConnectionTargetLookup) {
+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": ErrDatabaseConnectionTargetLookup.Error()})
+ return
+ }
+
+ if errors.Is(err, ErrDatabaseConnectionAuthorizationLookup) {
+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": ErrDatabaseConnectionAuthorizationLookup.Error()})
+ return
+ }
+
if connErr, ok := errors.AsType[*postgresql_shared.ConnectionTestError](err); ok {
ctx.JSON(http.StatusBadRequest, gin.H{"code": connErr.Code})
return
diff --git a/backend/internal/features/databases/controller_test.go b/backend/internal/features/databases/controller_test.go
index 06acf508..7a7b2ef9 100644
--- a/backend/internal/features/databases/controller_test.go
+++ b/backend/internal/features/databases/controller_test.go
@@ -3,6 +3,7 @@ package databases
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"net"
"net/http"
@@ -33,6 +34,7 @@ import (
"databasus-backend/internal/features/storages"
users_enums "databasus-backend/internal/features/users/enums"
users_middleware "databasus-backend/internal/features/users/middleware"
+ users_models "databasus-backend/internal/features/users/models"
users_services "databasus-backend/internal/features/users/services"
users_testing "databasus-backend/internal/features/users/testing"
workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"
@@ -2139,6 +2141,293 @@ func getConnectionErrorCode(t *testing.T, body []byte) postgresql_shared.Connect
return payload.Code
}
+func createDatabaseForDirectConnectionTest(
+ t *testing.T,
+ router *gin.Engine,
+ workspaceID uuid.UUID,
+ ownerToken string,
+) *Database {
+ t.Helper()
+
+ request := Database{
+ Name: "Direct connection test database",
+ WorkspaceID: &workspaceID,
+ Type: DatabaseTypePostgresLogical,
+ PostgresqlLogical: getTestPostgresConfig(),
+ }
+
+ var createdDatabase Database
+ test_utils.MakePostRequestAndUnmarshal(
+ t,
+ router,
+ "/api/v1/databases/create",
+ "Bearer "+ownerToken,
+ request,
+ http.StatusCreated,
+ &createdDatabase,
+ )
+
+ t.Cleanup(func() {
+ RemoveTestDatabase(t.Context(), &createdDatabase)
+ })
+
+ return &createdDatabase
+}
+
+type connectionTestDatabaseStore struct {
+ databaseStore
+ database *Database
+ findError error
+}
+
+func (s *connectionTestDatabaseStore) FindByID(_ uuid.UUID) (*Database, error) {
+ return s.database, s.findError
+}
+
+type connectionTestWorkspaceService struct {
+ workspaceService
+ permissionError error
+}
+
+func (s *connectionTestWorkspaceService) CanUserManageDBs(
+ _ context.Context,
+ _ uuid.UUID,
+ _ *users_models.User,
+) (bool, error) {
+ return false, s.permissionError
+}
+
+func createDirectConnectionErrorTestRouter(
+ databaseStore databaseStore,
+ workspaceService workspaceService,
+ user *users_models.User,
+) *gin.Engine {
+ service := &DatabaseService{
+ databaseStore,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ workspaceService,
+ nil,
+ nil,
+ nil,
+ }
+ controller := &DatabaseController{service, nil, nil}
+ router := gin.New()
+ router.POST("/api/v1/databases/test-connection-direct", func(ctx *gin.Context) {
+ ctx.Set("user", user)
+ controller.TestDatabaseConnectionDirect(ctx)
+ })
+
+ return router
+}
+
+func Test_TestDatabaseConnectionDirect_WhenSavedDatabaseLookupFails_ReturnsSanitizedError(t *testing.T) {
+ user := &users_models.User{ID: uuid.New(), Role: users_enums.UserRoleMember}
+ router := createDirectConnectionErrorTestRouter(
+ &connectionTestDatabaseStore{findError: errors.New("sensitive repository failure")},
+ &connectionTestWorkspaceService{},
+ user,
+ )
+ request := Database{ID: uuid.New()}
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/databases/test-connection-direct",
+ "",
+ request,
+ http.StatusInternalServerError,
+ )
+
+ assert.JSONEq(t, `{"error":"failed to load database connection target"}`, string(response.Body))
+}
+
+func Test_TestDatabaseConnectionDirect_WhenPermissionLookupFails_ReturnsSanitizedError(t *testing.T) {
+ workspaceID := uuid.New()
+ user := &users_models.User{ID: uuid.New(), Role: users_enums.UserRoleMember}
+ permissionError := errors.New("sensitive membership failure")
+ testCases := []struct {
+ name string
+ databaseStore databaseStore
+ request Database
+ }{
+ {
+ name: "ad hoc database",
+ databaseStore: &connectionTestDatabaseStore{},
+ request: Database{WorkspaceID: &workspaceID},
+ },
+ {
+ name: "saved database",
+ databaseStore: &connectionTestDatabaseStore{database: &Database{
+ ID: uuid.New(),
+ WorkspaceID: &workspaceID,
+ }},
+ request: Database{ID: uuid.New()},
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ router := createDirectConnectionErrorTestRouter(
+ testCase.databaseStore,
+ &connectionTestWorkspaceService{permissionError: permissionError},
+ user,
+ )
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/databases/test-connection-direct",
+ "",
+ testCase.request,
+ http.StatusInternalServerError,
+ )
+
+ assert.JSONEq(t,
+ `{"error":"failed to verify database connection permissions"}`,
+ string(response.Body),
+ )
+ })
+ }
+}
+
+func Test_TestDatabaseConnectionDirect_WithoutWorkspace_ReturnsBadRequest(t *testing.T) {
+ router := createTestRouter()
+ user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ request := Database{
+ Name: "Direct connection test database",
+ Type: DatabaseTypePostgresLogical,
+ PostgresqlLogical: getTestPostgresConfig(),
+ }
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/databases/test-connection-direct",
+ "Bearer "+user.Token,
+ request,
+ http.StatusBadRequest,
+ )
+
+ assert.JSONEq(t, `{"error":"workspaceId is required"}`, string(response.Body))
+}
+
+func Test_TestDatabaseConnectionDirect_ForUnauthorizedSavedDatabase_ReturnsForbidden(t *testing.T) {
+ testCases := []struct {
+ name string
+ shouldAddToWorkspace bool
+ unauthorizedRole users_enums.WorkspaceRole
+ }{
+ {
+ name: "workspace viewer",
+ shouldAddToWorkspace: true,
+ unauthorizedRole: users_enums.WorkspaceRoleViewer,
+ },
+ {
+ name: "nonmember",
+ shouldAddToWorkspace: false,
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ router := createTestRouter()
+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Direct Test Workspace", owner, router)
+ t.Cleanup(func() {
+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
+ })
+
+ createdDatabase := createDatabaseForDirectConnectionTest(t, router, workspace.ID, owner.Token)
+ unauthorizedUser := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ if testCase.shouldAddToWorkspace {
+ workspaces_testing.AddMemberToWorkspace(
+ workspace,
+ unauthorizedUser,
+ testCase.unauthorizedRole,
+ owner.Token,
+ router,
+ )
+ }
+
+ createdDatabase.PostgresqlLogical.Host = "127.0.0.1"
+ createdDatabase.PostgresqlLogical.Port = 1
+ createdDatabase.PostgresqlLogical.Password = ""
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/databases/test-connection-direct",
+ "Bearer "+unauthorizedUser.Token,
+ createdDatabase,
+ http.StatusForbidden,
+ )
+
+ assert.JSONEq(t,
+ `{"error":"insufficient permissions to test this database connection"}`,
+ string(response.Body),
+ )
+ })
+ }
+}
+
+func Test_TestDatabaseConnectionDirect_ForUnknownDatabase_ReturnsForbidden(t *testing.T) {
+ router := createTestRouter()
+ user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ request := Database{
+ ID: uuid.New(),
+ Name: "Unknown database",
+ Type: DatabaseTypePostgresLogical,
+ PostgresqlLogical: getTestPostgresConfig(),
+ }
+
+ response := test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/databases/test-connection-direct",
+ "Bearer "+user.Token,
+ request,
+ http.StatusForbidden,
+ )
+
+ assert.JSONEq(t,
+ `{"error":"insufficient permissions to test this database connection"}`,
+ string(response.Body),
+ )
+}
+
+func Test_TestDatabaseConnectionDirect_ForWorkspaceMember_ReturnsSuccess(t *testing.T) {
+ router := createTestRouter()
+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Direct Test Workspace", owner, router)
+ t.Cleanup(func() {
+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
+ })
+
+ createdDatabase := createDatabaseForDirectConnectionTest(t, router, workspace.ID, owner.Token)
+ member := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ workspaces_testing.AddMemberToWorkspace(
+ workspace,
+ member,
+ users_enums.WorkspaceRoleMember,
+ owner.Token,
+ router,
+ )
+
+ test_utils.MakePostRequest(
+ t,
+ router,
+ "/api/v1/databases/test-connection-direct",
+ "Bearer "+member.Token,
+ createdDatabase,
+ http.StatusOK,
+ )
+}
+
func Test_TestDatabaseConnectionDirect_ForWalStreamWhenRoleCannotSwitchWal_ReturnsNoWalSwitchPrivilegeCode(
t *testing.T,
) {
diff --git a/backend/internal/features/databases/databases/postgresql/logical/model.go b/backend/internal/features/databases/databases/postgresql/logical/model.go
index 034ccc32..1c4adfcc 100644
--- a/backend/internal/features/databases/databases/postgresql/logical/model.go
+++ b/backend/internal/features/databases/databases/postgresql/logical/model.go
@@ -112,19 +112,8 @@ func (p *PostgresqlLogicalDatabase) Validate() error {
return err
}
- // Prevent Databasus from backing up itself
- // Databasus runs an internal PostgreSQL instance that should not be backed up through the UI
- // because it would expose internal metadata to non-system administrators.
- // To properly backup Databasus, see: https://databasus.com/faq#backup-databasus
- // Only a remote bastion relaxes it: there a loopback address names a database on the bastion,
- // whereas a bastion on this machine would forward straight back to the instance being guarded.
- if !p.isReachedThroughARemoteBastion() &&
- p.Database != nil &&
- isLocalhostAddress(p.Host) &&
- strings.EqualFold(*p.Database, "databasus") {
- return errors.New(
- "backing up Databasus internal database is not allowed. To backup Databasus itself, see https://databasus.com/faq#backup-databasus",
- )
+ if err := p.ValidateNotEmbeddedTarget(); err != nil {
+ return err
}
return nil
@@ -896,6 +885,21 @@ func (p *PostgresqlLogicalDatabase) CreateReadOnlyUser(
return "", "", errors.New("failed to generate unique username after 3 attempts")
}
+func (p *PostgresqlLogicalDatabase) ValidateNotEmbeddedTarget() error {
+ databaseName := ""
+ if p.Database != nil {
+ databaseName = *p.Database
+ }
+
+ return postgresql_shared.ValidateNotEmbeddedTarget(postgresql_shared.EmbeddedTargetSpec{
+ Host: p.Host,
+ Port: p.Port,
+ DatabaseName: databaseName,
+ IsSSHTunnelEnabled: p.SshTunnel.IsEnabled,
+ SSHBastionHost: p.SshTunnel.Host,
+ })
+}
+
func (p *PostgresqlLogicalDatabase) validateSslConfig() error {
return postgresql_shared.ValidateSslConfig(
p.SslMode,
@@ -988,28 +992,3 @@ func extractSupabaseProjectID(username string) string {
}
return ""
}
-
-func (p *PostgresqlLogicalDatabase) isReachedThroughARemoteBastion() bool {
- return p.SshTunnel.IsEnabled && !isLocalhostAddress(p.SshTunnel.Host)
-}
-
-func isLocalhostAddress(host string) bool {
- localhostHosts := []string{
- "localhost",
- "127.0.0.1",
- "172.17.0.1",
- "host.docker.internal",
- "::1", // IPv6 loopback (equivalent to 127.0.0.1)
- "::", // IPv6 all interfaces (equivalent to 0.0.0.0)
- "0.0.0.0", // IPv4 all interfaces
- }
-
- for _, localhostHost := range localhostHosts {
- if strings.EqualFold(host, localhostHost) {
- return true
- }
- }
-
- // The entire 127.0.0.0/8 loopback range, not just 127.0.0.1
- return strings.HasPrefix(host, "127.")
-}
diff --git a/backend/internal/features/databases/databases/postgresql/logical/model_test.go b/backend/internal/features/databases/databases/postgresql/logical/model_test.go
index 1daa265c..a492b08c 100644
--- a/backend/internal/features/databases/databases/postgresql/logical/model_test.go
+++ b/backend/internal/features/databases/databases/postgresql/logical/model_test.go
@@ -1151,6 +1151,12 @@ func Test_Validate_WhenLocalhostAndDatabasus_ReturnsError(t *testing.T) {
username: "postgres",
database: "databasus",
},
+ {
+ name: "Unix socket with databasus db",
+ host: "/tmp",
+ username: "postgres",
+ database: "databasus",
+ },
}
for _, tc := range testCases {
@@ -1165,7 +1171,7 @@ func Test_Validate_WhenLocalhostAndDatabasus_ReturnsError(t *testing.T) {
}
err := pgModel.Validate()
- assert.Error(t, err)
+ require.Error(t, err)
assert.Contains(t, err.Error(), "backing up Databasus internal database is not allowed")
assert.Contains(t, err.Error(), "https://databasus.com/faq#backup-databasus")
})
diff --git a/backend/internal/features/databases/databases/postgresql/logical/tunnel.go b/backend/internal/features/databases/databases/postgresql/logical/tunnel.go
index 1ba092c7..d0c2d60d 100644
--- a/backend/internal/features/databases/databases/postgresql/logical/tunnel.go
+++ b/backend/internal/features/databases/databases/postgresql/logical/tunnel.go
@@ -25,6 +25,12 @@ type TunneledDatabase struct {
// Ctx bounds opening the tunnel; the forwarder then lives until Close. With the tunnel disabled
// this still returns a usable wrapper around the original, so callers never branch.
func OpenTunnel(ctx context.Context, spec OpenTunnelSpec) (*TunneledDatabase, error) {
+ if spec.Database != nil {
+ if err := spec.Database.ValidateNotEmbeddedTarget(); err != nil {
+ return nil, err
+ }
+ }
+
if spec.Database == nil || !spec.Database.SshTunnel.IsEnabled {
return &TunneledDatabase{original: spec.Database, databaseThroughTunnel: spec.Database}, nil
}
diff --git a/backend/internal/features/databases/databases/postgresql/logical/tunnel_test.go b/backend/internal/features/databases/databases/postgresql/logical/tunnel_test.go
index b2b18b3a..6eb60c5b 100644
--- a/backend/internal/features/databases/databases/postgresql/logical/tunnel_test.go
+++ b/backend/internal/features/databases/databases/postgresql/logical/tunnel_test.go
@@ -61,6 +61,19 @@ func Test_OpenTunnel_WhenTheTunnelIsDisabled_HandsBackTheSameDatabase(t *testing
assert.Same(t, database, tunneledDatabase.GetDatabaseThroughTunnel())
}
+func Test_OpenTunnel_WhenTheStoredTargetIsEmbedded_ReturnsError(t *testing.T) {
+ databaseName := "databasus"
+ database := enabledTunnelDatabase()
+ database.Host = "/tmp"
+ database.Port = 5437
+ database.Database = &databaseName
+ database.SshTunnel.IsEnabled = false
+
+ _, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})
+
+ require.ErrorContains(t, err, "backing up Databasus internal database is not allowed")
+}
+
func Test_OpenTunnel_WhenTheBastionIsUnreachable_ReturnsAnError(t *testing.T) {
database := enabledTunnelDatabase()
// RFC 5737 TEST-NET-1: routable nowhere, so this fails to connect rather than resolving.
diff --git a/backend/internal/features/databases/databases/postgresql/physical/model.go b/backend/internal/features/databases/databases/postgresql/physical/model.go
index 495878b2..bff923ca 100644
--- a/backend/internal/features/databases/databases/postgresql/physical/model.go
+++ b/backend/internal/features/databases/databases/postgresql/physical/model.go
@@ -91,6 +91,10 @@ func (p *PostgresqlPhysicalDatabase) Validate() error {
return err
}
+ if err := p.ValidateNotEmbeddedTarget(); err != nil {
+ return err
+ }
+
switch p.BackupType {
case BackupTypeFullOnly, BackupTypeFullAndIncremental, BackupTypeFullIncrementalAndWalStream:
case "":
@@ -102,6 +106,16 @@ func (p *PostgresqlPhysicalDatabase) Validate() error {
return nil
}
+func (p *PostgresqlPhysicalDatabase) ValidateNotEmbeddedTarget() error {
+ return postgresql_shared.ValidateNotEmbeddedTarget(postgresql_shared.EmbeddedTargetSpec{
+ Host: p.Host,
+ Port: p.Port,
+ IsPhysical: true,
+ IsSSHTunnelEnabled: p.SshTunnel.IsEnabled,
+ SSHBastionHost: p.SshTunnel.Host,
+ })
+}
+
func (p *PostgresqlPhysicalDatabase) ValidateUpdate(old *PostgresqlPhysicalDatabase) error {
if old == nil {
return nil
diff --git a/backend/internal/features/databases/databases/postgresql/physical/model_test.go b/backend/internal/features/databases/databases/postgresql/physical/model_test.go
index 686521a2..222b25de 100644
--- a/backend/internal/features/databases/databases/postgresql/physical/model_test.go
+++ b/backend/internal/features/databases/databases/postgresql/physical/model_test.go
@@ -107,6 +107,14 @@ func openTestConnAt(t *testing.T, host string, port int) *pgx.Conn {
return conn
}
+func Test_Validate_EmbeddedPhysicalDatabase_ReturnsError(t *testing.T) {
+ physicalDatabase := newTestModelAt(t, "/tmp", 5437)
+
+ err := physicalDatabase.Validate()
+
+ require.ErrorContains(t, err, "backing up Databasus internal PostgreSQL cluster is not allowed")
+}
+
func createTempUser(t *testing.T, conn *pgx.Conn, extraAttrs string) (string, string) {
t.Helper()
diff --git a/backend/internal/features/databases/databases/postgresql/physical/tunnel.go b/backend/internal/features/databases/databases/postgresql/physical/tunnel.go
index 43853c2c..cabcd4e4 100644
--- a/backend/internal/features/databases/databases/postgresql/physical/tunnel.go
+++ b/backend/internal/features/databases/databases/postgresql/physical/tunnel.go
@@ -25,6 +25,12 @@ type TunneledDatabase struct {
// Ctx bounds opening the tunnel; the forwarder then lives until Close. With the tunnel disabled
// this still returns a usable wrapper around the original, so callers never branch.
func OpenTunnel(ctx context.Context, spec OpenTunnelSpec) (*TunneledDatabase, error) {
+ if spec.Database != nil {
+ if err := spec.Database.ValidateNotEmbeddedTarget(); err != nil {
+ return nil, err
+ }
+ }
+
if spec.Database == nil || !spec.Database.SshTunnel.IsEnabled {
return &TunneledDatabase{original: spec.Database, databaseThroughTunnel: spec.Database}, nil
}
diff --git a/backend/internal/features/databases/databases/postgresql/physical/tunnel_test.go b/backend/internal/features/databases/databases/postgresql/physical/tunnel_test.go
index a2d87757..56ffb7c3 100644
--- a/backend/internal/features/databases/databases/postgresql/physical/tunnel_test.go
+++ b/backend/internal/features/databases/databases/postgresql/physical/tunnel_test.go
@@ -66,6 +66,17 @@ func Test_OpenTunnel_WhenTheTunnelIsDisabled_HandsBackTheSameDatabase(t *testing
assert.Same(t, database, tunneledDatabase.GetDatabaseThroughTunnel())
}
+func Test_OpenTunnel_WhenTheStoredTargetIsEmbedded_ReturnsError(t *testing.T) {
+ database := enabledTunnelDatabase()
+ database.Host = "/tmp"
+ database.Port = 5437
+ database.SshTunnel.IsEnabled = false
+
+ _, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})
+
+ require.ErrorContains(t, err, "backing up Databasus internal PostgreSQL cluster is not allowed")
+}
+
func Test_OpenTunnel_WhenTheBastionIsUnreachable_ReturnsAnError(t *testing.T) {
database := enabledTunnelDatabase()
// RFC 5737 TEST-NET-1: routable nowhere, so this fails to connect rather than resolving.
diff --git a/backend/internal/features/databases/databases/postgresql/shared/credentials.go b/backend/internal/features/databases/databases/postgresql/shared/credentials.go
index 0a62d075..96f7dd26 100644
--- a/backend/internal/features/databases/databases/postgresql/shared/credentials.go
+++ b/backend/internal/features/databases/databases/postgresql/shared/credentials.go
@@ -85,13 +85,13 @@ func buildConnString(
files *CredentialTempFiles,
) string {
connStr := fmt.Sprintf(
- "host=%s port=%d user=%s password='%s' dbname=%s sslmode=%s",
- getConnectHost(spec),
+ "host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
+ quoteConninfoValue(getConnectHost(spec)),
spec.Port,
- spec.Username,
- escapeConnStringValue(password),
- dbName,
- sslModeOrDefault(spec),
+ quoteConninfoValue(spec.Username),
+ quoteConninfoValue(password),
+ quoteConninfoValue(dbName),
+ quoteConninfoValue(string(sslModeOrDefault(spec))),
)
connStr += " default_query_exec_mode=simple_protocol standard_conforming_strings=on client_encoding=UTF8"
@@ -108,13 +108,13 @@ func buildPhysicalReplicationConnString(
files *CredentialTempFiles,
) string {
connStr := fmt.Sprintf(
- "host=%s port=%d user=%s password='%s' dbname=%s sslmode=%s replication=true",
- getConnectHost(spec),
+ "host=%s port=%d user=%s password=%s dbname=%s sslmode=%s replication=true",
+ quoteConninfoValue(getConnectHost(spec)),
spec.Port,
- spec.Username,
- escapeConnStringValue(password),
- dbName,
- sslModeOrDefault(spec),
+ quoteConninfoValue(spec.Username),
+ quoteConninfoValue(password),
+ quoteConninfoValue(dbName),
+ quoteConninfoValue(string(sslModeOrDefault(spec))),
)
return appendSslFilePaths(connStr, files)
@@ -204,15 +204,15 @@ func appendSslFilePaths(connStr string, files *CredentialTempFiles) string {
}
if files.ClientCertPath != "" {
- connStr += fmt.Sprintf(" sslcert='%s'", escapeConnStringValue(files.ClientCertPath))
+ connStr += fmt.Sprintf(" sslcert=%s", quoteConninfoValue(files.ClientCertPath))
}
if files.ClientKeyPath != "" {
- connStr += fmt.Sprintf(" sslkey='%s'", escapeConnStringValue(files.ClientKeyPath))
+ connStr += fmt.Sprintf(" sslkey=%s", quoteConninfoValue(files.ClientKeyPath))
}
if files.RootCertPath != "" {
- connStr += fmt.Sprintf(" sslrootcert='%s'", escapeConnStringValue(files.RootCertPath))
+ connStr += fmt.Sprintf(" sslrootcert=%s", quoteConninfoValue(files.RootCertPath))
}
return connStr
@@ -285,9 +285,13 @@ func (f *CredentialTempFiles) writeCert(
return path, nil
}
-func escapeConnStringValue(value string) string {
+func quoteConninfoValue(value string) string {
value = strings.ReplaceAll(value, `\`, `\\`)
value = strings.ReplaceAll(value, `'`, `\'`)
- return value
+ return "'" + value + "'"
+}
+
+func BuildDatabaseNameConninfo(databaseName string) string {
+ return "dbname=" + quoteConninfoValue(databaseName)
}
diff --git a/backend/internal/features/databases/databases/postgresql/shared/credentials_test.go b/backend/internal/features/databases/databases/postgresql/shared/credentials_test.go
new file mode 100644
index 00000000..f69d8b10
--- /dev/null
+++ b/backend/internal/features/databases/databases/postgresql/shared/credentials_test.go
@@ -0,0 +1,34 @@
+package postgresql_shared
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_BuildConnConfig_TreatsCredentialFieldsAsLiteralValues(t *testing.T) {
+ spec := CredentialSpec{
+ Host: "db host=attacker\\socket'one",
+ Port: 5432,
+ Username: "user name=postgres\\role'one",
+ SslMode: PostgresSslModeDisable,
+ }
+ databaseName := "postgres dbname=databasus\\archive'one"
+ password := "secret password=overridden\\value'one"
+
+ connConfig, err := BuildConnConfig(spec, password, databaseName, nil)
+ require.NoError(t, err)
+ require.Equal(t, spec.Host, connConfig.Host)
+ require.Equal(t, spec.Username, connConfig.User)
+ require.Equal(t, databaseName, connConfig.Database)
+ require.Equal(t, password, connConfig.Password)
+}
+
+func Test_BuildDatabaseNameConninfo_TreatsDuplicateParameterAsLiteralDatabaseName(t *testing.T) {
+ databaseName := "postgres dbname=databasus"
+
+ connConfig, err := pgx.ParseConfig(BuildDatabaseNameConninfo(databaseName))
+ require.NoError(t, err)
+ require.Equal(t, databaseName, connConfig.Database)
+}
diff --git a/backend/internal/features/databases/databases/postgresql/shared/embedded_target.go b/backend/internal/features/databases/databases/postgresql/shared/embedded_target.go
new file mode 100644
index 00000000..29a6df0f
--- /dev/null
+++ b/backend/internal/features/databases/databases/postgresql/shared/embedded_target.go
@@ -0,0 +1,123 @@
+package postgresql_shared
+
+import (
+ "errors"
+ "net"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+)
+
+const embeddedPostgresPort = 5437
+
+type EmbeddedTargetSpec struct {
+ Host string
+ Port int
+ DatabaseName string
+ IsPhysical bool
+ IsSSHTunnelEnabled bool
+ SSHBastionHost string
+}
+
+func ValidateNotEmbeddedTarget(spec EmbeddedTargetSpec) error {
+ if spec.IsSSHTunnelEnabled && !isLocalEndpointHost(spec.SSHBastionHost) {
+ return nil
+ }
+
+ if !isLocalEndpointHost(spec.Host) {
+ return nil
+ }
+
+ if spec.IsPhysical {
+ if spec.Port == embeddedPostgresPort {
+ return errors.New("backing up Databasus internal PostgreSQL cluster is not allowed")
+ }
+
+ return nil
+ }
+
+ if strings.EqualFold(spec.DatabaseName, "databasus") {
+ return errors.New(
+ "backing up Databasus internal database is not allowed. To backup Databasus itself, see https://databasus.com/faq#backup-databasus",
+ )
+ }
+
+ return nil
+}
+
+func isLocalEndpointHost(host string) bool {
+ return slices.ContainsFunc(strings.Split(host, ","), isLocalEndpointHostEntry)
+}
+
+func isLocalEndpointHostEntry(host string) bool {
+ normalizedHost := strings.TrimSpace(host)
+ if normalizedHost == "" {
+ return true
+ }
+
+ if filepath.IsAbs(normalizedHost) || strings.HasPrefix(normalizedHost, "@") {
+ return true
+ }
+
+ normalizedHost = strings.TrimSuffix(strings.ToLower(normalizedHost), ".")
+ switch normalizedHost {
+ case "localhost", "host.docker.internal", "172.17.0.1":
+ return true
+ }
+
+ addressHost := strings.Trim(normalizedHost, "[]")
+ parsedIP := net.ParseIP(addressHost)
+ if parsedIP == nil {
+ parsedIP, _ = parseIPv4AddressAcceptedByLibc(addressHost)
+ }
+
+ return parsedIP != nil && (parsedIP.IsLoopback() || parsedIP.IsUnspecified())
+}
+
+func parseIPv4AddressAcceptedByLibc(host string) (net.IP, bool) {
+ addressParts := strings.Split(host, ".")
+ if len(addressParts) < 1 || len(addressParts) > 4 {
+ return nil, false
+ }
+
+ partValues := make([]uint64, len(addressParts))
+ for partIndex, addressPart := range addressParts {
+ partValue, err := strconv.ParseUint(addressPart, 0, 32)
+ if err != nil {
+ return nil, false
+ }
+
+ partValues[partIndex] = partValue
+ }
+
+ var addressValue uint64
+ switch len(partValues) {
+ case 1:
+ addressValue = partValues[0]
+ case 2:
+ if partValues[0] > 0xff || partValues[1] > 0xffffff {
+ return nil, false
+ }
+ addressValue = partValues[0]<<24 | partValues[1]
+ case 3:
+ if partValues[0] > 0xff || partValues[1] > 0xff || partValues[2] > 0xffff {
+ return nil, false
+ }
+ addressValue = partValues[0]<<24 | partValues[1]<<16 | partValues[2]
+ case 4:
+ for _, partValue := range partValues {
+ if partValue > 0xff {
+ return nil, false
+ }
+ }
+ addressValue = partValues[0]<<24 | partValues[1]<<16 | partValues[2]<<8 | partValues[3]
+ }
+
+ return net.IPv4(
+ byte(addressValue>>24),
+ byte(addressValue>>16),
+ byte(addressValue>>8),
+ byte(addressValue),
+ ), true
+}
diff --git a/backend/internal/features/databases/databases/postgresql/shared/embedded_target_test.go b/backend/internal/features/databases/databases/postgresql/shared/embedded_target_test.go
new file mode 100644
index 00000000..b25a3df1
--- /dev/null
+++ b/backend/internal/features/databases/databases/postgresql/shared/embedded_target_test.go
@@ -0,0 +1,79 @@
+package postgresql_shared
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func Test_ValidateNotEmbeddedTarget_RejectsEmbeddedLogicalDatabase(t *testing.T) {
+ testCases := []struct {
+ name string
+ host string
+ }{
+ {name: "temporary socket", host: "/tmp"},
+ {name: "private socket", host: "/databasus-data/pgsocket"},
+ {name: "localhost", host: "localhost"},
+ {name: "loopback range", host: "127.42.0.9"},
+ {name: "IPv6 loopback", host: "::1"},
+ {name: "IPv4 unspecified", host: "0.0.0.0"},
+ {name: "IPv6 unspecified", host: "::"},
+ {name: "Docker host alias", host: "host.docker.internal"},
+ {name: "Docker bridge", host: "172.17.0.1"},
+ {name: "libpq host list with socket", host: "remote.invalid,/tmp"},
+ {name: "libpq host list with loopback", host: "remote.invalid,127.0.0.1"},
+ {name: "libpq host list with default socket", host: "remote.invalid,"},
+ {name: "abbreviated loopback", host: "127.1"},
+ {name: "three-part loopback", host: "127.0.1"},
+ {name: "decimal loopback", host: "2130706433"},
+ {name: "octal loopback", host: "0177.0.0.1"},
+ {name: "hexadecimal loopback", host: "0x7f000001"},
+ {name: "single-part unspecified", host: "0"},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ err := ValidateNotEmbeddedTarget(EmbeddedTargetSpec{
+ Host: testCase.host,
+ Port: 5437,
+ DatabaseName: "DATABASUS",
+ })
+
+ require.ErrorContains(t, err, "backing up Databasus internal database is not allowed")
+ })
+ }
+}
+
+func Test_ValidateNotEmbeddedTarget_AllowsNonEmbeddedLogicalDatabase(t *testing.T) {
+ testCases := []EmbeddedTargetSpec{
+ {Host: "localhost", Port: 5437, DatabaseName: "application"},
+ {Host: "database.example.com", Port: 5437, DatabaseName: "databasus"},
+ {
+ Host: "localhost",
+ Port: 5437,
+ DatabaseName: "databasus",
+ IsSSHTunnelEnabled: true,
+ SSHBastionHost: "bastion.example.com",
+ },
+ }
+
+ for _, target := range testCases {
+ require.NoError(t, ValidateNotEmbeddedTarget(target))
+ }
+}
+
+func Test_ValidateNotEmbeddedTarget_RejectsLocalBastionAndPhysicalBackup(t *testing.T) {
+ require.Error(t, ValidateNotEmbeddedTarget(EmbeddedTargetSpec{
+ Host: "localhost",
+ Port: 5437,
+ DatabaseName: "databasus",
+ IsSSHTunnelEnabled: true,
+ SSHBastionHost: "127.0.0.1",
+ }))
+
+ require.Error(t, ValidateNotEmbeddedTarget(EmbeddedTargetSpec{
+ Host: "/tmp",
+ Port: 5437,
+ IsPhysical: true,
+ }))
+}
diff --git a/backend/internal/features/databases/errors.go b/backend/internal/features/databases/errors.go
new file mode 100644
index 00000000..60686ec0
--- /dev/null
+++ b/backend/internal/features/databases/errors.go
@@ -0,0 +1,13 @@
+package databases
+
+import "errors"
+
+var ErrInsufficientPermissionsToTestDatabaseConnection = errors.New(
+ "insufficient permissions to test this database connection",
+)
+
+var ErrDatabaseConnectionTargetLookup = errors.New("failed to load database connection target")
+
+var ErrDatabaseConnectionAuthorizationLookup = errors.New(
+ "failed to verify database connection permissions",
+)
diff --git a/backend/internal/features/databases/interfaces.go b/backend/internal/features/databases/interfaces.go
index ae8d4289..23f7a543 100644
--- a/backend/internal/features/databases/interfaces.go
+++ b/backend/internal/features/databases/interfaces.go
@@ -6,8 +6,31 @@ import (
"github.com/google/uuid"
postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"
+ users_enums "databasus-backend/internal/features/users/enums"
+ users_models "databasus-backend/internal/features/users/models"
+ workspaces_models "databasus-backend/internal/features/workspaces/models"
)
+type databaseStore interface {
+ Save(database *Database) (*Database, error)
+ FindByID(id uuid.UUID) (*Database, error)
+ FindByWorkspaceID(workspaceID uuid.UUID) ([]*Database, error)
+ Delete(id uuid.UUID) error
+ IsNotifierUsing(notifierID uuid.UUID) (bool, error)
+ GetAllDatabases() ([]*Database, error)
+ GetDatabasesIDsByNotifierID(notifierID uuid.UUID) ([]uuid.UUID, error)
+}
+
+type workspaceService interface {
+ CanUserAccessWorkspace(
+ ctx context.Context,
+ workspaceID uuid.UUID,
+ user *users_models.User,
+ ) (bool, *users_enums.WorkspaceRole, error)
+ CanUserManageDBs(ctx context.Context, workspaceID uuid.UUID, user *users_models.User) (bool, error)
+ GetWorkspaceByID(workspaceID uuid.UUID) (*workspaces_models.Workspace, error)
+}
+
type DatabaseCreationListener interface {
OnDatabaseCreated(ctx context.Context, databaseID uuid.UUID)
}
diff --git a/backend/internal/features/databases/service.go b/backend/internal/features/databases/service.go
index c27b23f4..e2af75ce 100644
--- a/backend/internal/features/databases/service.go
+++ b/backend/internal/features/databases/service.go
@@ -17,12 +17,11 @@ import (
postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"
"databasus-backend/internal/features/notifiers"
users_models "databasus-backend/internal/features/users/models"
- workspaces_services "databasus-backend/internal/features/workspaces/services"
"databasus-backend/internal/util/encryption"
)
type DatabaseService struct {
- dbRepository *DatabaseRepository
+ dbRepository databaseStore
notifierService *notifiers.NotifierService
logger *slog.Logger
@@ -31,7 +30,7 @@ type DatabaseService struct {
dbCopyListener []DatabaseCopyListener
dbBackupTypeChangeListener []DatabaseBackupTypeChangeListener
- workspaceService *workspaces_services.WorkspaceService
+ workspaceService workspaceService
auditLogService *audit_logs.AuditLogService
fieldEncryptor encryption.FieldEncryptor
physicalBackupService *physical_core_service.PhysicalBackupService
@@ -475,27 +474,22 @@ func (s *DatabaseService) TestDatabaseConnection(
func (s *DatabaseService) TestDatabaseConnectionDirect(
ctx context.Context,
+ user *users_models.User,
database *Database,
) error {
- usingDatabase, err := s.resolveConnectionTarget(database)
- if err != nil {
- return err
- }
-
- logger := s.logger.With("database_id", usingDatabase.ID)
-
- tunneledDatabase, err := OpenTunnel(ctx, OpenTunnelSpec{
- Database: usingDatabase,
- Logger: logger,
- Encryptor: s.fieldEncryptor,
- })
+ usingDatabase, err := s.resolveAuthorizedConnectionTarget(ctx, user, database)
if err != nil {
return err
}
- defer tunneledDatabase.Close()
+ return s.testDatabaseConnection(ctx, usingDatabase)
+}
- return tunneledDatabase.GetDatabaseThroughTunnel().TestConnection(logger, s.fieldEncryptor)
+func (s *DatabaseService) TestTrustedDatabaseConnection(
+ ctx context.Context,
+ database *Database,
+) error {
+ return s.testDatabaseConnection(ctx, database)
}
func (s *DatabaseService) GetDatabaseByID(
@@ -968,6 +962,27 @@ func (s *DatabaseService) CreateReplicationOnlyUser(
return createdUser, nil
}
+func (s *DatabaseService) testDatabaseConnection(ctx context.Context, database *Database) error {
+ if database == nil {
+ return errors.New("database is required")
+ }
+
+ logger := s.logger.With("database_id", database.ID)
+
+ tunneledDatabase, err := OpenTunnel(ctx, OpenTunnelSpec{
+ Database: database,
+ Logger: logger,
+ Encryptor: s.fieldEncryptor,
+ })
+ if err != nil {
+ return err
+ }
+
+ defer tunneledDatabase.Close()
+
+ return tunneledDatabase.GetDatabaseThroughTunnel().TestConnection(logger, s.fieldEncryptor)
+}
+
// fillPhysicalLastBackupTimes populates LastBackupTime for physical databases,
// whose backups (FULL / INCREMENTAL / WAL) live outside the databases table and so
// are not denormalized onto the row the way logical backups are. A failure here is
@@ -999,16 +1014,50 @@ func (s *DatabaseService) fillPhysicalLastBackupTimes(ctx context.Context, datab
}
}
-// resolveConnectionTarget merges an unsaved request over the persisted database
-// when an ID is supplied, so a connection test uses the same merge rules as save.
-func (s *DatabaseService) resolveConnectionTarget(database *Database) (*Database, error) {
+func (s *DatabaseService) resolveAuthorizedConnectionTarget(
+ ctx context.Context,
+ user *users_models.User,
+ database *Database,
+) (*Database, error) {
+ if database == nil {
+ return nil, errors.New("database is required")
+ }
+
if database.ID == uuid.Nil {
+ if database.WorkspaceID == nil {
+ return nil, errors.New("workspaceId is required")
+ }
+
+ canManage, err := s.workspaceService.CanUserManageDBs(ctx, *database.WorkspaceID, user)
+ if err != nil {
+ return nil, errors.Join(ErrDatabaseConnectionAuthorizationLookup, err)
+ }
+ if !canManage {
+ return nil, ErrInsufficientPermissionsToTestDatabaseConnection
+ }
+
return database, nil
}
existingDatabase, err := s.dbRepository.FindByID(database.ID)
if err != nil {
- return nil, err
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, ErrInsufficientPermissionsToTestDatabaseConnection
+ }
+
+ return nil, errors.Join(ErrDatabaseConnectionTargetLookup, err)
+ }
+
+ if existingDatabase.WorkspaceID == nil {
+ return nil, ErrInsufficientPermissionsToTestDatabaseConnection
+ }
+
+ canManage, err := s.workspaceService.CanUserManageDBs(ctx, *existingDatabase.WorkspaceID, user)
+ if err != nil {
+ return nil, errors.Join(ErrDatabaseConnectionAuthorizationLookup, err)
+ }
+ if !canManage {
+ return nil, ErrInsufficientPermissionsToTestDatabaseConnection
}
if database.WorkspaceID != nil && existingDatabase.WorkspaceID != nil &&
diff --git a/backend/internal/features/databases/tunneled_database.go b/backend/internal/features/databases/tunneled_database.go
index faa6d849..88e24bc0 100644
--- a/backend/internal/features/databases/tunneled_database.go
+++ b/backend/internal/features/databases/tunneled_database.go
@@ -36,6 +36,10 @@ func OpenTunnel(ctx context.Context, spec OpenTunnelSpec) (*TunneledDatabase, er
return &TunneledDatabase{}, nil
}
+ if err := validatePostgresqlTarget(spec.Database); err != nil {
+ return nil, err
+ }
+
// The copy carries the forwarded port and a disabled tunnel, so it must never reach Save.
databaseThroughTunnel := *spec.Database
@@ -67,6 +71,21 @@ func OpenTunnel(ctx context.Context, spec OpenTunnelSpec) (*TunneledDatabase, er
return tunneledDatabase, nil
}
+func validatePostgresqlTarget(database *Database) error {
+ switch database.Type {
+ case DatabaseTypePostgresLogical:
+ if database.PostgresqlLogical != nil {
+ return database.PostgresqlLogical.ValidateNotEmbeddedTarget()
+ }
+ case DatabaseTypePostgresPhysical:
+ if database.PostgresqlPhysical != nil {
+ return database.PostgresqlPhysical.ValidateNotEmbeddedTarget()
+ }
+ }
+
+ return nil
+}
+
func (t *TunneledDatabase) GetDatabaseThroughTunnel() *Database {
if t == nil {
return nil
diff --git a/backend/internal/features/databases/tunneled_database_test.go b/backend/internal/features/databases/tunneled_database_test.go
index 5db3e8db..20452816 100644
--- a/backend/internal/features/databases/tunneled_database_test.go
+++ b/backend/internal/features/databases/tunneled_database_test.go
@@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/require"
"databasus-backend/internal/features/databases/databases/mysql"
+ postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"
)
// Close and CopyDiscoveredMetadataToOriginal delegate through an interface, and a passthrough leaves
@@ -33,3 +34,34 @@ func Test_CloseTunneledDatabase_WhenTheDatabaseIsNil_DoesNotPanic(t *testing.T)
assert.NotPanics(t, tunneledDatabase.Close)
assert.Nil(t, tunneledDatabase.GetDatabaseThroughTunnel())
}
+
+func Test_OpenTunnel_WithPersistedEmbeddedLogicalTarget_ReturnsError(t *testing.T) {
+ testCases := []struct {
+ name string
+ host string
+ }{
+ {name: "Unix socket in libpq host list", host: "remote.invalid,/tmp"},
+ {name: "decimal loopback", host: "2130706433"},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ databaseName := "databasus"
+ database := &Database{
+ Type: DatabaseTypePostgresLogical,
+ PostgresqlLogical: &postgresql_logical.PostgresqlLogicalDatabase{
+ Host: testCase.host,
+ Port: 5437,
+ Username: "postgres",
+ Password: "stored-password",
+ Database: &databaseName,
+ CpuCount: 1,
+ },
+ }
+
+ _, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})
+
+ require.ErrorContains(t, err, "backing up Databasus internal database is not allowed")
+ })
+ }
+}
diff --git a/backend/internal/features/healthcheck/attempt/check_database_health_uc.go b/backend/internal/features/healthcheck/attempt/check_database_health_uc.go
index 32831e89..e778b7ba 100644
--- a/backend/internal/features/healthcheck/attempt/check_database_health_uc.go
+++ b/backend/internal/features/healthcheck/attempt/check_database_health_uc.go
@@ -154,7 +154,7 @@ func (uc *CheckDatabaseHealthUseCase) healthcheckDatabase(
// A database being down is the condition this probe exists to detect, and the caller reports it
// too, so it is a tolerated finding here rather than something needing attention.
- if err := uc.databaseService.TestDatabaseConnectionDirect(ctx, database); err != nil {
+ if err := uc.databaseService.TestTrustedDatabaseConnection(ctx, database); err != nil {
healthStatus = databases.HealthStatusUnavailable
logger.WarnContext(ctx, "database healthcheck probe failed", "error", err)
diff --git a/backend/internal/features/healthcheck/attempt/check_database_health_uc_test.go b/backend/internal/features/healthcheck/attempt/check_database_health_uc_test.go
index 8709e198..9070b199 100644
--- a/backend/internal/features/healthcheck/attempt/check_database_health_uc_test.go
+++ b/backend/internal/features/healthcheck/attempt/check_database_health_uc_test.go
@@ -89,7 +89,7 @@ func Test_CheckDatabaseHealthUseCase(t *testing.T) {
// Setup mock database service
mockDatabaseService := &MockDatabaseService{}
- mockDatabaseService.On("TestDatabaseConnectionDirect", database).
+ mockDatabaseService.On("TestTrustedDatabaseConnection", database).
Return(errors.New("test error"))
unavailableStatus := databases.HealthStatusUnavailable
mockDatabaseService.On("SetHealthStatus", database.ID, &unavailableStatus).
@@ -151,7 +151,7 @@ func Test_CheckDatabaseHealthUseCase(t *testing.T) {
// Setup mock database service - connection fails but SetHealthStatus should not be called
mockDatabaseService := &MockDatabaseService{}
- mockDatabaseService.On("TestDatabaseConnectionDirect", database).
+ mockDatabaseService.On("TestTrustedDatabaseConnection", database).
Return(errors.New("test error"))
mockDatabaseService.On("GetDatabaseByID", database.ID).
Return(database, nil)
@@ -220,7 +220,7 @@ func Test_CheckDatabaseHealthUseCase(t *testing.T) {
// Setup mock database service
mockDatabaseService := &MockDatabaseService{}
- mockDatabaseService.On("TestDatabaseConnectionDirect", database).
+ mockDatabaseService.On("TestTrustedDatabaseConnection", database).
Return(errors.New("test error"))
unavailableStatus := databases.HealthStatusUnavailable
mockDatabaseService.On("SetHealthStatus", database.ID, &unavailableStatus).
@@ -297,7 +297,7 @@ func Test_CheckDatabaseHealthUseCase(t *testing.T) {
// Setup mock database service - connection succeeds
mockDatabaseService := &MockDatabaseService{}
- mockDatabaseService.On("TestDatabaseConnectionDirect", database).Return(nil)
+ mockDatabaseService.On("TestTrustedDatabaseConnection", database).Return(nil)
availableStatus := databases.HealthStatusAvailable
mockDatabaseService.On("SetHealthStatus", database.ID, &availableStatus).
Return(nil)
@@ -359,7 +359,7 @@ func Test_CheckDatabaseHealthUseCase(t *testing.T) {
// Setup mock database service - connection succeeds
mockDatabaseService := &MockDatabaseService{}
- mockDatabaseService.On("TestDatabaseConnectionDirect", database).Return(nil)
+ mockDatabaseService.On("TestTrustedDatabaseConnection", database).Return(nil)
availableStatus := databases.HealthStatusAvailable
mockDatabaseService.On("SetHealthStatus", database.ID, &availableStatus).
Return(nil)
@@ -510,7 +510,7 @@ func Test_CheckDatabaseHealthUseCase(t *testing.T) {
mockSender.On("SendNotification", mock.Anything, mock.Anything).Return()
mockDatabaseService := &MockDatabaseService{}
- mockDatabaseService.On("TestDatabaseConnectionDirect", database).
+ mockDatabaseService.On("TestTrustedDatabaseConnection", database).
Return(errors.New("replication connection refused"))
unavailableStatus := databases.HealthStatusUnavailable
mockDatabaseService.On("SetHealthStatus", database.ID, &unavailableStatus).Return(nil)
diff --git a/backend/internal/features/healthcheck/attempt/interfaces.go b/backend/internal/features/healthcheck/attempt/interfaces.go
index bb42a5ea..54d5cbad 100644
--- a/backend/internal/features/healthcheck/attempt/interfaces.go
+++ b/backend/internal/features/healthcheck/attempt/interfaces.go
@@ -21,7 +21,7 @@ type HealthcheckAttemptSender interface {
type DatabaseService interface {
GetDatabaseByID(id uuid.UUID) (*databases.Database, error)
- TestDatabaseConnectionDirect(ctx context.Context, database *databases.Database) error
+ TestTrustedDatabaseConnection(ctx context.Context, database *databases.Database) error
SetHealthStatus(
databaseID uuid.UUID,
diff --git a/backend/internal/features/healthcheck/attempt/mocks.go b/backend/internal/features/healthcheck/attempt/mocks.go
index b2e0dc7c..8db587cd 100644
--- a/backend/internal/features/healthcheck/attempt/mocks.go
+++ b/backend/internal/features/healthcheck/attempt/mocks.go
@@ -27,7 +27,7 @@ type MockDatabaseService struct {
mock.Mock
}
-func (m *MockDatabaseService) TestDatabaseConnectionDirect(
+func (m *MockDatabaseService) TestTrustedDatabaseConnection(
ctx context.Context,
database *databases.Database,
) error {
diff --git a/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/.openspec.yaml b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/.openspec.yaml
new file mode 100644
index 00000000..1d9aeef9
--- /dev/null
+++ b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-09-04
diff --git a/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/design.md b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/design.md
new file mode 100644
index 00000000..2c2c401f
--- /dev/null
+++ b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/design.md
@@ -0,0 +1,128 @@
+## Context
+
+See [proposal.md](proposal.md#why) for the attack paths and [the capability spec](specs/internal-postgresql-protection/spec.md) for required behavior.
+
+PostgreSQL connection strings are assembled centrally in `backend/internal/features/databases/databases/postgresql/shared/credentials.go:82-120`, while logical dumps pass their database argument separately in `backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go:363-371`. Connection creation also has more than one entry point: the database-level tunnel dispatcher in `backend/internal/features/databases/tunneled_database.go:34-71` and engine-specific tunnel functions.
+
+The direct connection-test endpoint accepts both unsaved configurations and partial updates for saved database IDs. Its service path is split from trusted healthchecks at `backend/internal/features/databases/service.go:475-493`, and saved-target authorization happens at `backend/internal/features/databases/service.go:1017-1075`.
+
+The container starts PostgreSQL and the application in one process tree. `Dockerfile:330-456` owns PostgreSQL initialization, authentication policy, password rotation, and the connection string inherited by the application. Custom `PUID` and `PGID` values remain supported, subject to the account separation check at `Dockerfile:232-252`.
+
+The approach is constrained by [`AGENTS.md`](../../../../AGENTS.md) and [`backend/AGENTS.md`](../../../../backend/AGENTS.md), especially their rules on layered security, controller-level tests, sanitized errors, explicit names, and removal of obsolete call signatures without compatibility shims.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Stop each confirmed path from a workspace-controlled PostgreSQL request to the embedded metadata database.
+- Authorize saved credentials before any caller-controlled endpoint can use them.
+- Preserve legitimate local databases, remote SSH targets, healthchecks, external metadata databases, and custom non-conflicting PostgreSQL UIDs.
+- Make the container's PostgreSQL authentication safe even if a target classifier misses a future local hostname form.
+
+**Non-Goals:**
+
+- Resolve arbitrary hostnames during request validation.
+- Redesign workspace roles, database persistence, or the general API error format.
+- Extend this PostgreSQL-specific target policy to other database engines.
+- Add a data migration or a long-lived compatibility path for the old service method signature.
+
+## Decisions
+
+### 1. Combine semantic target checks with runtime isolation
+
+PostgreSQL targets are classified before validation succeeds and again immediately before a connection opens. The shared classifier treats absolute and abstract socket names as local, examines every comma-separated libpq host, recognizes configured container aliases, and parses IPv4 forms accepted by libc before checking loopback or unspecified ranges. A loopback database address behind a genuinely remote SSH bastion remains remote in meaning.
+
+The connection-time check is required because persisted rows can predate the validation rule or enter a connection path that does not call full model validation. The container authentication changes provide the second boundary when an unrecognized hostname still resolves locally.
+
+Alternatives rejected:
+
+- Extend the old string allowlist only. It cannot cover Unix sockets, multi-host fallback, or resolver-equivalent numeric addresses reliably.
+- Harden the container without application checks. That makes access depend on the secrecy of one credential and still permits repeated probes of the internal service.
+- Resolve DNS during validation. It adds latency and availability dependencies, and the result can change between validation and connection through DNS rebinding.
+
+### 2. Quote each conninfo value at construction
+
+The shared PostgreSQL credential builder quotes and escapes every string field before parsing it. The logical dump receives a one-field conninfo expression whose quoted `dbname` contains the complete database name. This handles parameter-looking input as data instead of trying to reject selected substrings.
+
+Alternatives rejected:
+
+- Reject whitespace or the text `dbname=`. Valid PostgreSQL identifiers can contain unusual characters, and a denylist would miss other parameter names and escaping forms.
+- Quote only passwords. Host, username, database, TLS mode, and certificate paths are all parser inputs and need the same invariant.
+- Pass the raw database name to the dump tool. That tool interprets values containing conninfo syntax as connection strings.
+
+### 3. Authorize the saved record before merging request fields
+
+An unsaved direct test requires `workspaceId` and checks the caller's existing database-management permission for that workspace. A saved-ID request first loads the persisted database, authorizes its stored workspace, and only then overlays the submitted update. The saved password is therefore unavailable to an unauthorized request.
+
+Database storage and workspace access are represented by narrow internal interfaces in `backend/internal/features/databases/interfaces.go:12-31`. This permits controller tests to inject repository and membership failures without replacing production dependency wiring.
+
+Alternatives rejected:
+
+- Trust the request's `workspaceId`. A caller can claim a workspace they control while referencing a database stored elsewhere.
+- Merge first and clear the password on denial. The unsafe credential has already crossed the authorization boundary, and later code can accidentally use it.
+- Check authorization only in the controller. Trusted internal callers and future entry points would bypass the invariant.
+
+### 4. Separate user-authorized and trusted connection tests
+
+The HTTP path takes an authenticated user and resolves an authorized target. Scheduled healthchecks call a separate trusted method with a database already loaded by the service, while both methods share the connection implementation and the runtime embedded-target check.
+
+Alternatives rejected:
+
+- Accept a nullable user in one method. A missing principal would silently become an authorization bypass available to any caller.
+- Give the healthcheck a synthetic administrator. That invents user identity for a system action and makes audit behavior misleading.
+- Keep the old method name for both meanings. It hides the security boundary between an HTTP request and a trusted background operation.
+
+### 5. Make authorization infrastructure failures explicit and sanitized
+
+Unknown and unauthorized saved IDs map to one permission sentinel and HTTP 403 response. A repository failure and a workspace-permission lookup failure use separate wrapped sentinels, preserve the original error for server-side handling, and expose only fixed HTTP 500 messages.
+
+Alternatives rejected:
+
+- Return every failure as HTTP 400 with `err.Error()`. That exposes storage and membership details and misclassifies server failures as invalid input.
+- Return HTTP 404 for unknown IDs. A different response would let a caller distinguish an existing protected UUID from an unused one.
+- Discard underlying errors entirely. Wrapping retains diagnostic context without sending it to the client.
+
+### 6. Use a private peer-authenticated socket to bootstrap random TCP credentials
+
+The PostgreSQL socket lives under `/databasus-data/pgsocket`, owned by `postgres` with mode `0700`. Local HBA rules allow peer authentication only for the PostgreSQL operating-system account and reject other local users. Startup administration uses that socket to assign a new random password. The application and legacy-data checks use loopback TCP with SCRAM, and replication is rejected.
+
+When `DATABASE_DSN` is absent from the container environment, startup exports a DSN containing the generated password. An explicitly supplied value wins, matching the existing environment precedence contract.
+
+Alternatives rejected:
+
+- Keep a fixed password because the port binds to loopback. Workspace-controlled connection features run inside the same container, so loopback is within their reach.
+- Keep `local all all trust` and rely on socket filesystem placement. Authentication should still reject access if directory permissions are weakened later.
+- Disable Unix sockets entirely. Startup would need another bootstrap credential path, while a private peer-authenticated socket already gives PostgreSQL a standard local administration boundary.
+- Store one generated password permanently in the volume. Rotation at startup avoids creating another secret file and limits the lifetime of a disclosed value.
+
+### 7. Reject UID collisions while preserving custom ownership
+
+Before remapping `postgres`, startup resolves the requested `PUID`. If another image account already owns it, startup exits before changing the account. An unused UID is still accepted and applied.
+
+Alternatives rejected:
+
+- Continue using `usermod -o` for every value. Duplicate UIDs erase the filesystem boundary between `postgres` and `databasus`.
+- Remove custom UID support. Bind-mounted NAS and host directories rely on operator-selected ownership.
+- Reject only the known `databasus` UID. Root or another existing account would create the same class of collision.
+
+## Risks / Trade-offs
+
+- [A legitimate local database named `databasus` is rejected] -> Preserve the established conservative rule for local logical targets; a remote database with that name remains valid.
+- [A hostname not recognized as local can pass classification] -> Do not rely on classification alone; private socket permissions, HBA rejection, generated credentials, and replication rejection remain active.
+- [Comma splitting rejects a Unix-socket path containing a comma] -> Favor preventing libpq fallback to the embedded instance. Such paths can be renamed or reached through a remote tunnel.
+- [Password rotation interrupts a process that retained the previous DSN] -> Rotation happens before the application starts, and the new DSN is exported to that process tree.
+- [Clients of the direct endpoint omit `workspaceId`] -> Treat this as an intentional API break; clients must supply the workspace already selected in the UI or API workflow.
+- [A custom `PUID` collides after an image adds another system account] -> Fail with the conflicting username before changing ownership, giving the operator a deterministic configuration error.
+- [Rolling back to an older image can fail authentication against a volume already upgraded] -> Take a volume snapshot before deployment. Before rollback, either restore that snapshot or use the current image's peer-authenticated socket to set the internal role to the credential expected by the older image.
+
+## Migration Plan
+
+1. Remove an explicit `DATABASE_DSN` that targets the embedded database. Keep it only when it targets an external PostgreSQL database with its own credentials.
+2. Update direct connection-test clients to send `workspaceId` for unsaved configurations and accept the documented 403 and 500 responses.
+3. Build and run the backend tests, lint, Dockerfile validation, and image smoke tests before publishing the image.
+4. Snapshot `/databasus-data` before replacing an existing container.
+5. Start the new image. Startup rewrites the internal HBA file, creates the private socket directory, rotates the internal password, and launches the application with the matching DSN.
+6. Confirm application health, verify that the application account cannot enter the private socket directory, and verify that the previously published fixed password fails over TCP.
+7. For rollback, stop the new container and restore the volume snapshot before starting the prior image. If no snapshot is available, reset the internal role through the current image's peer-authenticated socket to the credential expected by the prior image, then roll back.
+
+No database schema migration is required.
diff --git a/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/proposal.md b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/proposal.md
new file mode 100644
index 00000000..a145b9be
--- /dev/null
+++ b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/proposal.md
@@ -0,0 +1,55 @@
+## Why
+
+Workspace users can reach the PostgreSQL instance embedded in the Databasus container through Unix sockets and libpq connection-string parsing that bypass the existing localhost check. The direct connection-test endpoint can also combine another workspace's saved password with a caller-controlled host because it loads and merges the saved database without checking access.
+
+## Governing docs
+
+This change answers to [`AGENTS.md`](../../../../AGENTS.md) and [`backend/AGENTS.md`](../../../../backend/AGENTS.md). It changes the root `Dockerfile` and backend code only.
+
+## What Changes
+
+- Treat every PostgreSQL connection field as a literal conninfo value, including the database name passed to `pg_dump`.
+- Reject logical and physical backup targets that can address the embedded PostgreSQL instance through Unix sockets, local aliases, loopback or unspecified addresses, libc-compatible numeric IPv4 forms, and comma-separated libpq host lists.
+- Enforce the embedded-target check both during model validation and immediately before opening a connection, so an older persisted row cannot bypass it.
+- Authorize `test-connection-direct` against the requested workspace or the saved database's actual workspace before applying saved credentials. Unknown and unauthorized saved IDs return the same response.
+- Keep trusted healthcheck calls separate from the user-facing direct connection-test path.
+- Return sanitized server errors when saved-target or workspace-permission lookups fail.
+- Move the embedded PostgreSQL Unix socket to a private directory, reject general local socket access, require SCRAM authentication over loopback TCP, and generate the internal password at container startup.
+- Reject a PostgreSQL `PUID` that is already assigned to another account in the container.
+- **BREAKING**: an ad hoc `POST /api/v1/databases/test-connection-direct` request without `workspaceId` is rejected with HTTP 400. Unauthorized or unknown saved targets return HTTP 403, and internal lookup failures return HTTP 500 instead of exposing an error through HTTP 400.
+- **BREAKING**: `DatabaseService.TestDatabaseConnectionDirect` now requires the authenticated user. Trusted internal callers use `TestTrustedDatabaseConnection`; the old service signature is deleted without a compatibility shim.
+- **BREAKING**: a container configured with a PostgreSQL `PUID` already owned by another account fails at startup. The conflicting configuration is rejected rather than preserved through duplicate UIDs.
+- **BREAKING**: an explicitly supplied `DATABASE_DSN` that points to the embedded PostgreSQL instance with the previously published fixed password stops working because startup preserves the explicit value while rotating the internal role's password.
+
+### Operator migration
+
+- Remove an explicit `DATABASE_DSN` that points to the embedded database before upgrading, so startup can inject the generated credential. Keep `DATABASE_DSN` only when it points to an external PostgreSQL database with independently managed credentials.
+- Update callers of the direct connection-test endpoint to include `workspaceId` for unsaved configurations and accept the documented 403 and 500 responses.
+- Choose an unused PostgreSQL `PUID` if the configured value belongs to another account in the image.
+
+### Out of scope
+
+- Changing workspace roles or which existing roles may manage database connections.
+- Applying the embedded-target policy to MySQL, MariaDB, or MongoDB.
+- Resolving arbitrary DNS names during validation. Runtime socket isolation and generated credentials remain the protection when a hostname resolves to the container itself.
+- Changing an explicitly supplied external `DATABASE_DSN`.
+- Adding a new public error-code schema or changing generated Swagger files.
+
+## Capabilities
+
+### New Capabilities
+
+- `internal-postgresql-protection`: prevents workspace-controlled connection and backup operations from reading the Databasus metadata database or reusing saved credentials outside their authorized workspace.
+
+### Modified Capabilities
+
+None. Existing physical-backup specifications do not define access to the embedded Databasus PostgreSQL instance or authorization for direct connection tests.
+
+## Impact
+
+- `Dockerfile`: embedded PostgreSQL socket placement, `pg_hba.conf`, generated credentials, and UID collision validation.
+- `backend/internal/features/databases`: connection-test authorization, sanitized errors, trusted healthcheck entry point, and pre-connection target validation.
+- `backend/internal/features/databases/databases/postgresql`: shared target classification and conninfo quoting for logical and physical connections.
+- `backend/internal/features/backups/backups/usecases/logical/postgresql`: literal database-name handling for `pg_dump`.
+- `backend/internal/features/healthcheck/attempt`: use of the trusted connection-test entry point.
+- No new runtime dependency, database migration, or frontend change.
diff --git a/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/specs/internal-postgresql-protection/spec.md b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/specs/internal-postgresql-protection/spec.md
new file mode 100644
index 00000000..5b7fdc9d
--- /dev/null
+++ b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/specs/internal-postgresql-protection/spec.md
@@ -0,0 +1,242 @@
+## Purpose
+
+Prevents workspace-controlled PostgreSQL connections and backups from reading the Databasus metadata database or sending another workspace's saved credentials to a caller-controlled server.
+
+## ADDED Requirements
+
+### Requirement: Logical backups cannot target the embedded metadata database
+
+The system SHALL reject a logical PostgreSQL source when its database name is `databasus` and any effective host points back to the Databasus container. Local targets include filesystem and abstract Unix sockets, loopback and unspecified IP addresses, supported container-local aliases, libc-compatible numeric IPv4 forms, and an empty entry in a comma-separated host list.
+
+The system SHALL inspect every host in a multi-host value. A remote entry SHALL NOT make a later local entry acceptable.
+
+#### Scenario: Filesystem Unix socket
+
+- **WHEN** a user configures a logical PostgreSQL source with database `databasus` and a filesystem Unix-socket directory as its host
+- **THEN** the system rejects the source before opening the connection
+
+#### Scenario: Abstract Unix socket
+
+- **WHEN** a user configures database `databasus` with an abstract Unix-socket host
+- **THEN** the system rejects the source before opening the connection
+
+#### Scenario: Loopback address in a host list
+
+- **WHEN** a PostgreSQL host list contains a remote hostname followed by a loopback address and the database is `databasus`
+- **THEN** the system rejects the whole source
+
+#### Scenario: Numeric loopback spelling
+
+- **WHEN** a user specifies a loopback address in an abbreviated, integer, octal, or hexadecimal form accepted by the operating-system resolver
+- **THEN** the system treats it as local and rejects database `databasus`
+
+#### Scenario: Local application database
+
+- **WHEN** a user configures a local PostgreSQL source whose database name is not `databasus`
+- **THEN** the embedded-target rule allows the source
+
+#### Scenario: Remote database with the same name
+
+- **WHEN** a PostgreSQL source is remote and its database name is `databasus`
+- **THEN** the embedded-target rule allows the source
+
+### Requirement: Physical backups cannot target the embedded PostgreSQL cluster
+
+The system SHALL reject a physical PostgreSQL source when an effective local host uses the embedded cluster's port. This rule SHALL apply without relying on a database name because a physical backup addresses the cluster rather than one logical database.
+
+#### Scenario: Embedded cluster through a Unix socket
+
+- **WHEN** a user configures a physical backup against a local Unix socket and the embedded PostgreSQL port
+- **THEN** the system rejects the source before any physical backup connection is opened
+
+#### Scenario: Different local PostgreSQL instance
+
+- **WHEN** a physical source uses a local address on a port other than the embedded PostgreSQL port
+- **THEN** the embedded-target rule allows the source
+
+### Requirement: Remote SSH targets keep their remote meaning
+
+When a database is reached through an SSH bastion on another host, a loopback database address SHALL be interpreted relative to that remote host. A local SSH bastion SHALL NOT relax the embedded-target rules.
+
+#### Scenario: Database bound to loopback on a remote bastion
+
+- **WHEN** SSH tunneling is enabled through a non-local bastion and the PostgreSQL host is a loopback address
+- **THEN** the embedded-target rule allows the source
+
+#### Scenario: Local bastion points back to the container
+
+- **WHEN** SSH tunneling names a local bastion and the PostgreSQL target matches the embedded instance
+- **THEN** the system rejects the source
+
+### Requirement: Persisted configurations are checked at connection time
+
+The system SHALL apply embedded-target protection immediately before a PostgreSQL connection is opened, including connections created from rows saved before this policy existed. Model validation alone SHALL NOT be the only enforcement point.
+
+#### Scenario: Existing logical row contains a socket target
+
+- **WHEN** a previously saved logical source names the embedded database through a local socket
+- **THEN** a backup, connection test, or healthcheck refuses to open that connection
+
+#### Scenario: Existing physical row contains the embedded cluster
+
+- **WHEN** a previously saved physical source names the embedded PostgreSQL cluster
+- **THEN** physical connection and backup paths refuse to open that connection
+
+### Requirement: PostgreSQL connection values remain literal
+
+Every user-controlled string used in a PostgreSQL conninfo value SHALL be interpreted as one value. Whitespace, quotes, backslashes, equal signs, and text resembling another conninfo parameter SHALL NOT create or replace connection parameters.
+
+The database name passed to a logical dump SHALL follow the same rule even when the dump tool accepts a conninfo string in place of a plain database name.
+
+#### Scenario: Database name contains a second database parameter
+
+- **WHEN** a database name contains `dbname=databasus` after another value
+- **THEN** PostgreSQL receives the complete input as one literal database name
+- **AND** the text cannot redirect the connection to the embedded database
+
+#### Scenario: Other credential fields contain conninfo syntax
+
+- **WHEN** a host, username, password, TLS mode, or certificate path contains whitespace or conninfo metacharacters
+- **THEN** the connection parser returns the original field value without creating another parameter
+
+### Requirement: Direct connection tests require workspace authorization
+
+The direct connection-test endpoint SHALL require an authenticated user who can manage databases in the relevant workspace. An ad hoc database SHALL identify that workspace. A request referencing a saved database SHALL be authorized against the workspace stored on that database before saved credentials are merged with request fields.
+
+#### Scenario: Ad hoc request without a workspace
+
+- **WHEN** an authenticated user submits an unsaved database without `workspaceId`
+- **THEN** the endpoint returns HTTP 400
+- **AND** no connection is attempted
+
+#### Scenario: Ad hoc request for an unauthorized workspace
+
+- **WHEN** an authenticated user submits an unsaved database for a workspace where they cannot manage databases
+- **THEN** the endpoint returns HTTP 403
+- **AND** no connection is attempted
+
+#### Scenario: Saved database from another workspace
+
+- **WHEN** a user references a saved database outside a workspace they can manage and supplies a different host
+- **THEN** the endpoint returns HTTP 403 before applying the saved password
+- **AND** the system makes no connection to the supplied host
+
+#### Scenario: Authorized workspace member tests a saved database
+
+- **WHEN** a workspace member who can manage databases tests a saved database in that workspace and leaves its password blank
+- **THEN** the system may use the saved password and performs the connection test
+
+### Requirement: Direct connection-test failures do not disclose protected records or internal errors
+
+The endpoint SHALL return the same HTTP 403 response for an unknown saved database and a saved database the caller cannot manage. Storage failures while loading a saved target and failures while checking workspace permissions SHALL return distinct, sanitized HTTP 500 messages that do not include the underlying error.
+
+#### Scenario: Unknown saved database ID
+
+- **WHEN** a caller submits an ID that does not identify a saved database
+- **THEN** the endpoint returns the same HTTP 403 body used for an unauthorized saved database
+
+#### Scenario: Saved target lookup fails internally
+
+- **WHEN** storage fails while loading the referenced saved database
+- **THEN** the endpoint returns HTTP 500 with `failed to load database connection target`
+- **AND** the storage error is absent from the response
+
+#### Scenario: Permission lookup fails internally
+
+- **WHEN** the workspace permission lookup fails for either an ad hoc or saved database
+- **THEN** the endpoint returns HTTP 500 with `failed to verify database connection permissions`
+- **AND** the underlying membership error is absent from the response
+
+### Requirement: Healthchecks use a trusted internal connection path
+
+Scheduled healthchecks SHALL test a database already loaded by the system without pretending to be an end user. The user-facing direct endpoint SHALL NOT expose that trusted path or bypass its workspace checks.
+
+#### Scenario: Scheduled healthcheck
+
+- **WHEN** the healthcheck service loads a saved database and probes it
+- **THEN** the probe runs without an end-user principal
+- **AND** embedded-target protection still runs before the connection opens
+
+#### Scenario: User-facing direct test
+
+- **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
+
+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.
+
+#### 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
+
+#### Scenario: PostgreSQL account performs startup administration
+
+- **WHEN** the PostgreSQL operating-system account connects through the private socket during startup
+- **THEN** peer authentication 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: Replication connection to the embedded cluster
+
+- **WHEN** a client requests a replication connection to the embedded PostgreSQL server
+- **THEN** PostgreSQL rejects it
+
+### Requirement: Internal PostgreSQL credentials are generated at startup
+
+When Databasus uses its embedded metadata database, the container SHALL generate a cryptographically random PostgreSQL password at startup, set it on the internal role, and supply it to the application without logging it. A container restart SHALL replace the previous password. An explicitly supplied external metadata-database connection string SHALL remain unchanged.
+
+An operator-supplied connection string that points back to the embedded database with the previously published fixed password is incompatible with rotation and SHALL NOT be treated as a supported embedded-database configuration.
+
+#### Scenario: Fresh container startup
+
+- **WHEN** a container starts without an explicit metadata-database connection string
+- **THEN** it configures the embedded role and the application with the same generated password
+- **AND** the application becomes healthy without printing that password
+
+#### Scenario: Container restart
+
+- **WHEN** the same container restarts
+- **THEN** the embedded role receives a different generated password
+- **AND** the application reconnects with the new password
+
+#### Scenario: Previously published fixed password
+
+- **WHEN** a client attempts loopback TCP authentication with the old fixed image password
+- **THEN** PostgreSQL rejects the connection
+
+#### Scenario: External metadata database
+
+- **WHEN** the operator explicitly supplies a connection string for an external metadata database
+- **THEN** startup preserves that value rather than replacing it with the embedded database connection
+
+#### Scenario: Explicit connection string points 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/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/tasks.md b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/tasks.md
new file mode 100644
index 00000000..d998865e
--- /dev/null
+++ b/openspec/changes/archive/2026-09-04-protect-internal-postgresql-access/tasks.md
@@ -0,0 +1,41 @@
+## 1. Security regressions
+
+- [x] 1.1 Add conninfo tests proving that parameter-looking host, username, password, and database values remain literal, and verify the focused PostgreSQL shared-package test fails before the quoting fix
+- [x] 1.2 Add shared-classifier tests for Unix sockets, local aliases, comma-separated host fallback, and libc-compatible numeric loopback forms, plus logical and physical model regressions for `/tmp`; verify they fail before target classification changes
+- [x] 1.3 Add engine-level connection-time tests for persisted logical and physical embedded targets and a database-level logical regression, and verify the focused `OpenTunnel` tests fail before runtime enforcement
+- [x] 1.4 Add controller tests for missing workspace, unauthorized and unknown saved IDs, authorized workspace members, repository failure, and ad hoc plus saved membership failures, and verify the vulnerable authorization and unsanitized-error cases fail
+- [x] 1.5 Build the pre-fix image with `docker build` and verify that a container configured with `PUID=65532` becomes healthy instead of rejecting the UID collision
+
+## 2. PostgreSQL target and conninfo protection
+
+- [x] 2.1 Add one shared embedded-target classifier for logical and physical PostgreSQL configurations, including remote SSH semantics, and verify all classifier tests pass with `go test -count=1 ./internal/features/databases/databases/postgresql/shared`
+- [x] 2.2 Call embedded-target validation from logical and physical model validation and immediately before opening engine-level and database-level tunnels, and verify the logical, physical, and database package tests pass
+- [x] 2.3 Quote every string field used to build PostgreSQL conninfo and verify parsed connection fields exactly match the submitted literal values
+- [x] 2.4 Pass the logical dump database as a quoted one-field conninfo value and verify the dump argument test preserves `postgres dbname=databasus` as one database name
+
+## 3. Direct connection-test authorization
+
+- [x] 3.1 Add internal database-store and workspace-service seams for controlled controller failure tests, and verify production dependency wiring compiles through `make lint`
+- [x] 3.2 Require `workspaceId` and database-management permission for unsaved direct tests, verify the missing-workspace controller regression returns 400, and confirm the permission-denied branch returns before the connection path during implementation review
+- [x] 3.3 Load a saved target, authorize its persisted workspace, and only then merge request fields with saved credentials, and verify a viewer or nonmember cannot redirect the saved password while an authorized member can test it
+- [x] 3.4 Return the same 403 response for unknown and unauthorized saved IDs, and verify the controller responses are byte-equivalent JSON objects
+- [x] 3.5 Wrap saved-target and permission lookup failures with separate sentinels, map them to sanitized HTTP 500 responses, and verify injected sensitive errors never appear in the response body
+- [x] 3.6 Split the trusted healthcheck connection path from the user-authorized direct endpoint, update its interface and mocks, and verify `go test -count=1 ./internal/features/healthcheck/attempt` passes
+
+## 4. Embedded PostgreSQL runtime isolation
+
+- [x] 4.1 Create `/databasus-data/pgsocket` for the PostgreSQL account with mode `0700`, start PostgreSQL there, and verify the Databasus application account cannot connect through the socket
+- [x] 4.2 Rewrite the internal HBA policy at startup to allow PostgreSQL peer administration, reject other local socket users and replication, and require SCRAM over loopback TCP; verify the running container reports the expected rules
+- [x] 4.3 Generate a random internal PostgreSQL password at each startup, set it through the private socket, and export a matching `DATABASE_DSN` only when the operator did not supply one; verify the container becomes healthy and the password verifier changes after restart
+- [x] 4.4 Update legacy WAL checks to use the generated credential without logging it, and verify startup completes against an existing metadata database
+- [x] 4.5 Reject a requested PostgreSQL UID owned by another image account, and verify `PUID=65532` exits with code 1 while an unused `PUID=23456` starts healthy under that UID
+- [x] 4.6 Verify the previously published fixed password fails over loopback TCP and no PostgreSQL socket is created under `/tmp`
+
+## 5. Final verification
+
+- [x] 5.1 Run `make lint` from `backend/` and verify it reports `0 issues`
+- [x] 5.2 Run `make test-fedora` from `backend/` and verify the complete backend suite passes in the supported Fedora host-native environment
+- [x] 5.3 Re-run all packages touched by the final review fixes with `go test -count=1` and verify the database, PostgreSQL shared/logical/physical, logical backup, and healthcheck packages pass
+- [x] 5.4 Run `docker build --check .` and a full image build, then verify collision and non-conflicting custom-UID smoke scenarios
+- [x] 5.5 Complete the mandatory planning and implementation reviews against `AGENTS.md` and `backend/AGENTS.md`, resolve every required change, and verify the final implementation review reports `PASS`
+- [x] 5.6 Run `git diff --check`, remove test containers and images, and verify the working tree contains only the implementation and this completed OpenSpec change
diff --git a/openspec/specs/internal-postgresql-protection/spec.md b/openspec/specs/internal-postgresql-protection/spec.md
new file mode 100644
index 00000000..af557736
--- /dev/null
+++ b/openspec/specs/internal-postgresql-protection/spec.md
@@ -0,0 +1,244 @@
+# Internal PostgreSQL Protection Specification
+
+## Purpose
+
+Prevents workspace-controlled PostgreSQL connections and backups from reading the Databasus metadata database or sending another workspace's saved credentials to a caller-controlled server.
+
+## Requirements
+
+### Requirement: Logical backups cannot target the embedded metadata database
+
+The system SHALL reject a logical PostgreSQL source when its database name is `databasus` and any effective host points back to the Databasus container. Local targets include filesystem and abstract Unix sockets, loopback and unspecified IP addresses, supported container-local aliases, libc-compatible numeric IPv4 forms, and an empty entry in a comma-separated host list.
+
+The system SHALL inspect every host in a multi-host value. A remote entry SHALL NOT make a later local entry acceptable.
+
+#### Scenario: Filesystem Unix socket
+
+- **WHEN** a user configures a logical PostgreSQL source with database `databasus` and a filesystem Unix-socket directory as its host
+- **THEN** the system rejects the source before opening the connection
+
+#### Scenario: Abstract Unix socket
+
+- **WHEN** a user configures database `databasus` with an abstract Unix-socket host
+- **THEN** the system rejects the source before opening the connection
+
+#### Scenario: Loopback address in a host list
+
+- **WHEN** a PostgreSQL host list contains a remote hostname followed by a loopback address and the database is `databasus`
+- **THEN** the system rejects the whole source
+
+#### Scenario: Numeric loopback spelling
+
+- **WHEN** a user specifies a loopback address in an abbreviated, integer, octal, or hexadecimal form accepted by the operating-system resolver
+- **THEN** the system treats it as local and rejects database `databasus`
+
+#### Scenario: Local application database
+
+- **WHEN** a user configures a local PostgreSQL source whose database name is not `databasus`
+- **THEN** the embedded-target rule allows the source
+
+#### Scenario: Remote database with the same name
+
+- **WHEN** a PostgreSQL source is remote and its database name is `databasus`
+- **THEN** the embedded-target rule allows the source
+
+### Requirement: Physical backups cannot target the embedded PostgreSQL cluster
+
+The system SHALL reject a physical PostgreSQL source when an effective local host uses the embedded cluster's port. This rule SHALL apply without relying on a database name because a physical backup addresses the cluster rather than one logical database.
+
+#### Scenario: Embedded cluster through a Unix socket
+
+- **WHEN** a user configures a physical backup against a local Unix socket and the embedded PostgreSQL port
+- **THEN** the system rejects the source before any physical backup connection is opened
+
+#### Scenario: Different local PostgreSQL instance
+
+- **WHEN** a physical source uses a local address on a port other than the embedded PostgreSQL port
+- **THEN** the embedded-target rule allows the source
+
+### Requirement: Remote SSH targets keep their remote meaning
+
+When a database is reached through an SSH bastion on another host, a loopback database address SHALL be interpreted relative to that remote host. A local SSH bastion SHALL NOT relax the embedded-target rules.
+
+#### Scenario: Database bound to loopback on a remote bastion
+
+- **WHEN** SSH tunneling is enabled through a non-local bastion and the PostgreSQL host is a loopback address
+- **THEN** the embedded-target rule allows the source
+
+#### Scenario: Local bastion points back to the container
+
+- **WHEN** SSH tunneling names a local bastion and the PostgreSQL target matches the embedded instance
+- **THEN** the system rejects the source
+
+### Requirement: Persisted configurations are checked at connection time
+
+The system SHALL apply embedded-target protection immediately before a PostgreSQL connection is opened, including connections created from rows saved before this policy existed. Model validation alone SHALL NOT be the only enforcement point.
+
+#### Scenario: Existing logical row contains a socket target
+
+- **WHEN** a previously saved logical source names the embedded database through a local socket
+- **THEN** a backup, connection test, or healthcheck refuses to open that connection
+
+#### Scenario: Existing physical row contains the embedded cluster
+
+- **WHEN** a previously saved physical source names the embedded PostgreSQL cluster
+- **THEN** physical connection and backup paths refuse to open that connection
+
+### Requirement: PostgreSQL connection values remain literal
+
+Every user-controlled string used in a PostgreSQL conninfo value SHALL be interpreted as one value. Whitespace, quotes, backslashes, equal signs, and text resembling another conninfo parameter SHALL NOT create or replace connection parameters.
+
+The database name passed to a logical dump SHALL follow the same rule even when the dump tool accepts a conninfo string in place of a plain database name.
+
+#### Scenario: Database name contains a second database parameter
+
+- **WHEN** a database name contains `dbname=databasus` after another value
+- **THEN** PostgreSQL receives the complete input as one literal database name
+- **AND** the text cannot redirect the connection to the embedded database
+
+#### Scenario: Other credential fields contain conninfo syntax
+
+- **WHEN** a host, username, password, TLS mode, or certificate path contains whitespace or conninfo metacharacters
+- **THEN** the connection parser returns the original field value without creating another parameter
+
+### Requirement: Direct connection tests require workspace authorization
+
+The direct connection-test endpoint SHALL require an authenticated user who can manage databases in the relevant workspace. An ad hoc database SHALL identify that workspace. A request referencing a saved database SHALL be authorized against the workspace stored on that database before saved credentials are merged with request fields.
+
+#### Scenario: Ad hoc request without a workspace
+
+- **WHEN** an authenticated user submits an unsaved database without `workspaceId`
+- **THEN** the endpoint returns HTTP 400
+- **AND** no connection is attempted
+
+#### Scenario: Ad hoc request for an unauthorized workspace
+
+- **WHEN** an authenticated user submits an unsaved database for a workspace where they cannot manage databases
+- **THEN** the endpoint returns HTTP 403
+- **AND** no connection is attempted
+
+#### Scenario: Saved database from another workspace
+
+- **WHEN** a user references a saved database outside a workspace they can manage and supplies a different host
+- **THEN** the endpoint returns HTTP 403 before applying the saved password
+- **AND** the system makes no connection to the supplied host
+
+#### Scenario: Authorized workspace member tests a saved database
+
+- **WHEN** a workspace member who can manage databases tests a saved database in that workspace and leaves its password blank
+- **THEN** the system may use the saved password and performs the connection test
+
+### Requirement: Direct connection-test failures do not disclose protected records or internal errors
+
+The endpoint SHALL return the same HTTP 403 response for an unknown saved database and a saved database the caller cannot manage. Storage failures while loading a saved target and failures while checking workspace permissions SHALL return distinct, sanitized HTTP 500 messages that do not include the underlying error.
+
+#### Scenario: Unknown saved database ID
+
+- **WHEN** a caller submits an ID that does not identify a saved database
+- **THEN** the endpoint returns the same HTTP 403 body used for an unauthorized saved database
+
+#### Scenario: Saved target lookup fails internally
+
+- **WHEN** storage fails while loading the referenced saved database
+- **THEN** the endpoint returns HTTP 500 with `failed to load database connection target`
+- **AND** the storage error is absent from the response
+
+#### Scenario: Permission lookup fails internally
+
+- **WHEN** the workspace permission lookup fails for either an ad hoc or saved database
+- **THEN** the endpoint returns HTTP 500 with `failed to verify database connection permissions`
+- **AND** the underlying membership error is absent from the response
+
+### Requirement: Healthchecks use a trusted internal connection path
+
+Scheduled healthchecks SHALL test a database already loaded by the system without pretending to be an end user. The user-facing direct endpoint SHALL NOT expose that trusted path or bypass its workspace checks.
+
+#### Scenario: Scheduled healthcheck
+
+- **WHEN** the healthcheck service loads a saved database and probes it
+- **THEN** the probe runs without an end-user principal
+- **AND** embedded-target protection still runs before the connection opens
+
+#### Scenario: User-facing direct test
+
+- **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
+
+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.
+
+#### 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
+
+#### Scenario: PostgreSQL account performs startup administration
+
+- **WHEN** the PostgreSQL operating-system account connects through the private socket during startup
+- **THEN** peer authentication 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: Replication connection to the embedded cluster
+
+- **WHEN** a client requests a replication connection to the embedded PostgreSQL server
+- **THEN** PostgreSQL rejects it
+
+### Requirement: Internal PostgreSQL credentials are generated at startup
+
+When Databasus uses its embedded metadata database, the container SHALL generate a cryptographically random PostgreSQL password at startup, set it on the internal role, and supply it to the application without logging it. A container restart SHALL replace the previous password. An explicitly supplied external metadata-database connection string SHALL remain unchanged.
+
+An operator-supplied connection string that points back to the embedded database with the previously published fixed password is incompatible with rotation and SHALL NOT be treated as a supported embedded-database configuration.
+
+#### Scenario: Fresh container startup
+
+- **WHEN** a container starts without an explicit metadata-database connection string
+- **THEN** it configures the embedded role and the application with the same generated password
+- **AND** the application becomes healthy without printing that password
+
+#### Scenario: Container restart
+
+- **WHEN** the same container restarts
+- **THEN** the embedded role receives a different generated password
+- **AND** the application reconnects with the new password
+
+#### Scenario: Previously published fixed password
+
+- **WHEN** a client attempts loopback TCP authentication with the old fixed image password
+- **THEN** PostgreSQL rejects the connection
+
+#### Scenario: External metadata database
+
+- **WHEN** the operator explicitly supplies a connection string for an external metadata database
+- **THEN** startup preserves that value rather than replacing it with the embedded database connection
+
+#### Scenario: Explicit connection string points 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