PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (postgresql): Add isSkipUserMappings to handle FDW user mapping
Rostislav Dugin0a9b3908a16a
diff --git a/backend/internal/features/databases/databases/postgresql/logical/model.go b/backend/internal/features/databases/databases/postgresql/logical/model.goindex a9a5f5f2..7a818410 100644--- a/backend/internal/features/databases/databases/postgresql/logical/model.go+++ b/backend/internal/features/databases/databases/postgresql/logical/model.go@@ -39,11 +39,12 @@ type PostgresqlLogicalDatabase struct {SslRootCert string `json:"sslRootCert" gorm:"column:ssl_root_cert;type:text;not null;default:''"`// backup settings- IncludeSchemas []string `json:"includeSchemas" gorm:"-"`- IncludeSchemasString string `json:"-" gorm:"column:include_schemas;type:text;not null;default:''"`- ExcludeTables []string `json:"excludeTables" gorm:"-"`- ExcludeTablesString string `json:"-" gorm:"column:exclude_tables;type:text;not null;default:''"`- CpuCount int `json:"cpuCount" gorm:"column:cpu_count;type:int;not null;default:1"`+ IncludeSchemas []string `json:"includeSchemas" gorm:"-"`+ IncludeSchemasString string `json:"-" gorm:"column:include_schemas;type:text;not null;default:''"`+ ExcludeTables []string `json:"excludeTables" gorm:"-"`+ ExcludeTablesString string `json:"-" gorm:"column:exclude_tables;type:text;not null;default:''"`+ CpuCount int `json:"cpuCount" gorm:"column:cpu_count;type:int;not null;default:1"`+ IsSkipUserMappings bool `json:"isSkipUserMappings" gorm:"column:is_skip_user_mappings;type:bool;not null;default:false"`// restore settings (not saved to DB)IsExcludeExtensions bool `json:"isExcludeExtensions" gorm:"-"`@@ -219,6 +220,7 @@ func (p *PostgresqlLogicalDatabase) Update(incoming *PostgresqlLogicalDatabase)p.IncludeSchemas = incoming.IncludeSchemasp.ExcludeTables = incoming.ExcludeTablesp.CpuCount = incoming.CpuCount+ p.IsSkipUserMappings = incoming.IsSkipUserMappingsif incoming.Password != "" {p.Password = incoming.Password@@ -949,6 +951,36 @@ func testSingleDatabaseConnection(return err}+ if !postgresDb.IsSkipUserMappings {+ if err := checkUserMappingsReadable(ctx, conn); err != nil {+ return err+ }+ }++ return nil+}++// PostgreSQL masks pg_user_mappings.umoptions (credentials) from any role that is not a superuser,+// the foreign server owner, or the mapping's own user. Such a role's pg_dump emits a bare CREATE+// USER MAPPING that loses the credentials and breaks restore for FDWs that require them (e.g.+// oracle_fdw), so refuse the backup when any mapping's options are hidden.+func checkUserMappingsReadable(ctx context.Context, conn *pgx.Conn) error {+ var unreadableCount int+ err := conn.QueryRow(ctx, "SELECT count(*) FROM pg_user_mappings WHERE umoptions IS NULL").+ Scan(&unreadableCount)+ if err != nil {+ return fmt.Errorf("cannot check user mapping options: %w", err)+ }++ if unreadableCount > 0 {+ return fmt.Errorf(+ "database has %d user mapping(s) whose options this role cannot read; their "++ "credentials would be lost on restore — back up as a superuser or the foreign "++ "server/mapping owner, or enable 'skip user mappings'",+ unreadableCount,+ )+ }+return nil}diff --git a/backend/internal/features/databases/databases/postgresql/logical/model_test.go b/backend/internal/features/databases/databases/postgresql/logical/model_test.goindex b2256904..4c888647 100644--- a/backend/internal/features/databases/databases/postgresql/logical/model_test.go+++ b/backend/internal/features/databases/databases/postgresql/logical/model_test.go@@ -173,10 +173,103 @@ func Test_PostgresqlModel_AcrossSupportedVersions(t *testing.T) {t.Run("Test_CreateReadOnlyUser_PublicSchemaExistsButNoPermissions_ReturnsError", func(t *testing.T) {testCreateReadOnlyUserPublicSchemaExistsButNoPermissions(t, endpoint, dbVersion.tag)})++ t.Run("Test_TestConnection_WhenUserMappingUnreadableAndFlagFalse_ReturnsError", func(t *testing.T) {+ testConnectionUserMappingUnreadableFlagFalse(t, endpoint, dbVersion.tag)+ })++ t.Run("Test_TestConnection_WhenUserMappingUnreadableAndFlagTrue_NoError", func(t *testing.T) {+ testConnectionUserMappingUnreadableFlagTrue(t, endpoint, dbVersion.tag)+ })})}}+// setupUnreadableUserMappingModel sets up a superuser-owned user mapping and a limited role that+// passes the backup-permission checks (CONNECT/USAGE/SELECT) yet cannot read the mapping's options.+// postgres_fdw stands in for oracle_fdw, which is not installable in CI.+func setupUnreadableUserMappingModel(+ t *testing.T,+ container *PostgresContainer,+ version string,+) *PostgresqlLogicalDatabase {+ suffix := uuid.New().String()[:8]+ limitedUsername := fmt.Sprintf("um_limited_%s", suffix)+ limitedPassword := "limitedpassword123"+ serverName := fmt.Sprintf("um_test_srv_%s", suffix)+ tableName := fmt.Sprintf("um_test_table_%s", suffix)++ setupStatements := []string{+ fmt.Sprintf(`CREATE TABLE %s (id SERIAL PRIMARY KEY, data TEXT NOT NULL)`, tableName),+ fmt.Sprintf(`INSERT INTO %s (data) VALUES ('row1')`, tableName),+ `CREATE EXTENSION IF NOT EXISTS postgres_fdw`,+ fmt.Sprintf(+ `CREATE SERVER %s FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname 'postgres')`,+ serverName,+ ),+ fmt.Sprintf(+ `CREATE USER MAPPING FOR CURRENT_USER SERVER %s OPTIONS ("user" 'remote', password 'secret')`,+ serverName,+ ),+ fmt.Sprintf(`CREATE USER "%s" WITH PASSWORD '%s' LOGIN`, limitedUsername, limitedPassword),+ fmt.Sprintf(`GRANT CONNECT ON DATABASE "%s" TO "%s"`, container.Database, limitedUsername),+ fmt.Sprintf(`GRANT USAGE ON SCHEMA public TO "%s"`, limitedUsername),+ fmt.Sprintf(`GRANT SELECT ON %s TO "%s"`, tableName, limitedUsername),+ }++ for _, statement := range setupStatements {+ _, err := container.DB.Exec(statement)+ assert.NoError(t, err)+ }++ t.Cleanup(func() {+ _, _ = container.DB.Exec(fmt.Sprintf(`DROP SERVER IF EXISTS %s CASCADE`, serverName))+ _, _ = container.DB.Exec(fmt.Sprintf(`DROP TABLE IF EXISTS %s CASCADE`, tableName))+ _, _ = container.DB.Exec(fmt.Sprintf(`DROP OWNED BY "%s"`, limitedUsername))+ _, _ = container.DB.Exec(fmt.Sprintf(`DROP USER IF EXISTS "%s"`, limitedUsername))+ })++ return &PostgresqlLogicalDatabase{+ Version: tools.GetPostgresqlVersionEnum(version),+ Host: container.Host,+ Port: container.Port,+ Username: limitedUsername,+ Password: limitedPassword,+ Database: &container.Database,+ SslMode: postgresql_shared.PostgresSslModeDisable,+ CpuCount: 1,+ }+}++func testConnectionUserMappingUnreadableFlagFalse(t *testing.T, endpoint containers.Endpoint, version string) {+ container := connectToPostgresEndpoint(t, endpoint)+ defer container.DB.Close()++ limitedModel := setupUnreadableUserMappingModel(t, container, version)+ limitedModel.IsSkipUserMappings = false++ logger := slog.New(slog.NewTextHandler(os.Stdout, nil))++ err := limitedModel.TestConnection(logger, nil)+ assert.Error(t, err)+ if err != nil {+ assert.Contains(t, err.Error(), "user mapping")+ }+}++func testConnectionUserMappingUnreadableFlagTrue(t *testing.T, endpoint containers.Endpoint, version string) {+ container := connectToPostgresEndpoint(t, endpoint)+ defer container.DB.Close()++ limitedModel := setupUnreadableUserMappingModel(t, container, version)+ limitedModel.IsSkipUserMappings = true++ logger := slog.New(slog.NewTextHandler(os.Stdout, nil))++ err := limitedModel.TestConnection(logger, nil)+ assert.NoError(t, err)+}+func testConnectionInsufficientPermissions(t *testing.T, endpoint containers.Endpoint, version string) {container := connectToPostgresEndpoint(t, endpoint)defer container.DB.Close()diff --git a/backend/internal/features/restores/core/dto.go b/backend/internal/features/restores/core/dto.goindex 46ebc42e..39759308 100644--- a/backend/internal/features/restores/core/dto.go+++ b/backend/internal/features/restores/core/dto.go@@ -13,3 +13,8 @@ type RestoreBackupRequest struct {MariadbDatabase *mariadb.MariadbDatabase `json:"mariadbDatabase"`MongodbDatabase *mongodb.MongodbDatabase `json:"mongodbDatabase"`}++type RestoreOptions struct {+ IsExcludeExtensions bool+ IsSkipUserMappings bool+}diff --git a/backend/internal/features/restores/core/interfaces.go b/backend/internal/features/restores/core/interfaces.goindex 649c7ea8..18f049c8 100644--- a/backend/internal/features/restores/core/interfaces.go+++ b/backend/internal/features/restores/core/interfaces.go@@ -18,6 +18,6 @@ type RestoreBackupUsecase interface {restoringToDB *databases.Database,backup *backups_core_logical.LogicalBackup,storage *storages.Storage,- isExcludeExtensions bool,+ options RestoreOptions,) error}diff --git a/backend/internal/features/restores/restoring/mocks.go b/backend/internal/features/restores/restoring/mocks.goindex 51df8126..8e0d21c5 100644--- a/backend/internal/features/restores/restoring/mocks.go+++ b/backend/internal/features/restores/restoring/mocks.go@@ -21,7 +21,7 @@ func (uc *MockSuccessRestoreUsecase) Execute(restoringToDB *databases.Database,backup *backups_core_logical.LogicalBackup,storage *storages.Storage,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {return nil}@@ -36,7 +36,7 @@ func (uc *MockFailedRestoreUsecase) Execute(restoringToDB *databases.Database,backup *backups_core_logical.LogicalBackup,storage *storages.Storage,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {return errors.New("restore failed")}@@ -54,7 +54,7 @@ func (uc *MockCaptureCredentialsRestoreUsecase) Execute(restoringToDB *databases.Database,backup *backups_core_logical.LogicalBackup,storage *storages.Storage,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {uc.CalledChan <- restoringToDB@@ -76,7 +76,7 @@ func (uc *MockBlockingRestoreUsecase) Execute(restoringToDB *databases.Database,backup *backups_core_logical.LogicalBackup,storage *storages.Storage,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {if uc.StartedChan != nil {uc.StartedChan <- truediff --git a/backend/internal/features/restores/restoring/restorer.go b/backend/internal/features/restores/restoring/restorer.goindex f934c107..8ff934d4 100644--- a/backend/internal/features/restores/restoring/restorer.go+++ b/backend/internal/features/restores/restoring/restorer.go@@ -129,9 +129,14 @@ func (r *Restorer) MakeRestore(restoreID uuid.UUID) {return}- isExcludeExtensions := false+ // IsExcludeExtensions is a transient choice carried on the target config from the restore+ // request; IsSkipUserMappings is a persisted property of the source database being restored.+ restoreOptions := restores_core.RestoreOptions{}if dbCache.PostgresqlLogicalDatabase != nil {- isExcludeExtensions = dbCache.PostgresqlLogicalDatabase.IsExcludeExtensions+ restoreOptions.IsExcludeExtensions = dbCache.PostgresqlLogicalDatabase.IsExcludeExtensions+ }+ if database.PostgresqlLogical != nil {+ restoreOptions.IsSkipUserMappings = database.PostgresqlLogical.IsSkipUserMappings}err = r.restoreBackupUsecase.Execute(@@ -142,7 +147,7 @@ func (r *Restorer) MakeRestore(restoreID uuid.UUID) {restoringToDB,backup,storage,- isExcludeExtensions,+ restoreOptions,)if err != nil {errMsg := err.Error()diff --git a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.goindex 9f24daf9..a85703a9 100644--- a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go+++ b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go@@ -44,7 +44,7 @@ func (uc *RestorePostgresqlBackupUsecase) Execute(restore restores_core.Restore,backup *backups_core_logical.LogicalBackup,storage *storages.Storage,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {if originalDB.Type != databases.DatabaseTypePostgresLogical {return errors.New("database type not supported")@@ -77,7 +77,7 @@ func (uc *RestorePostgresqlBackupUsecase) Execute(backup,storage,pg,- isExcludeExtensions,+ options,)}@@ -89,7 +89,7 @@ func (uc *RestorePostgresqlBackupUsecase) restoreCustomType(backup *backups_core_logical.LogicalBackup,storage *storages.Storage,pg *pgtypes.PostgresqlLogicalDatabase,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {uc.logger.Info("Restoring backup in custom type (-Fc)",@@ -99,12 +99,13 @@ func (uc *RestorePostgresqlBackupUsecase) restoreCustomType(pg.CpuCount,)- // File-based restore for parallel jobs (multiple CPUs) or extension exclusion (needs a TOC file);- // otherwise stream directly via stdin. A timescaledb backup uses whichever path applies — the- // pre/post hooks wrap it the same way (they only set a database-level GUC, so streaming is kept).+ // File-based restore for parallel jobs (multiple CPUs) or any TOC filtering (extension exclusion+ // or skipping user mappings needs a TOC file); otherwise stream directly via stdin. A timescaledb+ // backup uses whichever path applies — the pre/post hooks wrap it the same way (they only set a+ // database-level GUC, so streaming is kept).runRestore := func() error {- if isExcludeExtensions || pg.CpuCount > 1 {- return uc.restoreViaFile(parentCtx, originalDB, pgBin, backup, storage, pg, isExcludeExtensions)+ if options.IsExcludeExtensions || options.IsSkipUserMappings || pg.CpuCount > 1 {+ return uc.restoreViaFile(parentCtx, originalDB, pgBin, backup, storage, pg, options)}return uc.restoreViaStdin(parentCtx, originalDB, pgBin, backup, storage, pg)@@ -378,7 +379,7 @@ func (uc *RestorePostgresqlBackupUsecase) restoreViaFile(backup *backups_core_logical.LogicalBackup,storage *storages.Storage,pg *pgtypes.PostgresqlLogicalDatabase,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {uc.logger.Info("Restoring via file with parallel jobs",@@ -429,7 +430,7 @@ func (uc *RestorePostgresqlBackupUsecase) restoreViaFile(backup,storage,pg,- isExcludeExtensions,+ options,)}@@ -443,7 +444,7 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage(backup *backups_core_logical.LogicalBackup,storage *storages.Storage,pgConfig *pgtypes.PostgresqlLogicalDatabase,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {uc.logger.Info("Restoring PostgreSQL backup from storage via temporary file",@@ -452,7 +453,9 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage("args",args,"isExcludeExtensions",- isExcludeExtensions,+ options.IsExcludeExtensions,+ "isSkipUserMappings",+ options.IsSkipUserMappings,)ctx, cancel := context.WithTimeout(parentCtx, 23*time.Hour)@@ -497,14 +500,14 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage(}defer cleanupFunc()- // If excluding extensions, generate filtered TOC list and use it- if isExcludeExtensions {+ if options.IsExcludeExtensions || options.IsSkipUserMappings {tocListFile, err := uc.generateFilteredTocList(ctx,pgBin,tempBackupFile,credentials,pgConfig,+ options,)if err != nil {return fmt.Errorf("failed to generate filtered TOC list: %w", err)@@ -913,16 +916,17 @@ func containsIgnoreCase(str, substr string) bool {return strings.Contains(strings.ToLower(str), strings.ToLower(substr))}-// generateFilteredTocList generates a pg_restore TOC list file with extensions filtered out.-// This is used when isExcludeExtensions is true to skip CREATE EXTENSION statements.+// generateFilteredTocList writes a pg_restore TOC list (for -L) with the object classes selected+// by options dropped, so pg_restore skips them.func (uc *RestorePostgresqlBackupUsecase) generateFilteredTocList(ctx context.Context,pgBin string,backupFile string,credentials *postgresql_shared.CredentialTempFiles,pgConfig *pgtypes.PostgresqlLogicalDatabase,+ options restores_core.RestoreOptions,) (string, error) {- uc.logger.Info("Generating filtered TOC list to exclude extensions", "backupFile", backupFile)+ uc.logger.Info("Generating filtered TOC list", "backupFile", backupFile)// Run pg_restore -l to get the TOC listlistCmd := exec.CommandContext(ctx, pgBin, "-l", backupFile)@@ -933,7 +937,17 @@ func (uc *RestorePostgresqlBackupUsecase) generateFilteredTocList(return "", fmt.Errorf("failed to generate TOC list: %w", err)}- // Filter out EXTENSION-related lines (both CREATE EXTENSION and COMMENT ON EXTENSION)+ // " EXTENSION " catches both CREATE EXTENSION ("3420; 0 0 EXTENSION - uuid-ossp") and+ // COMMENT ON EXTENSION ("3462; 0 0 COMMENT - EXTENSION "uuid-ossp"") entries.+ isExtensionEntry := func(upperLine string) bool {+ return strings.Contains(upperLine, " EXTENSION ")+ }+ // " USER MAPPING " catches CREATE USER MAPPING entries+ // ("18239; 0 0 USER MAPPING - platform SERVER oracle_tb_server").+ isUserMappingEntry := func(upperLine string) bool {+ return strings.Contains(upperLine, " USER MAPPING ")+ }+var filteredLines []stringfor line := range strings.SplitSeq(string(tocOutput), "\n") {trimmedLine := strings.TrimSpace(line)@@ -943,14 +957,16 @@ func (uc *RestorePostgresqlBackupUsecase) generateFilteredTocList(upperLine := strings.ToUpper(trimmedLine)- // Skip lines that contain " EXTENSION " - this catches both:- // - CREATE EXTENSION entries: "3420; 0 0 EXTENSION - uuid-ossp"- // - COMMENT ON EXTENSION entries: "3462; 0 0 COMMENT - EXTENSION "uuid-ossp""- if strings.Contains(upperLine, " EXTENSION ") {+ if options.IsExcludeExtensions && isExtensionEntry(upperLine) {uc.logger.Info("Excluding extension-related entry from restore", "tocLine", trimmedLine)continue}+ if options.IsSkipUserMappings && isUserMappingEntry(upperLine) {+ uc.logger.Info("Excluding user mapping entry from restore", "tocLine", trimmedLine)+ continue+ }+filteredLines = append(filteredLines, line)}diff --git a/backend/internal/features/restores/usecases/restore_backup_uc.go b/backend/internal/features/restores/usecases/restore_backup_uc.goindex 2bed3df3..e08c7d8f 100644--- a/backend/internal/features/restores/usecases/restore_backup_uc.go+++ b/backend/internal/features/restores/usecases/restore_backup_uc.go@@ -30,7 +30,7 @@ func (uc *RestoreBackupUsecase) Execute(restoringToDB *databases.Database,backup *backups_core_logical.LogicalBackup,storage *storages.Storage,- isExcludeExtensions bool,+ options restores_core.RestoreOptions,) error {switch originalDB.Type {case databases.DatabaseTypePostgresLogical:@@ -42,7 +42,7 @@ func (uc *RestoreBackupUsecase) Execute(restore,backup,storage,- isExcludeExtensions,+ options,)case databases.DatabaseTypeMysql:return uc.restoreMysqlBackupUsecase.Execute(diff --git a/backend/internal/features/tests/logical/postgresql/backup_restore_test.go b/backend/internal/features/tests/logical/postgresql/backup_restore_test.goindex 41c2cd68..71909337 100644--- a/backend/internal/features/tests/logical/postgresql/backup_restore_test.go+++ b/backend/internal/features/tests/logical/postgresql/backup_restore_test.go@@ -145,6 +145,10 @@ func Test_PostgresqlBackupRestore_AcrossSupportedVersions(t *testing.T) {t.Run("Test_BackupAndRestorePostgresql_WithReadOnlyUser_RestoreIsSuccessful", func(t *testing.T) {testBackupRestoreWithReadOnlyUserForVersion(t, endpoint, dbVersion.tag)})++ t.Run("Test_BackupAndRestorePostgresql_WithSkipUserMappings_RestoreIsSuccessful", func(t *testing.T) {+ testBackupRestoreSkipUserMappingsForVersion(t, endpoint, dbVersion.tag)+ })})}}@@ -508,6 +512,132 @@ func testBackupRestoreWithExcludeExtensionsForVersion(t *testing.T, endpoint conworkspaces_testing.RemoveTestWorkspace(workspace, router)}+// testBackupRestoreSkipUserMappingsForVersion backs up under a role that cannot read a user+// mapping's options (so pg_dump emits a bare CREATE USER MAPPING) with IsSkipUserMappings enabled,+// and asserts the restore succeeds with the mapping excluded. postgres_fdw stands in for+// oracle_fdw, which is not installable in CI.+func testBackupRestoreSkipUserMappingsForVersion(t *testing.T, endpoint containers.Endpoint, pgVersion string) {+ container, err := connectToPostgresEndpoint(t, endpoint)+ if err != nil {+ t.Fatalf("Failed to connect to PostgreSQL container: %v", err)+ }+ defer container.DB.Close()++ suffix := uuid.New().String()[:8]+ limitedUsername := fmt.Sprintf("um_backup_%s", suffix)+ limitedPassword := "limitedpassword123"+ serverName := fmt.Sprintf("um_srv_%s", suffix)++ setupStatements := []string{+ `CREATE TABLE skip_um_data (id INT PRIMARY KEY, name TEXT NOT NULL)`,+ `INSERT INTO skip_um_data (id, name) VALUES (1, 'row1'), (2, 'row2'), (3, 'row3')`,+ `CREATE EXTENSION IF NOT EXISTS postgres_fdw`,+ fmt.Sprintf(+ `CREATE SERVER %s FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname 'postgres')`,+ serverName,+ ),+ fmt.Sprintf(+ `CREATE USER MAPPING FOR CURRENT_USER SERVER %s OPTIONS ("user" 'remote', password 'secret')`,+ serverName,+ ),+ fmt.Sprintf(`CREATE USER "%s" WITH PASSWORD '%s' LOGIN`, limitedUsername, limitedPassword),+ fmt.Sprintf(`GRANT CONNECT ON DATABASE "%s" TO "%s"`, container.Database, limitedUsername),+ fmt.Sprintf(`GRANT USAGE ON SCHEMA public TO "%s"`, limitedUsername),+ `GRANT SELECT ON skip_um_data TO "` + limitedUsername + `"`,+ }++ for _, statement := range setupStatements {+ _, err = container.DB.Exec(statement)+ assert.NoError(t, err)+ }++ defer func() {+ _, _ = container.DB.Exec(fmt.Sprintf(`DROP SERVER IF EXISTS %s CASCADE`, serverName))+ _, _ = container.DB.Exec(`DROP TABLE IF EXISTS skip_um_data CASCADE`)+ _, _ = container.DB.Exec(fmt.Sprintf(`DROP OWNED BY "%s"`, limitedUsername))+ _, _ = container.DB.Exec(fmt.Sprintf(`DROP USER IF EXISTS "%s"`, limitedUsername))+ }()++ router := logicaltesting.CreateTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Skip User Mappings Workspace", user, router)++ storage := storages.CreateTestStorage(workspace.ID)++ // Created under the limited role with IsSkipUserMappings enabled, so TestConnection's+ // unreadable-user-mapping gate is bypassed and the backup runs as that role.+ database := createDatabaseWithSkipUserMappingsViaAPI(+ t, router, "Skip User Mappings Database", workspace.ID,+ container.Host, container.Port,+ limitedUsername, limitedPassword, container.Database,+ user.Token,+ )++ logicaltesting.EnableBackupsViaAPI(+ t, router, database.ID, storage.ID,+ backups_core_enums.BackupEncryptionNone, user.Token,+ )++ logicaltesting.CreateBackupViaAPI(t, router, database.ID, user.Token)++ backup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)+ assert.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)++ newDBName := fmt.Sprintf("restored_skip_um_%s_%s", pgVersion, suffix)+ _, err = container.DB.Exec(fmt.Sprintf("CREATE DATABASE %s;", newDBName))+ assert.NoError(t, err)++ defer func() {+ _, _ = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))+ }()++ newDSN := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",+ container.Host, container.Port, container.Username, container.Password, newDBName)+ newDB, err := sqlx.Connect("postgres", newDSN)+ assert.NoError(t, err)+ defer newDB.Close()++ // Restore connects as the admin so the dumped extension/server can be created; the source+ // database's persisted IsSkipUserMappings flag drives the user-mapping exclusion.+ createRestoreViaAPI(+ t, router, backup.ID,+ container.Host, container.Port,+ container.Username, container.Password, newDBName,+ user.Token,+ )++ restore := waitForRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)+ assert.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)++ var rowCount int+ err = newDB.Get(&rowCount, `SELECT COUNT(*) FROM skip_um_data`)+ assert.NoError(t, err)+ assert.Equal(t, 3, rowCount, "table data should be restored")++ var userMappingCount int+ err = newDB.Get(&userMappingCount,+ `SELECT COUNT(*) FROM pg_user_mappings um+ JOIN pg_foreign_server s ON s.oid = um.srvid+ WHERE s.srvname = $1`, serverName)+ assert.NoError(t, err)+ assert.Equal(t, 0, userMappingCount, "user mapping should be excluded from the restore")++ err = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))+ if err != nil {+ t.Logf("Warning: Failed to delete backup file: %v", err)+ }++ test_utils.MakeDeleteRequest(+ t,+ router,+ "/api/v1/databases/"+database.ID.String(),+ "Bearer "+user.Token,+ http.StatusNoContent,+ )+ storages.RemoveTestStorage(storage.ID)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}+func testBackupRestoreWithoutExcludeExtensionsForVersion(t *testing.T,endpoint containers.Endpoint,@@ -1622,6 +1752,53 @@ func createDatabaseWithCpuCountViaAPI(return &createdDatabase}+func createDatabaseWithSkipUserMappingsViaAPI(+ t *testing.T,+ router *gin.Engine,+ name string,+ workspaceID uuid.UUID,+ host string,+ port int,+ username string,+ password string,+ database string,+ token string,+) *databases.Database {+ request := databases.Database{+ Name: name,+ WorkspaceID: &workspaceID,+ Type: databases.DatabaseTypePostgresLogical,+ PostgresqlLogical: &pgtypes.PostgresqlLogicalDatabase{+ Host: host,+ Port: port,+ Username: username,+ Password: password,+ Database: &database,+ CpuCount: 1,+ IsSkipUserMappings: true,+ },+ }++ w := workspaces_testing.MakeAPIRequest(+ router,+ "POST",+ "/api/v1/databases/create",+ "Bearer "+token,+ request,+ )++ if w.Code != http.StatusCreated {+ t.Fatalf("Failed to create database. Status: %d, Body: %s", w.Code, w.Body.String())+ }++ var createdDatabase databases.Database+ if err := json.Unmarshal(w.Body.Bytes(), &createdDatabase); err != nil {+ t.Fatalf("Failed to unmarshal database response: %v", err)+ }++ return &createdDatabase+}+func createRestoreViaAPI(t *testing.T,router *gin.Engine,diff --git a/backend/migrations/20260618121514_add_skip_user_mappings_to_postgresql_logical_databases.sql b/backend/migrations/20260618121514_add_skip_user_mappings_to_postgresql_logical_databases.sqlnew file mode 100644index 00000000..bff819ea--- /dev/null+++ b/backend/migrations/20260618121514_add_skip_user_mappings_to_postgresql_logical_databases.sql@@ -0,0 +1,11 @@+-- +goose Up+-- +goose StatementBegin+ALTER TABLE postgresql_logical_databases+ ADD COLUMN is_skip_user_mappings BOOLEAN NOT NULL DEFAULT FALSE;+-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin+ALTER TABLE postgresql_logical_databases+ DROP COLUMN is_skip_user_mappings;+-- +goose StatementEnddiff --git a/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.ts b/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.tsindex af44ea6e..a4839df1 100644--- a/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.ts+++ b/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.ts@@ -22,6 +22,7 @@ export interface PostgresqlLogicalDatabase {includeSchemas?: string[];excludeTables?: string[];cpuCount: number;+ isSkipUserMappings?: boolean;// restore settings (not saved to DB)isExcludeExtensions?: boolean;diff --git a/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsxindex 2e2e16db..bd357b81 100644--- a/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx@@ -89,7 +89,8 @@ export const EditPostgreSqlLogicalSpecificDataComponent = ({!!database.postgresqlLogical?.isRestoreOwnership ||!!database.postgresqlLogical?.isRestorePrivileges: !!database.postgresqlLogical?.includeSchemas?.length ||- !!database.postgresqlLogical?.excludeTables?.length);+ !!database.postgresqlLogical?.excludeTables?.length ||+ !!database.postgresqlLogical?.isSkipUserMappings);const [isShowAdvanced, setShowAdvanced] = useState(hasAdvancedValues);const [hasAutoAddedPublicSchema, setHasAutoAddedPublicSchema] = useState(false);@@ -688,6 +689,34 @@ export const EditPostgreSqlLogicalSpecificDataComponent = ({</div>)}+ {!isRestoreMode && (+ <div className="mb-1 flex w-full items-center">+ <div className="flex min-w-[150px] items-center">+ <span>Skip user mappings</span>+ <Tooltip+ className="cursor-pointer"+ title="Skip restoring user mappings (CREATE USER MAPPING statements). Enable this when the backup role cannot read the mapping credentials - otherwise they are dumped without options and break restore for FDWs like oracle_fdw."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ <Checkbox+ checked={editingDatabase.postgresqlLogical?.isSkipUserMappings || false}+ onChange={(e) => {+ if (!editingDatabase.postgresqlLogical) return;++ setEditingDatabase({+ ...editingDatabase,+ postgresqlLogical: {+ ...editingDatabase.postgresqlLogical,+ isSkipUserMappings: e.target.checked,+ },+ });+ }}+ />+ </div>+ )}+{isRestoreMode && (<div className="mb-1 flex w-full items-center"><div className="flex min-w-[150px] items-center">diff --git a/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsxindex 2d1bc420..903dbaae 100644--- a/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsx@@ -84,6 +84,13 @@ export const ShowPostgreSqlLogicalSpecificDataComponent = ({ database }: Props)<div>{database.postgresqlLogical.excludeTables.join(', ')}</div></div>)}++ {!!database.postgresqlLogical?.isSkipUserMappings && (+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">Skip user mappings</div>+ <div>Yes</div>+ </div>+ )}</div>);};