PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (databases): Back up and restore logical databases through an SSH bastion
Rostislav Dugin10e04b18826d
diff --git a/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.goindex 00010d80..bd044a6d 100644--- a/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go@@ -72,47 +72,54 @@ func (uc *CreateMariadbBackupUsecase) Execute(storage *storages.Storage,backupProgressListener func(completedMBs float64),) (*backups_core_logical.BackupMetadata, error) {- uc.logger.Info(- "Creating MariaDB backup via mariadb-dump",- "databaseId", db.ID,- "storageId", storage.ID,- )+ logger := uc.logger.With("database_id", db.ID, "storage_id", storage.ID)++ logger.Info("creating mariadb backup via mariadb-dump")++ tunneledDatabase, err := databases.OpenTunnel(ctx, databases.OpenTunnelSpec{+ Database: db,+ Logger: logger,+ Encryptor: uc.fieldEncryptor,+ })+ if err != nil {+ return nil, err+ }++ defer tunneledDatabase.Close()- mdb := db.Mariadb- if mdb == nil {+ mariadbDatabase := tunneledDatabase.GetDatabaseThroughTunnel().Mariadb+ if mariadbDatabase == nil {return nil, fmt.Errorf("mariadb database configuration is required")}- if mdb.Database == nil || *mdb.Database == "" {+ if mariadbDatabase.Database == nil || *mariadbDatabase.Database == "" {return nil, fmt.Errorf("database name is required for mariadb-dump backups")}- decryptedPassword, err := uc.fieldEncryptor.Decrypt(mdb.Password)+ decryptedPassword, err := uc.fieldEncryptor.Decrypt(mariadbDatabase.Password)if err != nil {return nil, fmt.Errorf("failed to decrypt database password: %w", err)}- rawSizeMB, err := mdb.GetRawDbSizeMb(ctx, uc.logger, uc.fieldEncryptor)+ rawSizeMB, err := mariadbDatabase.GetRawDbSizeMb(ctx, logger, uc.fieldEncryptor)if err != nil {- uc.logger.Warn("failed to fetch raw db size before backup",- "database_id", db.ID,- "error", err)+ logger.Warn("failed to fetch raw db size before backup", "error", err)} else {backup.BackupRawDbSizeMb = rawSizeMB}- args := uc.buildMariadbDumpArgs(mdb)+ args := uc.buildMariadbDumpArgs(mariadbDatabase)return uc.streamToStorage(ctx,backup,backupConfig,- tools.GetMariadbExecutable(mdb.Version, tools.MariadbExecutableMariadbDump),+ tools.GetMariadbExecutable(mariadbDatabase.Version, tools.MariadbExecutableMariadbDump),args,decryptedPassword,storage,backupProgressListener,- mdb,+ mariadbDatabase,)}diff --git a/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.goindex 51c9d6f4..89930b1d 100644--- a/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.go@@ -58,36 +58,43 @@ func (uc *CreateMongodbBackupUsecase) Execute(storage *storages.Storage,backupProgressListener func(completedMBs float64),) (*backups_core_logical.BackupMetadata, error) {- uc.logger.Info(- "Creating MongoDB backup via mongodump",- "databaseId", db.ID,- "storageId", storage.ID,- )+ logger := uc.logger.With("database_id", db.ID, "storage_id", storage.ID)++ logger.Info("creating mongodb backup via mongodump")++ tunneledDatabase, err := databases.OpenTunnel(ctx, databases.OpenTunnelSpec{+ Database: db,+ Logger: logger,+ Encryptor: uc.fieldEncryptor,+ })+ if err != nil {+ return nil, err+ }++ defer tunneledDatabase.Close()- mdb := db.Mongodb- if mdb == nil {+ mongodbDatabase := tunneledDatabase.GetDatabaseThroughTunnel().Mongodb+ if mongodbDatabase == nil {return nil, fmt.Errorf("mongodb database configuration is required")}- if mdb.Database == "" {+ if mongodbDatabase.Database == "" {return nil, fmt.Errorf("database name is required for mongodump backups")}- decryptedPassword, err := uc.fieldEncryptor.Decrypt(mdb.Password)+ decryptedPassword, err := uc.fieldEncryptor.Decrypt(mongodbDatabase.Password)if err != nil {return nil, fmt.Errorf("failed to decrypt database password: %w", err)}- rawSizeMB, err := mdb.GetRawDbSizeMb(ctx, uc.logger, uc.fieldEncryptor)+ rawSizeMB, err := mongodbDatabase.GetRawDbSizeMb(ctx, logger, uc.fieldEncryptor)if err != nil {- uc.logger.Warn("failed to fetch raw db size before backup",- "database_id", db.ID,- "error", err)+ logger.Warn("failed to fetch raw db size before backup", "error", err)} else {backup.BackupRawDbSizeMb = rawSizeMB}- args := uc.buildMongodumpArgs(mdb, decryptedPassword)+ args := uc.buildMongodumpArgs(mongodbDatabase, decryptedPassword)return uc.streamToStorage(ctx,diff --git a/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.goindex 14b26e1c..723fd7f0 100644--- a/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go@@ -72,47 +72,54 @@ func (uc *CreateMysqlBackupUsecase) Execute(storage *storages.Storage,backupProgressListener func(completedMBs float64),) (*backups_core_logical.BackupMetadata, error) {- uc.logger.Info(- "Creating MySQL backup via mysqldump",- "databaseId", db.ID,- "storageId", storage.ID,- )+ logger := uc.logger.With("database_id", db.ID, "storage_id", storage.ID)++ logger.Info("creating mysql backup via mysqldump")++ tunneledDatabase, err := databases.OpenTunnel(ctx, databases.OpenTunnelSpec{+ Database: db,+ Logger: logger,+ Encryptor: uc.fieldEncryptor,+ })+ if err != nil {+ return nil, err+ }++ defer tunneledDatabase.Close()- my := db.Mysql- if my == nil {+ mysqlDatabase := tunneledDatabase.GetDatabaseThroughTunnel().Mysql+ if mysqlDatabase == nil {return nil, fmt.Errorf("mysql database configuration is required")}- if my.Database == nil || *my.Database == "" {+ if mysqlDatabase.Database == nil || *mysqlDatabase.Database == "" {return nil, fmt.Errorf("database name is required for mysqldump backups")}- decryptedPassword, err := uc.fieldEncryptor.Decrypt(my.Password)+ decryptedPassword, err := uc.fieldEncryptor.Decrypt(mysqlDatabase.Password)if err != nil {return nil, fmt.Errorf("failed to decrypt database password: %w", err)}- rawSizeMB, err := my.GetRawDbSizeMb(ctx, uc.logger, uc.fieldEncryptor)+ rawSizeMB, err := mysqlDatabase.GetRawDbSizeMb(ctx, logger, uc.fieldEncryptor)if err != nil {- uc.logger.Warn("failed to fetch raw db size before backup",- "database_id", db.ID,- "error", err)+ logger.Warn("failed to fetch raw db size before backup", "error", err)} else {backup.BackupRawDbSizeMb = rawSizeMB}- args := uc.buildMysqldumpArgs(my)+ args := uc.buildMysqldumpArgs(mysqlDatabase)return uc.streamToStorage(ctx,backup,backupConfig,- tools.GetMysqlExecutable(my.Version, tools.MysqlExecutableMysqldump),+ tools.GetMysqlExecutable(mysqlDatabase.Version, tools.MysqlExecutableMysqldump),args,decryptedPassword,storage,backupProgressListener,- my,+ mysqlDatabase,)}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.goindex 95019077..e11b8db7 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@@ -68,20 +68,28 @@ func (uc *CreatePostgresqlBackupUsecase) Execute(completedMBs float64,),) (*backups_core_logical.BackupMetadata, error) {- uc.logger.Info(- "Creating PostgreSQL backup via pg_dump custom format",- "databaseId",- db.ID,- "storageId",- storage.ID,- )+ logger := uc.logger.With("database_id", db.ID, "storage_id", storage.ID, "backup_id", backup.ID)- pg := db.PostgresqlLogical+ logger.Info("creating postgresql backup via pg_dump custom format")- if pg == nil {+ if db.PostgresqlLogical == nil {return nil, fmt.Errorf("postgresql database configuration is required for pg_dump backups")}+ tunneledDatabase, err := databases.OpenTunnel(ctx, databases.OpenTunnelSpec{+ Database: db,+ Logger: logger,+ Encryptor: uc.fieldEncryptor,+ })+ if err != nil {+ return nil, err+ }++ defer tunneledDatabase.Close()++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()+ pg := databaseThroughTunnel.PostgresqlLogical+if pg.Database == nil || *pg.Database == "" {return nil, fmt.Errorf("database name is required for pg_dump backups")}@@ -93,20 +101,16 @@ func (uc *CreatePostgresqlBackupUsecase) Execute(return nil, fmt.Errorf("failed to decrypt database password: %w", err)}- rawSizeMB, err := pg.GetRawDbSizeMb(ctx, uc.logger, uc.fieldEncryptor)+ rawSizeMB, err := pg.GetRawDbSizeMb(ctx, logger, uc.fieldEncryptor)if err != nil {- uc.logger.Warn("failed to fetch raw db size before backup",- "database_id", db.ID,- "error", err)+ logger.Warn("failed to fetch raw db size before backup", "error", err)} else {backup.BackupRawDbSizeMb = rawSizeMB}timescaledbVersion, err := pg.GetTimescaleDBVersion(ctx, uc.fieldEncryptor)if err != nil {- uc.logger.Warn("failed to detect timescaledb extension before backup",- "database_id", db.ID,- "error", err)+ logger.Warn("failed to detect timescaledb extension before backup", "error", err)} else {backup.TimescaledbVersion = timescaledbVersion}@@ -119,7 +123,7 @@ func (uc *CreatePostgresqlBackupUsecase) Execute(args,decryptedPassword,storage,- db,+ databaseThroughTunnel,backupProgressListener,)}@@ -154,7 +158,7 @@ func (uc *CreatePostgresqlBackupUsecase) streamToStorage(if err := uc.setupPgEnvironment(cmd,credentials,- db.PostgresqlLogical.SslMode,+ db.PostgresqlLogical.CredentialSpec(),password,db.PostgresqlLogical.CpuCount,pgBin,@@ -435,13 +439,14 @@ func (uc *CreatePostgresqlBackupUsecase) createBackupContext(func (uc *CreatePostgresqlBackupUsecase) setupPgEnvironment(cmd *exec.Cmd,credentials *postgresql_shared.CredentialTempFiles,- sslMode postgresql_shared.PostgresSslMode,+ credentialSpec postgresql_shared.CredentialSpec,password string,cpuCount int,pgBin string,) error {cmd.Env = os.Environ()cmd.Env = append(cmd.Env, "PGPASSFILE="+credentials.PgpassPath)+ cmd.Env = append(cmd.Env, postgresql_shared.GetPgHostAddrEnv(credentialSpec)...)uc.logger.Info("Setting up PostgreSQL environment","passwordLength", len(password),@@ -457,7 +462,7 @@ func (uc *CreatePostgresqlBackupUsecase) setupPgEnvironment("LANG=C.UTF-8",)- resolvedSslMode := sslMode+ resolvedSslMode := credentialSpec.SslModeif resolvedSslMode == "" {resolvedSslMode = postgresql_shared.PostgresSslModeDisable}diff --git a/backend/internal/features/databases/controller_test.go b/backend/internal/features/databases/controller_test.goindex 7c04f609..e4e167a3 100644--- a/backend/internal/features/databases/controller_test.go+++ b/backend/internal/features/databases/controller_test.go@@ -3,7 +3,10 @@ package databasesimport ("encoding/json""fmt"+ "net""net/http"+ "os"+ "path/filepath""strconv""strings""testing"@@ -19,10 +22,12 @@ import (physical_testing "databasus-backend/internal/features/backups/backups/core/physical/testing""databasus-backend/internal/features/databases/databases/mariadb""databasus-backend/internal/features/databases/databases/mongodb"+ "databasus-backend/internal/features/databases/databases/mysql"postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared""databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/features/storages"users_enums "databasus-backend/internal/features/users/enums"users_middleware "databasus-backend/internal/features/users/middleware"@@ -880,6 +885,66 @@ func Test_CreateDatabase_PasswordIsEncryptedInDB(t *testing.T) {workspaces_testing.RemoveTestWorkspace(workspace, router)}+const updatedSshTunnelHost = "moved-bastion.example.com"++// Populated but disabled: Validate skips a disabled tunnel and no code path dials it, while+// HideSensitiveData, Update and EncryptSensitiveFields all run regardless. That is what lets the+// secret lifecycle be asserted over HTTP against a database with no bastion in front of it.+func storedSshTunnelConfig() sshtunnel.Config {+ return sshtunnel.Config{+ IsEnabled: false,+ Host: "bastion.example.com",+ Port: 2222,+ Username: "tunneluser",+ Password: "tunnelpassword",+ PrivateKey: "tunnelprivatekey",+ PrivateKeyPassphrase: "tunnelpassphrase",+ }+}++// The host moves as well, so an engine that stopped delegating to sshtunnel.Config.Update would+// keep the stored secrets by doing nothing at all and still look correct.+func submittedSshTunnelConfigWithoutSecrets() sshtunnel.Config {+ sshTunnel := storedSshTunnelConfig()+ sshTunnel.Host = updatedSshTunnelHost+ sshTunnel.Password = ""+ sshTunnel.PrivateKey = ""+ sshTunnel.PrivateKeyPassphrase = ""++ return sshTunnel+}++func assertSshTunnelUpdateMovedTheHostAndKeptTheSecrets(t *testing.T, sshTunnel sshtunnel.Config) {+ t.Helper()++ assert.Equal(t, updatedSshTunnelHost, sshTunnel.Host,+ "the address is always submitted, so the update must land")++ encryptor := encryption.GetFieldEncryptor()++ for submittedSecret, storedSecret := range map[string]string{+ "tunnelpassword": sshTunnel.Password,+ "tunnelprivatekey": sshTunnel.PrivateKey,+ "tunnelpassphrase": sshTunnel.PrivateKeyPassphrase,+ } {+ assert.True(t, strings.HasPrefix(storedSecret, "enc:"),+ "SSH tunnel secret should be encrypted in database")++ decrypted, err := encryptor.Decrypt(storedSecret)+ assert.NoError(t, err)+ assert.Equal(t, submittedSecret, decrypted)+ }+}++func assertSshTunnelSecretsAreHidden(t *testing.T, sshTunnel sshtunnel.Config) {+ t.Helper()++ assert.Empty(t, sshTunnel.Password)+ assert.Empty(t, sshTunnel.PrivateKey)+ assert.Empty(t, sshTunnel.PrivateKeyPassphrase)+ assert.Equal(t, "tunneluser", sshTunnel.Username, "the address stays readable in the UI")+}+func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {testCases := []struct {name string@@ -894,6 +959,7 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {databaseType: DatabaseTypePostgresLogical,createDatabase: func(_ *testing.T, workspaceID uuid.UUID) *Database {pgConfig := getTestPostgresConfig()+ pgConfig.SshTunnel = storedSshTunnelConfig()return &Database{WorkspaceID: &workspaceID,Name: "Test PostgreSQL Database",@@ -904,6 +970,7 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {updateDatabase: func(_ *testing.T, workspaceID, databaseID uuid.UUID) *Database {pgConfig := getTestPostgresConfig()pgConfig.Password = ""+ pgConfig.SshTunnel = submittedSshTunnelConfigWithoutSecrets()return &Database{ID: databaseID,WorkspaceID: &workspaceID,@@ -920,9 +987,11 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {decrypted, err := encryptor.Decrypt(database.PostgresqlLogical.Password)assert.NoError(t, err)assert.Equal(t, "testpassword", decrypted)+ assertSshTunnelUpdateMovedTheHostAndKeptTheSecrets(t, database.PostgresqlLogical.SshTunnel)},verifyHiddenData: func(t *testing.T, database *Database) {assert.Equal(t, "", database.PostgresqlLogical.Password)+ assertSshTunnelSecretsAreHidden(t, database.PostgresqlLogical.SshTunnel)},},{@@ -930,6 +999,7 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {databaseType: DatabaseTypeMariadb,createDatabase: func(t *testing.T, workspaceID uuid.UUID) *Database {mariaConfig := getTestMariadbConfig(t)+ mariaConfig.SshTunnel = storedSshTunnelConfig()return &Database{WorkspaceID: &workspaceID,Name: "Test MariaDB Database",@@ -940,6 +1010,7 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {updateDatabase: func(t *testing.T, workspaceID, databaseID uuid.UUID) *Database {mariaConfig := getTestMariadbConfig(t)mariaConfig.Password = ""+ mariaConfig.SshTunnel = submittedSshTunnelConfigWithoutSecrets()return &Database{ID: databaseID,WorkspaceID: &workspaceID,@@ -956,9 +1027,51 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {decrypted, err := encryptor.Decrypt(database.Mariadb.Password)assert.NoError(t, err)assert.Equal(t, "testpassword", decrypted)+ assertSshTunnelUpdateMovedTheHostAndKeptTheSecrets(t, database.Mariadb.SshTunnel)},verifyHiddenData: func(t *testing.T, database *Database) {assert.Equal(t, "", database.Mariadb.Password)+ assertSshTunnelSecretsAreHidden(t, database.Mariadb.SshTunnel)+ },+ },+ {+ name: "MySQL Database",+ databaseType: DatabaseTypeMysql,+ createDatabase: func(t *testing.T, workspaceID uuid.UUID) *Database {+ mysqlConfig := getTestMysqlConfig(t)+ mysqlConfig.SshTunnel = storedSshTunnelConfig()+ return &Database{+ WorkspaceID: &workspaceID,+ Name: "Test MySQL Database",+ Type: DatabaseTypeMysql,+ Mysql: mysqlConfig,+ }+ },+ updateDatabase: func(t *testing.T, workspaceID, databaseID uuid.UUID) *Database {+ mysqlConfig := getTestMysqlConfig(t)+ mysqlConfig.Password = ""+ mysqlConfig.SshTunnel = submittedSshTunnelConfigWithoutSecrets()+ return &Database{+ ID: databaseID,+ WorkspaceID: &workspaceID,+ Name: "Updated MySQL Database",+ Type: DatabaseTypeMysql,+ Mysql: mysqlConfig,+ }+ },+ verifySensitiveData: func(t *testing.T, database *Database) {+ assert.True(t, strings.HasPrefix(database.Mysql.Password, "enc:"),+ "Password should be encrypted in database")++ encryptor := encryption.GetFieldEncryptor()+ decrypted, err := encryptor.Decrypt(database.Mysql.Password)+ assert.NoError(t, err)+ assert.Equal(t, "testpassword", decrypted)+ assertSshTunnelUpdateMovedTheHostAndKeptTheSecrets(t, database.Mysql.SshTunnel)+ },+ verifyHiddenData: func(t *testing.T, database *Database) {+ assert.Equal(t, "", database.Mysql.Password)+ assertSshTunnelSecretsAreHidden(t, database.Mysql.SshTunnel)},},{@@ -966,6 +1079,7 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {databaseType: DatabaseTypeMongodb,createDatabase: func(t *testing.T, workspaceID uuid.UUID) *Database {mongoConfig := getTestMongodbConfig(t)+ mongoConfig.SshTunnel = storedSshTunnelConfig()return &Database{WorkspaceID: &workspaceID,Name: "Test MongoDB Database",@@ -976,6 +1090,7 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {updateDatabase: func(t *testing.T, workspaceID, databaseID uuid.UUID) *Database {mongoConfig := getTestMongodbConfig(t)mongoConfig.Password = ""+ mongoConfig.SshTunnel = submittedSshTunnelConfigWithoutSecrets()return &Database{ID: databaseID,WorkspaceID: &workspaceID,@@ -992,9 +1107,11 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {decrypted, err := encryptor.Decrypt(database.Mongodb.Password)assert.NoError(t, err)assert.Equal(t, "rootpassword", decrypted)+ assertSshTunnelUpdateMovedTheHostAndKeptTheSecrets(t, database.Mongodb.SshTunnel)},verifyHiddenData: func(t *testing.T, database *Database) {assert.Equal(t, "", database.Mongodb.Password)+ assertSshTunnelSecretsAreHidden(t, database.Mongodb.SshTunnel)},},}@@ -1349,6 +1466,12 @@ func getTestMariadbConfig(t *testing.T) *mariadb.MariadbDatabase {return GetTestMariadbConfig(endpoint.Host, endpoint.Port)}+func getTestMysqlConfig(t *testing.T) *mysql.MysqlDatabase {+ endpoint := containers.StartMysql(t, "mysql:8.0")++ return GetTestMysqlConfig(endpoint.Host, endpoint.Port)+}+func getTestMongodbConfig(t *testing.T) *mongodb.MongodbDatabase {endpoint := containers.StartMongodb(t, "mongo:7.0")@@ -1466,3 +1589,218 @@ func Test_UpdateDatabase_FailsForSwitchToPhysicalIncrementalWhenSummarizeWalOff(})}}++func bastionedPostgresConfig(+ topology containers.BastionedDatabase,+) *postgresql_logical.PostgresqlLogicalDatabase {+ databaseName := containers.PostgresDatabase++ return &postgresql_logical.PostgresqlLogicalDatabase{+ Host: topology.Database.Host,+ Port: topology.Database.Port,+ Username: containers.PostgresUsername,+ Password: containers.PostgresPassword,+ Database: &databaseName,+ CpuCount: 1,+ SshTunnel: sshtunnel.Config{+ IsEnabled: true,+ Host: topology.Bastion.Host,+ Port: topology.Bastion.Port,+ Username: containers.SshBastionUsername,+ Password: containers.SshBastionPassword,+ },+ }+}++// Without this the tunnel tests would stay green if the tunnel silently stopped being used, because+// every other assertion only proves that some route to the database exists.+func Test_BastionedPostgres_WithoutTheTunnel_IsUnreachableFromTheHost(t *testing.T) {+ topology := containers.StartPostgresBehindSshBastion(t, "postgres:16")++ address := net.JoinHostPort(topology.Database.Host, strconv.Itoa(topology.Database.Port))++ conn, err := net.DialTimeout("tcp", address, 5*time.Second)+ if err == nil {+ _ = conn.Close()+ t.Fatalf("the bastioned database answered on %s without a tunnel", address)+ }+}++func Test_CreateDatabase_OverSshTunnel_DetectsVersionAndHidesTunnelSecrets(t *testing.T) {+ topology := containers.StartPostgresBehindSshBastion(t, "postgres:16")++ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("SSH Tunnel", owner, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ var createdDatabase Database+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/databases/create", "Bearer "+owner.Token,+ Database{+ Name: "Bastioned PG",+ WorkspaceID: &workspace.ID,+ Type: DatabaseTypePostgresLogical,+ PostgresqlLogical: bastionedPostgresConfig(topology),+ },+ http.StatusCreated, &createdDatabase,+ )+ t.Cleanup(func() { RemoveTestDatabase(&createdDatabase) })++ require.NotNil(t, createdDatabase.PostgresqlLogical)+ assert.Equal(t, "16", string(createdDatabase.PostgresqlLogical.Version))++ // The stored config must still address the database as the bastion sees it, not as the+ // forwarder rewrote it for the duration of the connection test.+ assert.Equal(t, topology.Database.Host, createdDatabase.PostgresqlLogical.Host)+ assert.Equal(t, topology.Database.Port, createdDatabase.PostgresqlLogical.Port)+ assert.True(t, createdDatabase.PostgresqlLogical.SshTunnel.IsEnabled)++ var fetchedDatabase Database+ test_utils.MakeGetRequestAndUnmarshal(+ t, router, "/api/v1/databases/"+createdDatabase.ID.String(),+ "Bearer "+owner.Token, http.StatusOK, &fetchedDatabase,+ )++ require.NotNil(t, fetchedDatabase.PostgresqlLogical)+ assert.Empty(t, fetchedDatabase.PostgresqlLogical.SshTunnel.Password)+ assert.Empty(t, fetchedDatabase.PostgresqlLogical.SshTunnel.PrivateKey)+ assert.Empty(t, fetchedDatabase.PostgresqlLogical.SshTunnel.PrivateKeyPassphrase)+ assert.Equal(t, containers.SshBastionUsername, fetchedDatabase.PostgresqlLogical.SshTunnel.Username)++ testConnectionResponse := workspaces_testing.MakeAPIRequest(+ router, "POST", "/api/v1/databases/"+createdDatabase.ID.String()+"/test-connection",+ "Bearer "+owner.Token, nil,+ )+ assert.Equal(t, http.StatusOK, testConnectionResponse.Code, "body: %s", testConnectionResponse.Body.String())+}++func Test_CreateDatabase_OverSshTunnelWithAPrivateKey_DatabaseCreated(t *testing.T) {+ topology := containers.StartPostgresBehindSshBastion(t, "postgres:16")++ privateKey, err := os.ReadFile(filepath.Join(containers.GetSshBastionTestdataDir(t), "test_key"))+ require.NoError(t, err)++ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("SSH Tunnel Key", owner, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ postgresConfig := bastionedPostgresConfig(topology)+ postgresConfig.SshTunnel.Password = ""+ postgresConfig.SshTunnel.PrivateKey = string(privateKey)++ var createdDatabase Database+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/databases/create", "Bearer "+owner.Token,+ Database{+ Name: "Bastioned PG by key",+ WorkspaceID: &workspace.ID,+ Type: DatabaseTypePostgresLogical,+ PostgresqlLogical: postgresConfig,+ },+ http.StatusCreated, &createdDatabase,+ )+ t.Cleanup(func() { RemoveTestDatabase(&createdDatabase) })++ require.NotNil(t, createdDatabase.PostgresqlLogical)+ assert.Equal(t, "16", string(createdDatabase.PostgresqlLogical.Version))+}++func Test_CreateDatabase_WhenSshTunnelIsEnabledWithoutAHost_ReturnsBadRequest(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("SSH Tunnel Invalid", owner, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ postgresConfig := getTestPostgresConfig()+ postgresConfig.SshTunnel = sshtunnel.Config{+ IsEnabled: true,+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ }++ response := workspaces_testing.MakeAPIRequest(+ router, "POST", "/api/v1/databases/create", "Bearer "+owner.Token,+ Database{+ Name: "Tunnel without a host",+ WorkspaceID: &workspace.ID,+ Type: DatabaseTypePostgresLogical,+ PostgresqlLogical: postgresConfig,+ },+ )++ assert.Equal(t, http.StatusBadRequest, response.Code)+ assert.Contains(t, response.Body.String(), "SSH tunnel host is required")+}++func Test_CopyDatabase_WhenTheSourceIsBehindABastion_KeepsTheTunnelConfig(t *testing.T) {+ topology := containers.StartPostgresBehindSshBastion(t, "postgres:16")++ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("SSH Tunnel Copy", owner, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ var createdDatabase Database+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/databases/create", "Bearer "+owner.Token,+ Database{+ Name: "Bastioned PG to copy",+ WorkspaceID: &workspace.ID,+ Type: DatabaseTypePostgresLogical,+ PostgresqlLogical: bastionedPostgresConfig(topology),+ },+ http.StatusCreated, &createdDatabase,+ )+ t.Cleanup(func() { RemoveTestDatabase(&createdDatabase) })++ var copiedDatabase Database+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/databases/"+createdDatabase.ID.String()+"/copy",+ "Bearer "+owner.Token, nil, http.StatusCreated, &copiedDatabase,+ )+ t.Cleanup(func() { RemoveTestDatabase(&copiedDatabase) })++ require.NotNil(t, copiedDatabase.PostgresqlLogical)+ assert.True(t, copiedDatabase.PostgresqlLogical.SshTunnel.IsEnabled)+ assert.Equal(t, topology.Bastion.Host, copiedDatabase.PostgresqlLogical.SshTunnel.Host)+ assert.Equal(t, topology.Bastion.Port, copiedDatabase.PostgresqlLogical.SshTunnel.Port)+ assert.Equal(t, containers.SshBastionUsername, copiedDatabase.PostgresqlLogical.SshTunnel.Username)+}++func Test_CreateMongodbDatabase_WhenSrvAndSshTunnelAreEnabled_ReturnsBadRequest(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Mongo SRV Tunnel", owner, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ response := workspaces_testing.MakeAPIRequest(+ router, "POST", "/api/v1/databases/create", "Bearer "+owner.Token,+ Database{+ Name: "SRV behind a bastion",+ WorkspaceID: &workspace.ID,+ Type: DatabaseTypeMongodb,+ Mongodb: &mongodb.MongodbDatabase{+ Host: "cluster0.example.mongodb.net",+ Username: "testuser",+ Password: "testpassword",+ Database: "testdb",+ AuthDatabase: "admin",+ CpuCount: 1,+ IsSrv: true,+ SshTunnel: sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: containers.SshBastionUsername,+ Password: containers.SshBastionPassword,+ },+ },+ },+ )++ assert.Equal(t, http.StatusBadRequest, response.Code)+ assert.Contains(t, response.Body.String(), "SRV")+}diff --git a/backend/internal/features/databases/databases/mariadb/model.go b/backend/internal/features/databases/databases/mariadb/model.goindex 129612d9..1c6b33b3 100644--- a/backend/internal/features/databases/databases/mariadb/model.go+++ b/backend/internal/features/databases/databases/mariadb/model.go@@ -8,6 +8,7 @@ import ("fmt""log/slog""regexp"+ "slices""sort""strings""time"@@ -16,6 +17,7 @@ import ("github.com/google/uuid""gorm.io/gorm"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/encryption""databasus-backend/internal/util/namelist""databasus-backend/internal/util/tools"@@ -27,17 +29,21 @@ type MariadbDatabase struct {Version tools.MariadbVersion `json:"version" gorm:"type:text;not null"`- Host string `json:"host" gorm:"type:text;not null"`- Port int `json:"port" gorm:"type:int;not null"`- Username string `json:"username" gorm:"type:text;not null"`- Password string `json:"password" gorm:"type:text;not null"`- Database *string `json:"database" gorm:"type:text"`- IsHttps bool `json:"isHttps" gorm:"type:boolean;default:false"`- IsExcludeEvents bool `json:"isExcludeEvents" gorm:"type:boolean;default:false"`- IsSkipGaleraDisable bool `json:"isSkipGaleraDisable" gorm:"column:is_skip_galera_disable;type:boolean;not null;default:false"`- ExcludeTables []string `json:"excludeTables" gorm:"-"`- ExcludeTablesString string `json:"-" gorm:"column:exclude_tables;type:text;not null;default:''"`- Privileges string `json:"privileges" gorm:"column:privileges;type:text;not null;default:''"`+ Host string `json:"host" gorm:"type:text;not null"`+ Port int `json:"port" gorm:"type:int;not null"`+ Username string `json:"username" gorm:"type:text;not null"`+ Password string `json:"password" gorm:"type:text;not null"`+ Database *string `json:"database" gorm:"type:text"`+ IsHttps bool `json:"isHttps" gorm:"type:boolean;default:false"`+ IsExcludeEvents bool `json:"isExcludeEvents" gorm:"type:boolean;default:false"`+ IsSkipGaleraDisable bool `json:"isSkipGaleraDisable" gorm:"column:is_skip_galera_disable;type:boolean;not null;default:false"`++ // When the tunnel is enabled, Host and Port above address the database as the bastion sees it.+ SshTunnel sshtunnel.Config `json:"sshTunnel" gorm:"embedded;embeddedPrefix:ssh_"`++ ExcludeTables []string `json:"excludeTables" gorm:"-"`+ ExcludeTablesString string `json:"-" gorm:"column:exclude_tables;type:text;not null;default:''"`+ Privileges string `json:"privileges" gorm:"column:privileges;type:text;not null;default:''"`}func (m *MariadbDatabase) TableName() string {@@ -69,7 +75,8 @@ func (m *MariadbDatabase) Validate() error {if m.Password == "" {return errors.New("password is required")}- return nil++ return m.SshTunnel.Validate()}func (m *MariadbDatabase) TestConnection(@@ -176,6 +183,7 @@ func (m *MariadbDatabase) HideSensitiveData() {return}m.Password = ""+ m.SshTunnel.HideSensitiveData()}func (m *MariadbDatabase) Update(incoming *MariadbDatabase) {@@ -189,12 +197,30 @@ func (m *MariadbDatabase) Update(incoming *MariadbDatabase) {m.IsSkipGaleraDisable = incoming.IsSkipGaleraDisablem.ExcludeTables = incoming.ExcludeTablesm.Privileges = incoming.Privileges+ m.SshTunnel.Update(&incoming.SshTunnel)if incoming.Password != "" {m.Password = incoming.Password}}+func (m *MariadbDatabase) CopyForNewDatabase() *MariadbDatabase {+ if m == nil {+ return nil+ }++ copiedDatabase := *m+ copiedDatabase.ID = uuid.Nil+ copiedDatabase.DatabaseID = nil+ copiedDatabase.ExcludeTables = slices.Clone(m.ExcludeTables)++ if m.Database != nil {+ copiedDatabase.Database = new(*m.Database)+ }++ return &copiedDatabase+}+func (m *MariadbDatabase) EncryptSensitiveFields(encryptor encryption.FieldEncryptor,) error {@@ -205,7 +231,8 @@ func (m *MariadbDatabase) EncryptSensitiveFields(}m.Password = encrypted}- return nil++ return m.SshTunnel.EncryptSensitiveFields(encryptor)}func (m *MariadbDatabase) PopulateDbData(diff --git a/backend/internal/features/databases/databases/mariadb/tunnel.go b/backend/internal/features/databases/databases/mariadb/tunnel.gonew file mode 100644index 00000000..ce8c173a--- /dev/null+++ b/backend/internal/features/databases/databases/mariadb/tunnel.go@@ -0,0 +1,83 @@+package mariadb++import (+ "context"+ "log/slog"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/encryption"+)++type OpenTunnelSpec struct {+ Database *MariadbDatabase+ Logger *slog.Logger+ Encryptor encryption.FieldEncryptor+}++// The tunnel belongs to the operation, not to the model: buildDSN is called separately by every+// method that reaches the server, so no method down there could own a Close.+type TunneledDatabase struct {+ original *MariadbDatabase+ databaseThroughTunnel *MariadbDatabase+ forwarder *sshtunnel.Forwarder+}++// 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 || !spec.Database.SshTunnel.IsEnabled {+ return &TunneledDatabase{original: spec.Database, databaseThroughTunnel: spec.Database}, nil+ }++ forwarder, err := sshtunnel.Open(ctx, sshtunnel.OpenSpec{+ Config: spec.Database.SshTunnel,+ Target: sshtunnel.Endpoint{Host: spec.Database.Host, Port: spec.Database.Port},+ Encryptor: spec.Encryptor,+ Logger: spec.Logger,+ })+ if err != nil {+ return nil, err+ }++ localEndpoint := forwarder.GetLocalEndpoint()++ databaseThroughTunnel := *spec.Database+ databaseThroughTunnel.Host = localEndpoint.Host+ databaseThroughTunnel.Port = localEndpoint.Port+ // The copy describes an already forwarded connection; leaving this on would make anything that+ // re-reads it open a second tunnel pointed at the first one's local port.+ databaseThroughTunnel.SshTunnel.IsEnabled = false++ return &TunneledDatabase{+ original: spec.Database,+ databaseThroughTunnel: &databaseThroughTunnel,+ forwarder: forwarder,+ }, nil+}++func (t *TunneledDatabase) GetDatabaseThroughTunnel() *MariadbDatabase {+ if t == nil {+ return nil+ }++ return t.databaseThroughTunnel+}++// TestConnection and PopulateDbData write what they detect into the model they were handed, which+// is the copy. Callers that persist the result need it carried back.+func (t *TunneledDatabase) CopyDiscoveredMetadataToOriginal() {+ if t == nil || t.original == nil || t.databaseThroughTunnel == nil {+ return+ }++ t.original.Version = t.databaseThroughTunnel.Version+ t.original.Privileges = t.databaseThroughTunnel.Privileges+}++func (t *TunneledDatabase) Close() {+ if t == nil || t.forwarder == nil {+ return+ }++ t.forwarder.Close()+}diff --git a/backend/internal/features/databases/databases/mariadb/tunnel_test.go b/backend/internal/features/databases/databases/mariadb/tunnel_test.gonew file mode 100644index 00000000..d4a1b3c3--- /dev/null+++ b/backend/internal/features/databases/databases/mariadb/tunnel_test.go@@ -0,0 +1,116 @@+package mariadb++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/testing/containers"+ "databasus-backend/internal/util/tools"+)++const discoveredVersion = tools.MariadbVersion114++const unreachableBastionTimeout = 2 * time.Second++func enabledTunnelDatabase() *MariadbDatabase {+ databaseName := "testdb"++ return &MariadbDatabase{+ Host: "db.internal",+ Port: 3306,+ Username: "testuser",+ Password: "testpassword",+ Database: &databaseName,+ SshTunnel: sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ },+ }+}++func bastionedTunnelDatabase(t *testing.T) *MariadbDatabase {+ t.Helper()++ bastion := containers.StartSshBastion(t)++ database := enabledTunnelDatabase()+ database.SshTunnel.Host = bastion.Host+ database.SshTunnel.Port = bastion.Port+ database.SshTunnel.Username = containers.SshBastionUsername+ database.SshTunnel.Password = containers.SshBastionPassword++ return database+}++func Test_OpenTunnel_WhenTheTunnelIsDisabled_HandsBackTheSameDatabase(t *testing.T) {+ database := enabledTunnelDatabase()+ database.SshTunnel.IsEnabled = false++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ assert.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.Same(t, database, tunneledDatabase.GetDatabaseThroughTunnel())+}++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.+ database.SshTunnel.Host = "192.0.2.1"++ // A blackholing network would otherwise burn the forwarder's full 30s dial timeout here.+ ctx, cancel := context.WithTimeout(t.Context(), unreachableBastionTimeout)+ defer cancel()++ _, err := OpenTunnel(ctx, OpenTunnelSpec{Database: database})++ assert.Error(t, err)+}++func Test_OpenTunnel_WhenTunneled_DisablesTheTunnelFlagOnTheCopy(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()++ assert.False(t, databaseThroughTunnel.SshTunnel.IsEnabled,+ "a re-read of the copy would otherwise open a second tunnel into the first one")+ assert.True(t, database.SshTunnel.IsEnabled, "the original must keep the stored configuration")+ assert.Equal(t, "db.internal", database.Host, "the original address must not be rewritten")+ assert.Equal(t, 3306, database.Port)+ assert.Equal(t, "127.0.0.1", databaseThroughTunnel.Host)+ assert.NotEqual(t, database.Port, databaseThroughTunnel.Port)+}++// Discovery runs against the copy, so anything it writes there is lost unless it is carried back:+// a bastioned database would otherwise be saved with the privileges of a connection never made.+func Test_CopyDiscoveredMetadataToOriginal_CarriesTheVersionAndPrivileges(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()+ databaseThroughTunnel.Version = discoveredVersion+ databaseThroughTunnel.Privileges = "SELECT,LOCK TABLES"++ tunneledDatabase.CopyDiscoveredMetadataToOriginal()++ assert.Equal(t, discoveredVersion, database.Version)+ assert.Equal(t, "SELECT,LOCK TABLES", database.Privileges)+}diff --git a/backend/internal/features/databases/databases/mongodb/model.go b/backend/internal/features/databases/databases/mongodb/model.goindex 7cd65640..895d6a23 100644--- a/backend/internal/features/databases/databases/mongodb/model.go+++ b/backend/internal/features/databases/databases/mongodb/model.go@@ -7,6 +7,7 @@ import ("log/slog""net/url""regexp"+ "slices""strings""time"@@ -16,6 +17,7 @@ import ("go.mongodb.org/mongo-driver/mongo/options""gorm.io/gorm"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/encryption""databasus-backend/internal/util/namelist""databasus-backend/internal/util/tools"@@ -27,16 +29,20 @@ type MongodbDatabase struct {Version tools.MongodbVersion `json:"version" gorm:"type:text;not null"`- Host string `json:"host" gorm:"type:text;not null"`- Port *int `json:"port" gorm:"type:int"`- Username string `json:"username" gorm:"type:text;not null"`- Password string `json:"password" gorm:"type:text;not null"`- Database string `json:"database" gorm:"type:text;not null"`- AuthDatabase string `json:"authDatabase" gorm:"type:text;not null;default:'admin'"`- IsHttps bool `json:"isHttps" gorm:"type:boolean;default:false"`- IsSrv bool `json:"isSrv" gorm:"column:is_srv;type:boolean;not null;default:false"`- IsDirectConnection bool `json:"isDirectConnection" gorm:"column:is_direct_connection;type:boolean;not null;default:false"`- CpuCount int `json:"cpuCount" gorm:"column:cpu_count;type:int;not null;default:1"`+ Host string `json:"host" gorm:"type:text;not null"`+ Port *int `json:"port" gorm:"type:int"`+ Username string `json:"username" gorm:"type:text;not null"`+ Password string `json:"password" gorm:"type:text;not null"`+ Database string `json:"database" gorm:"type:text;not null"`+ AuthDatabase string `json:"authDatabase" gorm:"type:text;not null;default:'admin'"`+ IsHttps bool `json:"isHttps" gorm:"type:boolean;default:false"`+ IsSrv bool `json:"isSrv" gorm:"column:is_srv;type:boolean;not null;default:false"`+ IsDirectConnection bool `json:"isDirectConnection" gorm:"column:is_direct_connection;type:boolean;not null;default:false"`+ CpuCount int `json:"cpuCount" gorm:"column:cpu_count;type:int;not null;default:1"`++ // When the tunnel is enabled, Host and Port above address the database as the bastion sees it.+ SshTunnel sshtunnel.Config `json:"sshTunnel" gorm:"embedded;embeddedPrefix:ssh_"`+ExcludeCollections []string `json:"excludeCollections" gorm:"-"`ExcludeCollectionsString string `json:"-" gorm:"column:exclude_collections;type:text;not null;default:''"`}@@ -81,7 +87,16 @@ func (m *MongodbDatabase) Validate() error {return errors.New("cpu count must be greater than 0")}- return nil+ // SRV resolves its own host list from DNS and never carries a port, so there is nothing for a+ // local forward to stand in front of.+ if m.SshTunnel.IsEnabled && m.IsSrv {+ return errors.New(+ "SSH tunnel cannot be used with an SRV connection: " ++ "SRV resolves its own host list and bypasses the forwarded port",+ )+ }++ return m.SshTunnel.Validate()}func (m *MongodbDatabase) TestConnection(@@ -179,6 +194,7 @@ func (m *MongodbDatabase) HideSensitiveData() {return}m.Password = ""+ m.SshTunnel.HideSensitiveData()}func (m *MongodbDatabase) Update(incoming *MongodbDatabase) {@@ -193,12 +209,30 @@ func (m *MongodbDatabase) Update(incoming *MongodbDatabase) {m.IsDirectConnection = incoming.IsDirectConnectionm.CpuCount = incoming.CpuCountm.ExcludeCollections = incoming.ExcludeCollections+ m.SshTunnel.Update(&incoming.SshTunnel)if incoming.Password != "" {m.Password = incoming.Password}}+func (m *MongodbDatabase) CopyForNewDatabase() *MongodbDatabase {+ if m == nil {+ return nil+ }++ copiedDatabase := *m+ copiedDatabase.ID = uuid.Nil+ copiedDatabase.DatabaseID = nil+ copiedDatabase.ExcludeCollections = slices.Clone(m.ExcludeCollections)++ if m.Port != nil {+ copiedDatabase.Port = new(*m.Port)+ }++ return &copiedDatabase+}+func (m *MongodbDatabase) EncryptSensitiveFields(encryptor encryption.FieldEncryptor,) error {@@ -209,7 +243,8 @@ func (m *MongodbDatabase) EncryptSensitiveFields(}m.Password = encrypted}- return nil++ return m.SshTunnel.EncryptSensitiveFields(encryptor)}func (m *MongodbDatabase) PopulateDbData(diff --git a/backend/internal/features/databases/databases/mongodb/model_test.go b/backend/internal/features/databases/databases/mongodb/model_test.goindex c866f3c2..e61c553a 100644--- a/backend/internal/features/databases/databases/mongodb/model_test.go+++ b/backend/internal/features/databases/databases/mongodb/model_test.go@@ -16,6 +16,7 @@ import ("go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/testing/containers""databasus-backend/internal/util/tools")@@ -837,3 +838,35 @@ func Test_MapMongodbVersion_VersionMatrix_ReturnsExpected(t *testing.T) {})}}++func srvDatabase() *MongodbDatabase {+ return &MongodbDatabase{+ Host: "cluster0.example.mongodb.net",+ Port: nil,+ Username: "testuser",+ Password: "testpass123",+ Database: "mydb",+ AuthDatabase: "admin",+ CpuCount: 1,+ IsSrv: true,+ }+}++func Test_Validate_WhenSrvIsEnabledBehindAnSshTunnel_IsRejected(t *testing.T) {+ model := srvDatabase()+ model.SshTunnel = sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ }++ err := model.Validate()++ assert.ErrorContains(t, err, "SRV")+}++func Test_Validate_WhenSrvIsEnabledWithoutAnSshTunnel_IsAccepted(t *testing.T) {+ assert.NoError(t, srvDatabase().Validate())+}diff --git a/backend/internal/features/databases/databases/mongodb/tunnel.go b/backend/internal/features/databases/databases/mongodb/tunnel.gonew file mode 100644index 00000000..37fa13e4--- /dev/null+++ b/backend/internal/features/databases/databases/mongodb/tunnel.go@@ -0,0 +1,95 @@+package mongodb++import (+ "context"+ "errors"+ "log/slog"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/encryption"+)++type OpenTunnelSpec struct {+ Database *MongodbDatabase+ Logger *slog.Logger+ Encryptor encryption.FieldEncryptor+}++// The tunnel belongs to the operation, not to the model: buildURI is called separately by every+// method that reaches the server, so no method down there could own a Close.+type TunneledDatabase struct {+ original *MongodbDatabase+ databaseThroughTunnel *MongodbDatabase+ forwarder *sshtunnel.Forwarder+}++// 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 || !spec.Database.SshTunnel.IsEnabled {+ return &TunneledDatabase{original: spec.Database, databaseThroughTunnel: spec.Database}, nil+ }++ // Restore targets arrive as bare models straight from the request DTO, so Validate has not+ // necessarily run and the port may still be unset.+ if spec.Database.Port == nil {+ return nil, errors.New("SSH tunnel requires an explicit MongoDB port")+ }++ forwarder, err := sshtunnel.Open(ctx, sshtunnel.OpenSpec{+ Config: spec.Database.SshTunnel,+ Target: sshtunnel.Endpoint{Host: spec.Database.Host, Port: *spec.Database.Port},+ Encryptor: spec.Encryptor,+ Logger: spec.Logger,+ })+ if err != nil {+ return nil, err+ }++ localEndpoint := forwarder.GetLocalEndpoint()++ databaseThroughTunnel := *spec.Database+ databaseThroughTunnel.Host = localEndpoint.Host+ // A fresh pointer, because the shallow copy shares the original's and the original is what gets+ // persisted.+ databaseThroughTunnel.Port = new(localEndpoint.Port)+ // Topology discovery re-dials the addresses the replica set advertises, which leave the process+ // directly and never reach the forwarded port. Only the copy is pinned, so the stored config+ // keeps whatever failover behaviour the user chose.+ databaseThroughTunnel.IsDirectConnection = true+ // The copy describes an already forwarded connection; leaving this on would make anything that+ // re-reads it open a second tunnel pointed at the first one's local port.+ databaseThroughTunnel.SshTunnel.IsEnabled = false++ return &TunneledDatabase{+ original: spec.Database,+ databaseThroughTunnel: &databaseThroughTunnel,+ forwarder: forwarder,+ }, nil+}++func (t *TunneledDatabase) GetDatabaseThroughTunnel() *MongodbDatabase {+ if t == nil {+ return nil+ }++ return t.databaseThroughTunnel+}++// TestConnection and PopulateVersion write the detected version into the model they were handed,+// which is the copy. Callers that persist the result need it carried back.+func (t *TunneledDatabase) CopyDiscoveredMetadataToOriginal() {+ if t == nil || t.original == nil || t.databaseThroughTunnel == nil {+ return+ }++ t.original.Version = t.databaseThroughTunnel.Version+}++func (t *TunneledDatabase) Close() {+ if t == nil || t.forwarder == nil {+ return+ }++ t.forwarder.Close()+}diff --git a/backend/internal/features/databases/databases/mongodb/tunnel_test.go b/backend/internal/features/databases/databases/mongodb/tunnel_test.gonew file mode 100644index 00000000..bd44eaad--- /dev/null+++ b/backend/internal/features/databases/databases/mongodb/tunnel_test.go@@ -0,0 +1,124 @@+package mongodb++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/testing/containers"+)++const unreachableBastionTimeout = 2 * time.Second++func enabledTunnelDatabase() *MongodbDatabase {+ return &MongodbDatabase{+ Host: "db.internal",+ Port: new(27017),+ Username: "testuser",+ Password: "testpassword",+ Database: "testdb",+ AuthDatabase: "admin",+ CpuCount: 1,+ IsDirectConnection: false,+ SshTunnel: sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ },+ }+}++func bastionedTunnelDatabase(t *testing.T) *MongodbDatabase {+ t.Helper()++ bastion := containers.StartSshBastion(t)++ database := enabledTunnelDatabase()+ database.SshTunnel.Host = bastion.Host+ database.SshTunnel.Port = bastion.Port+ database.SshTunnel.Username = containers.SshBastionUsername+ database.SshTunnel.Password = containers.SshBastionPassword++ return database+}++func Test_OpenTunnel_WhenTheTunnelIsDisabled_HandsBackTheSameDatabase(t *testing.T) {+ database := enabledTunnelDatabase()+ database.SshTunnel.IsEnabled = false++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ assert.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.Same(t, database, tunneledDatabase.GetDatabaseThroughTunnel())+}++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.+ database.SshTunnel.Host = "192.0.2.1"++ // A blackholing network would otherwise burn the forwarder's full 30s dial timeout here.+ ctx, cancel := context.WithTimeout(t.Context(), unreachableBastionTimeout)+ defer cancel()++ _, err := OpenTunnel(ctx, OpenTunnelSpec{Database: database})++ assert.Error(t, err)+}++func Test_OpenTunnel_WhenTunneledWithoutAPort_ReturnsAnError(t *testing.T) {+ database := enabledTunnelDatabase()+ database.Port = nil++ _, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})++ assert.ErrorContains(t, err, "port")+}++func Test_OpenTunnel_WhenTunneled_DisablesTheTunnelFlagOnTheCopy(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.False(t, tunneledDatabase.GetDatabaseThroughTunnel().SshTunnel.IsEnabled,+ "a re-read of the copy would otherwise open a second tunnel into the first one")+ assert.True(t, database.SshTunnel.IsEnabled, "the original must keep the stored configuration")+}++func Test_OpenTunnel_WhenTunneled_GivesTheCopyItsOwnPortPointer(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.Equal(t, 27017, *database.Port, "the persisted model owns its own port")+ assert.NotSame(t, database.Port, tunneledDatabase.GetDatabaseThroughTunnel().Port)+ assert.Equal(t, "db.internal", database.Host)+}++func Test_OpenTunnel_WhenTunneled_ForcesDirectConnectionOnTheCopyOnly(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.True(t, tunneledDatabase.GetDatabaseThroughTunnel().IsDirectConnection,+ "topology discovery would re-dial the advertised member addresses and bypass the forward")+ assert.False(t, database.IsDirectConnection,+ "removing the tunnel must restore the failover behaviour the user configured")+}diff --git a/backend/internal/features/databases/databases/mysql/model.go b/backend/internal/features/databases/databases/mysql/model.goindex 5d07b95a..ec32cd73 100644--- a/backend/internal/features/databases/databases/mysql/model.go+++ b/backend/internal/features/databases/databases/mysql/model.go@@ -8,6 +8,7 @@ import ("fmt""log/slog""regexp"+ "slices""sort""strings""time"@@ -16,6 +17,7 @@ import ("github.com/google/uuid""gorm.io/gorm"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/encryption""databasus-backend/internal/util/namelist""databasus-backend/internal/util/tools"@@ -27,12 +29,16 @@ type MysqlDatabase struct {Version tools.MysqlVersion `json:"version" gorm:"type:text;not null"`- Host string `json:"host" gorm:"type:text;not null"`- Port int `json:"port" gorm:"type:int;not null"`- Username string `json:"username" gorm:"type:text;not null"`- Password string `json:"password" gorm:"type:text;not null"`- Database *string `json:"database" gorm:"type:text"`- IsHttps bool `json:"isHttps" gorm:"type:boolean;default:false"`+ Host string `json:"host" gorm:"type:text;not null"`+ Port int `json:"port" gorm:"type:int;not null"`+ Username string `json:"username" gorm:"type:text;not null"`+ Password string `json:"password" gorm:"type:text;not null"`+ Database *string `json:"database" gorm:"type:text"`+ IsHttps bool `json:"isHttps" gorm:"type:boolean;default:false"`++ // When the tunnel is enabled, Host and Port above address the database as the bastion sees it.+ SshTunnel sshtunnel.Config `json:"sshTunnel" gorm:"embedded;embeddedPrefix:ssh_"`+ExcludeTables []string `json:"excludeTables" gorm:"-"`ExcludeTablesString string `json:"-" gorm:"column:exclude_tables;type:text;not null;default:''"`Privileges string `json:"privileges" gorm:"column:privileges;type:text;not null;default:''"`@@ -67,7 +73,8 @@ func (m *MysqlDatabase) Validate() error {if m.Password == "" {return errors.New("password is required")}- return nil++ return m.SshTunnel.Validate()}func (m *MysqlDatabase) TestConnection(@@ -174,6 +181,7 @@ func (m *MysqlDatabase) HideSensitiveData() {return}m.Password = ""+ m.SshTunnel.HideSensitiveData()}func (m *MysqlDatabase) Update(incoming *MysqlDatabase) {@@ -185,12 +193,30 @@ func (m *MysqlDatabase) Update(incoming *MysqlDatabase) {m.IsHttps = incoming.IsHttpsm.ExcludeTables = incoming.ExcludeTablesm.Privileges = incoming.Privileges+ m.SshTunnel.Update(&incoming.SshTunnel)if incoming.Password != "" {m.Password = incoming.Password}}+func (m *MysqlDatabase) CopyForNewDatabase() *MysqlDatabase {+ if m == nil {+ return nil+ }++ copiedDatabase := *m+ copiedDatabase.ID = uuid.Nil+ copiedDatabase.DatabaseID = nil+ copiedDatabase.ExcludeTables = slices.Clone(m.ExcludeTables)++ if m.Database != nil {+ copiedDatabase.Database = new(*m.Database)+ }++ return &copiedDatabase+}+func (m *MysqlDatabase) EncryptSensitiveFields(encryptor encryption.FieldEncryptor,) error {@@ -201,7 +227,8 @@ func (m *MysqlDatabase) EncryptSensitiveFields(}m.Password = encrypted}- return nil++ return m.SshTunnel.EncryptSensitiveFields(encryptor)}func (m *MysqlDatabase) PopulateDbData(diff --git a/backend/internal/features/databases/databases/mysql/tunnel.go b/backend/internal/features/databases/databases/mysql/tunnel.gonew file mode 100644index 00000000..e26ca2e0--- /dev/null+++ b/backend/internal/features/databases/databases/mysql/tunnel.go@@ -0,0 +1,83 @@+package mysql++import (+ "context"+ "log/slog"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/encryption"+)++type OpenTunnelSpec struct {+ Database *MysqlDatabase+ Logger *slog.Logger+ Encryptor encryption.FieldEncryptor+}++// The tunnel belongs to the operation, not to the model: buildDSN is called separately by every+// method that reaches the server, so no method down there could own a Close.+type TunneledDatabase struct {+ original *MysqlDatabase+ databaseThroughTunnel *MysqlDatabase+ forwarder *sshtunnel.Forwarder+}++// 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 || !spec.Database.SshTunnel.IsEnabled {+ return &TunneledDatabase{original: spec.Database, databaseThroughTunnel: spec.Database}, nil+ }++ forwarder, err := sshtunnel.Open(ctx, sshtunnel.OpenSpec{+ Config: spec.Database.SshTunnel,+ Target: sshtunnel.Endpoint{Host: spec.Database.Host, Port: spec.Database.Port},+ Encryptor: spec.Encryptor,+ Logger: spec.Logger,+ })+ if err != nil {+ return nil, err+ }++ localEndpoint := forwarder.GetLocalEndpoint()++ databaseThroughTunnel := *spec.Database+ databaseThroughTunnel.Host = localEndpoint.Host+ databaseThroughTunnel.Port = localEndpoint.Port+ // The copy describes an already forwarded connection; leaving this on would make anything that+ // re-reads it open a second tunnel pointed at the first one's local port.+ databaseThroughTunnel.SshTunnel.IsEnabled = false++ return &TunneledDatabase{+ original: spec.Database,+ databaseThroughTunnel: &databaseThroughTunnel,+ forwarder: forwarder,+ }, nil+}++func (t *TunneledDatabase) GetDatabaseThroughTunnel() *MysqlDatabase {+ if t == nil {+ return nil+ }++ return t.databaseThroughTunnel+}++// TestConnection and PopulateDbData write what they detect into the model they were handed, which+// is the copy. Callers that persist the result need it carried back.+func (t *TunneledDatabase) CopyDiscoveredMetadataToOriginal() {+ if t == nil || t.original == nil || t.databaseThroughTunnel == nil {+ return+ }++ t.original.Version = t.databaseThroughTunnel.Version+ t.original.Privileges = t.databaseThroughTunnel.Privileges+}++func (t *TunneledDatabase) Close() {+ if t == nil || t.forwarder == nil {+ return+ }++ t.forwarder.Close()+}diff --git a/backend/internal/features/databases/databases/mysql/tunnel_test.go b/backend/internal/features/databases/databases/mysql/tunnel_test.gonew file mode 100644index 00000000..cdf58d4e--- /dev/null+++ b/backend/internal/features/databases/databases/mysql/tunnel_test.go@@ -0,0 +1,116 @@+package mysql++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/testing/containers"+ "databasus-backend/internal/util/tools"+)++const discoveredVersion = tools.MysqlVersion84++const unreachableBastionTimeout = 2 * time.Second++func enabledTunnelDatabase() *MysqlDatabase {+ databaseName := "testdb"++ return &MysqlDatabase{+ Host: "db.internal",+ Port: 3306,+ Username: "testuser",+ Password: "testpassword",+ Database: &databaseName,+ SshTunnel: sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ },+ }+}++func bastionedTunnelDatabase(t *testing.T) *MysqlDatabase {+ t.Helper()++ bastion := containers.StartSshBastion(t)++ database := enabledTunnelDatabase()+ database.SshTunnel.Host = bastion.Host+ database.SshTunnel.Port = bastion.Port+ database.SshTunnel.Username = containers.SshBastionUsername+ database.SshTunnel.Password = containers.SshBastionPassword++ return database+}++func Test_OpenTunnel_WhenTheTunnelIsDisabled_HandsBackTheSameDatabase(t *testing.T) {+ database := enabledTunnelDatabase()+ database.SshTunnel.IsEnabled = false++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ assert.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.Same(t, database, tunneledDatabase.GetDatabaseThroughTunnel())+}++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.+ database.SshTunnel.Host = "192.0.2.1"++ // A blackholing network would otherwise burn the forwarder's full 30s dial timeout here.+ ctx, cancel := context.WithTimeout(t.Context(), unreachableBastionTimeout)+ defer cancel()++ _, err := OpenTunnel(ctx, OpenTunnelSpec{Database: database})++ assert.Error(t, err)+}++func Test_OpenTunnel_WhenTunneled_DisablesTheTunnelFlagOnTheCopy(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()++ assert.False(t, databaseThroughTunnel.SshTunnel.IsEnabled,+ "a re-read of the copy would otherwise open a second tunnel into the first one")+ assert.True(t, database.SshTunnel.IsEnabled, "the original must keep the stored configuration")+ assert.Equal(t, "db.internal", database.Host, "the original address must not be rewritten")+ assert.Equal(t, 3306, database.Port)+ assert.Equal(t, "127.0.0.1", databaseThroughTunnel.Host)+ assert.NotEqual(t, database.Port, databaseThroughTunnel.Port)+}++// Discovery runs against the copy, so anything it writes there is lost unless it is carried back:+// a bastioned database would otherwise be saved with the privileges of a connection never made.+func Test_CopyDiscoveredMetadataToOriginal_CarriesTheVersionAndPrivileges(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()+ databaseThroughTunnel.Version = discoveredVersion+ databaseThroughTunnel.Privileges = "SELECT,LOCK TABLES"++ tunneledDatabase.CopyDiscoveredMetadataToOriginal()++ assert.Equal(t, discoveredVersion, database.Version)+ assert.Equal(t, "SELECT,LOCK TABLES", database.Privileges)+}diff --git a/backend/internal/features/databases/databases/postgresql/logical/connection.go b/backend/internal/features/databases/databases/postgresql/logical/connection.goindex 1862da7b..490932e9 100644--- a/backend/internal/features/databases/databases/postgresql/logical/connection.go+++ b/backend/internal/features/databases/databases/postgresql/logical/connection.go@@ -14,8 +14,14 @@ import (// shared by every libpq path: the pgx connections here and pg_dump / pg_restore// in the backup and restore usecases.func (p *PostgresqlLogicalDatabase) CredentialSpec() postgresql_shared.CredentialSpec {+ hostAddr := ""+ if p.LocalTunnelEndpoint != nil {+ hostAddr = p.LocalTunnelEndpoint.Host+ }+return postgresql_shared.CredentialSpec{Host: p.Host,+ HostAddr: hostAddr,Port: p.Port,Username: p.Username,SslMode: p.SslMode,@@ -44,5 +50,10 @@ func openPgConn(}defer files.Remove()- return pgx.Connect(ctx, postgresql_shared.BuildConnString(p.CredentialSpec(), password, dbName, files))+ connConfig, err := postgresql_shared.BuildConnConfig(p.CredentialSpec(), password, dbName, files)+ if err != nil {+ return nil, err+ }++ return pgx.ConnectConfig(ctx, connConfig)}diff --git a/backend/internal/features/databases/databases/postgresql/logical/connection_test.go b/backend/internal/features/databases/databases/postgresql/logical/connection_test.gonew file mode 100644index 00000000..dcc9c86e--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/logical/connection_test.go@@ -0,0 +1,39 @@+package postgresql_logical++import (+ "testing"++ "github.com/stretchr/testify/assert"++ "databasus-backend/internal/features/sshtunnel"+)++func credentialSpecDatabase() *PostgresqlLogicalDatabase {+ databaseName := "testdb"++ return &PostgresqlLogicalDatabase{+ Host: "db.internal",+ Port: 5432,+ Username: "testuser",+ Password: "testpassword",+ Database: &databaseName,+ CpuCount: 1,+ }+}++func Test_CredentialSpec_WithoutATunnel_LeavesHostAddrEmpty(t *testing.T) {+ spec := credentialSpecDatabase().CredentialSpec()++ assert.Equal(t, "db.internal", spec.Host)+ assert.Empty(t, spec.HostAddr)+}++func Test_CredentialSpec_WithALocalTunnelEndpoint_KeepsTheRealHostAndCarriesTheAddress(t *testing.T) {+ database := credentialSpecDatabase()+ database.LocalTunnelEndpoint = &sshtunnel.Endpoint{Host: "127.0.0.1", Port: 41000}++ spec := database.CredentialSpec()++ assert.Equal(t, "db.internal", spec.Host)+ assert.Equal(t, "127.0.0.1", spec.HostAddr)+}diff --git a/backend/internal/features/databases/databases/postgresql/logical/model.go b/backend/internal/features/databases/databases/postgresql/logical/model.goindex 855ea1ba..61ab4050 100644--- a/backend/internal/features/databases/databases/postgresql/logical/model.go+++ b/backend/internal/features/databases/databases/postgresql/logical/model.go@@ -6,6 +6,7 @@ import ("fmt""log/slog""regexp"+ "slices""strings""time"@@ -15,6 +16,7 @@ import ("gorm.io/gorm"postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/encryption""databasus-backend/internal/util/namelist""databasus-backend/internal/util/tools"@@ -39,6 +41,13 @@ type PostgresqlLogicalDatabase struct {SslClientKey string `json:"sslClientKey" gorm:"column:ssl_client_key;type:text;not null;default:''"`SslRootCert string `json:"sslRootCert" gorm:"column:ssl_root_cert;type:text;not null;default:''"`+ // When the tunnel is enabled, Host and Port above address the database as the bastion sees it.+ SshTunnel sshtunnel.Config `json:"sshTunnel" gorm:"embedded;embeddedPrefix:ssh_"`++ // Set only on the copy handed out by OpenTunnel, so CredentialSpec can point libpq at the+ // forwarded port while Host keeps the name that TLS and .pgpass are matched against.+ LocalTunnelEndpoint *sshtunnel.Endpoint `json:"-" gorm:"-"`+// backup settingsIncludeSchemas []string `json:"includeSchemas" gorm:"-"`IncludeSchemasString string `json:"-" gorm:"column:include_schemas;type:text;not null;default:''"`@@ -100,40 +109,23 @@ func (p *PostgresqlLogicalDatabase) Validate() error {return err}+ if err := p.SshTunnel.Validate(); err != nil {+ 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- if p.Database != nil && *p.Database != "" {- 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- }-- isLocalhost := false-- for _, host := range localhostHosts {- if strings.EqualFold(p.Host, host) {- isLocalhost = true- break- }- }-- // Also check if the host is in the entire 127.0.0.0/8 loopback range- if strings.HasPrefix(p.Host, "127.") {- isLocalhost = true- }-- if isLocalhost && 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",- )- }+ // 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",+ )}return nil@@ -188,6 +180,7 @@ func (p *PostgresqlLogicalDatabase) HideSensitiveData() {p.Password = ""p.SslClientKey = ""+ p.SshTunnel.HideSensitiveData()}func (p *PostgresqlLogicalDatabase) ValidateUpdate(_ *PostgresqlLogicalDatabase) error {@@ -207,6 +200,7 @@ func (p *PostgresqlLogicalDatabase) Update(incoming *PostgresqlLogicalDatabase)p.ExcludeTables = incoming.ExcludeTablesp.CpuCount = incoming.CpuCountp.IsSkipUserMappings = incoming.IsSkipUserMappings+ p.SshTunnel.Update(&incoming.SshTunnel)if incoming.Password != "" {p.Password = incoming.Password@@ -217,6 +211,26 @@ func (p *PostgresqlLogicalDatabase) Update(incoming *PostgresqlLogicalDatabase)}}+// LocalTunnelEndpoint belongs to the operation that opened the tunnel, not to the configuration.+func (p *PostgresqlLogicalDatabase) CopyForNewDatabase() *PostgresqlLogicalDatabase {+ if p == nil {+ return nil+ }++ copiedDatabase := *p+ copiedDatabase.ID = uuid.Nil+ copiedDatabase.DatabaseID = nil+ copiedDatabase.IncludeSchemas = slices.Clone(p.IncludeSchemas)+ copiedDatabase.ExcludeTables = slices.Clone(p.ExcludeTables)+ copiedDatabase.LocalTunnelEndpoint = nil++ if p.Database != nil {+ copiedDatabase.Database = new(*p.Database)+ }++ return &copiedDatabase+}+func (p *PostgresqlLogicalDatabase) EncryptSensitiveFields(encryptor encryption.FieldEncryptor,) error {@@ -238,7 +252,7 @@ func (p *PostgresqlLogicalDatabase) EncryptSensitiveFields(*field = encrypted}- return nil+ return p.SshTunnel.EncryptSensitiveFields(encryptor)}// PopulateDbData detects and sets the PostgreSQL version.@@ -1143,3 +1157,28 @@ 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.goindex 1fac1d2f..ae322b97 100644--- a/backend/internal/features/databases/databases/postgresql/logical/model_test.go+++ b/backend/internal/features/databases/databases/postgresql/logical/model_test.go@@ -13,6 +13,7 @@ import ("github.com/stretchr/testify/assert"postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/testing/containers""databasus-backend/internal/util/tools")@@ -2153,3 +2154,50 @@ func extractPostgresVersion(versionStr string) tools.PostgresqlVersion {return tools.GetPostgresqlVersionEnum("16")}++func databasusOnLoopback() *PostgresqlLogicalDatabase {+ databaseName := "databasus"++ return &PostgresqlLogicalDatabase{+ Host: "127.0.0.1",+ Port: 5432,+ Username: "postgres",+ Password: "password",+ Database: &databaseName,+ CpuCount: 1,+ }+}++func Test_Validate_WhenPointedAtDatabasusOnLoopback_IsRejected(t *testing.T) {+ assert.Error(t, databasusOnLoopback().Validate())+}++func Test_Validate_WhenDatabasusOnLoopbackIsBehindARemoteBastion_IsAllowed(t *testing.T) {+ database := databasusOnLoopback()+ database.SshTunnel = sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ }++ assert.NoError(t, database.Validate())+}++// A bastion on this machine forwards straight back to the instance the guard protects, so enabling+// a tunnel must not be a way around it.+func Test_Validate_WhenDatabasusOnLoopbackIsBehindALocalBastion_IsRejected(t *testing.T) {+ for _, bastionHost := range []string{"127.0.0.1", "localhost", "host.docker.internal", "127.5.5.5"} {+ database := databasusOnLoopback()+ database.SshTunnel = sshtunnel.Config{+ IsEnabled: true,+ Host: bastionHost,+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ }++ assert.Error(t, database.Validate(), "bastion host %q must not bypass the guard", bastionHost)+ }+}diff --git a/backend/internal/features/databases/databases/postgresql/logical/tunnel.go b/backend/internal/features/databases/databases/postgresql/logical/tunnel.gonew file mode 100644index 00000000..1ba092c7--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/logical/tunnel.go@@ -0,0 +1,84 @@+package postgresql_logical++import (+ "context"+ "log/slog"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/encryption"+)++type OpenTunnelSpec struct {+ Database *PostgresqlLogicalDatabase+ Logger *slog.Logger+ Encryptor encryption.FieldEncryptor+}++// The tunnel belongs to the operation, not to the model: openPgConn hands back a live connection+// that outlives the call, so no method down there could own a Close.+type TunneledDatabase struct {+ original *PostgresqlLogicalDatabase+ databaseThroughTunnel *PostgresqlLogicalDatabase+ forwarder *sshtunnel.Forwarder+}++// 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 || !spec.Database.SshTunnel.IsEnabled {+ return &TunneledDatabase{original: spec.Database, databaseThroughTunnel: spec.Database}, nil+ }++ forwarder, err := sshtunnel.Open(ctx, sshtunnel.OpenSpec{+ Config: spec.Database.SshTunnel,+ Target: sshtunnel.Endpoint{Host: spec.Database.Host, Port: spec.Database.Port},+ Encryptor: spec.Encryptor,+ Logger: spec.Logger,+ })+ if err != nil {+ return nil, err+ }++ localEndpoint := forwarder.GetLocalEndpoint()++ databaseThroughTunnel := *spec.Database+ // Host stays the real one: sslmode=verify-full matches the certificate against it, and libpq+ // looks up .pgpass by host and port.+ databaseThroughTunnel.Port = localEndpoint.Port+ databaseThroughTunnel.LocalTunnelEndpoint = &localEndpoint+ // The copy describes an already forwarded connection; leaving this on would make anything that+ // re-reads it open a second tunnel pointed at the first one's local port.+ databaseThroughTunnel.SshTunnel.IsEnabled = false++ return &TunneledDatabase{+ original: spec.Database,+ databaseThroughTunnel: &databaseThroughTunnel,+ forwarder: forwarder,+ }, nil+}++func (t *TunneledDatabase) GetDatabaseThroughTunnel() *PostgresqlLogicalDatabase {+ if t == nil {+ return nil+ }++ return t.databaseThroughTunnel+}++// TestConnection and PopulateVersion write the detected version into the model they were handed,+// which is the copy. Callers that persist the result need it carried back.+func (t *TunneledDatabase) CopyDiscoveredMetadataToOriginal() {+ if t == nil || t.original == nil || t.databaseThroughTunnel == nil {+ return+ }++ t.original.Version = t.databaseThroughTunnel.Version+}++func (t *TunneledDatabase) Close() {+ if t == nil || t.forwarder == nil {+ return+ }++ t.forwarder.Close()+}diff --git a/backend/internal/features/databases/databases/postgresql/logical/tunnel_test.go b/backend/internal/features/databases/databases/postgresql/logical/tunnel_test.gonew file mode 100644index 00000000..d6f090ea--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/logical/tunnel_test.go@@ -0,0 +1,109 @@+package postgresql_logical++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/testing/containers"+)++const unreachableBastionTimeout = 2 * time.Second++func enabledTunnelDatabase() *PostgresqlLogicalDatabase {+ databaseName := "testdb"++ return &PostgresqlLogicalDatabase{+ Host: "db.internal",+ Port: 5432,+ Username: "testuser",+ Password: "testpassword",+ Database: &databaseName,+ CpuCount: 1,+ SshTunnel: sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ },+ }+}++func bastionedTunnelDatabase(t *testing.T) *PostgresqlLogicalDatabase {+ t.Helper()++ bastion := containers.StartSshBastion(t)++ database := enabledTunnelDatabase()+ database.SshTunnel.Host = bastion.Host+ database.SshTunnel.Port = bastion.Port+ database.SshTunnel.Username = containers.SshBastionUsername+ database.SshTunnel.Password = containers.SshBastionPassword++ return database+}++func Test_OpenTunnel_WhenTheTunnelIsDisabled_HandsBackTheSameDatabase(t *testing.T) {+ database := enabledTunnelDatabase()+ database.SshTunnel.IsEnabled = false++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ assert.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.Same(t, database, tunneledDatabase.GetDatabaseThroughTunnel())+}++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.+ database.SshTunnel.Host = "192.0.2.1"++ // A blackholing network would otherwise burn the forwarder's full 30s dial timeout here.+ ctx, cancel := context.WithTimeout(t.Context(), unreachableBastionTimeout)+ defer cancel()++ _, err := OpenTunnel(ctx, OpenTunnelSpec{Database: database})++ assert.Error(t, err)+}++// PostgreSQL is the one engine whose copy keeps the real host: sslmode=verify-full matches the+// certificate against it, and libpq looks up .pgpass by host and port.+func Test_OpenTunnel_WhenTunneled_KeepsTheRealHostAndCarriesTheForwardedPort(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()++ assert.Equal(t, "db.internal", databaseThroughTunnel.Host)+ require.NotNil(t, databaseThroughTunnel.LocalTunnelEndpoint)+ assert.Equal(t, "127.0.0.1", databaseThroughTunnel.LocalTunnelEndpoint.Host)+ assert.Equal(t, databaseThroughTunnel.LocalTunnelEndpoint.Port, databaseThroughTunnel.Port)+ assert.NotEqual(t, database.Port, databaseThroughTunnel.Port)+}++func Test_OpenTunnel_WhenTunneled_DisablesTheTunnelFlagOnTheCopy(t *testing.T) {+ database := bastionedTunnelDatabase(t)++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.False(t, tunneledDatabase.GetDatabaseThroughTunnel().SshTunnel.IsEnabled,+ "a re-read of the copy would otherwise open a second tunnel into the first one")+ assert.True(t, database.SshTunnel.IsEnabled, "the original must keep the stored configuration")+ assert.Equal(t, 5432, database.Port, "the original address must not be rewritten")+ assert.Nil(t, database.LocalTunnelEndpoint)+}diff --git a/backend/internal/features/databases/databases/postgresql/physical/model.go b/backend/internal/features/databases/databases/postgresql/physical/model.goindex 87dd0f8e..eeedb182 100644--- a/backend/internal/features/databases/databases/postgresql/physical/model.go+++ b/backend/internal/features/databases/databases/postgresql/physical/model.go@@ -150,6 +150,26 @@ func (p *PostgresqlPhysicalDatabase) HideSensitiveData() {p.SslClientKey = ""}+// Copying the struct rather than listing fields is the point: a field added later travels with it+// instead of being silently dropped. The three server-managed fields must not travel: BeforeCreate+// only mints a replication slot name when the field is empty, so an inherited one would leave two+// databases sharing a single slot on the source cluster, and the identifier and segment size are+// read back from whichever cluster the copy is pointed at.+func (p *PostgresqlPhysicalDatabase) CopyForNewDatabase() *PostgresqlPhysicalDatabase {+ if p == nil {+ return nil+ }++ copiedDatabase := *p+ copiedDatabase.ID = uuid.Nil+ copiedDatabase.DatabaseID = nil+ copiedDatabase.ReplicationSlotName = ""+ copiedDatabase.SystemIdentifier = nil+ copiedDatabase.WalSegmentSizeBytes = nil++ return &copiedDatabase+}+func (p *PostgresqlPhysicalDatabase) EncryptSensitiveFields(encryptor encryption.FieldEncryptor,) error {diff --git a/backend/internal/features/databases/databases/postgresql/shared/credentials.go b/backend/internal/features/databases/databases/postgresql/shared/credentials.goindex 726fc889..3beaf563 100644--- a/backend/internal/features/databases/databases/postgresql/shared/credentials.go+++ b/backend/internal/features/databases/databases/postgresql/shared/credentials.go@@ -7,13 +7,18 @@ import ("strings""github.com/google/uuid"+ "github.com/jackc/pgx/v5""databasus-backend/internal/util/encryption""databasus-backend/internal/util/tools")type CredentialSpec struct {- Host string+ Host string+ // Named after the libpq parameter it maps to: when set, the connection is made to this address+ // while Host is what the certificate and .pgpass are matched against. That split is what lets an+ // SSH tunnel forward the traffic without breaking sslmode=verify-full.+ HostAddr stringPort intUsername stringSslMode PostgresSslMode@@ -80,7 +85,7 @@ func BuildConnString() string {connStr := fmt.Sprintf("host=%s port=%d user=%s password='%s' dbname=%s sslmode=%s",- spec.Host,+ getConnectHost(spec),spec.Port,spec.Username,escapeConnStringValue(password),@@ -115,6 +120,53 @@ func BuildPhysicalReplicationConnString(return appendSslFilePaths(connStr, files)}+// pgx has no hostaddr parameter, so through a tunnel the address goes in as the host and the real+// name is restored on the TLS config, which is what sslmode=verify-full matches against.+func BuildConnConfig(+ spec CredentialSpec,+ password, dbName string,+ files *CredentialTempFiles,+) (*pgx.ConnConfig, error) {+ connConfig, err := pgx.ParseConfig(BuildConnString(spec, password, dbName, files))+ if err != nil {+ return nil, fmt.Errorf("failed to parse the PostgreSQL connection string: %w", err)+ }++ if spec.HostAddr == "" {+ return connConfig, nil+ }++ if connConfig.TLSConfig != nil {+ connConfig.TLSConfig.ServerName = spec.Host+ }++ for _, fallback := range connConfig.Fallbacks {+ if fallback.TLSConfig != nil {+ fallback.TLSConfig.ServerName = spec.Host+ }+ }++ return connConfig, nil+}++// libpq resolves and connects to hostaddr while still matching the certificate and .pgpass against+// the host argument, so the CLI tools need no rewritten -h.+func GetPgHostAddrEnv(spec CredentialSpec) []string {+ if spec.HostAddr == "" {+ return nil+ }++ return []string{"PGHOSTADDR=" + spec.HostAddr}+}++func getConnectHost(spec CredentialSpec) string {+ if spec.HostAddr != "" {+ return spec.HostAddr+ }++ return spec.Host+}+func sslModeOrDefault(spec CredentialSpec) PostgresSslMode {if spec.SslMode == "" {return PostgresSslModeDisablediff --git a/backend/internal/features/databases/model.go b/backend/internal/features/databases/model.goindex 1df8def9..023ddcdc 100644--- a/backend/internal/features/databases/model.go+++ b/backend/internal/features/databases/model.go@@ -4,6 +4,7 @@ import ("context""errors""log/slog"+ "slices""time""github.com/google/uuid"@@ -14,6 +15,7 @@ import (postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical""databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/encryption")@@ -217,6 +219,68 @@ func (d *Database) HideSensitiveData() {}}+// Here and on every engine model the copy starts from the struct rather than a field list, so a+// field added later travels with it instead of being silently dropped; only identity, per-operation+// state and shared pointers are spelled out. Only the sub-model matching Type is carried over: the+// shallow copy would otherwise alias all five engine pointers onto the new row.+func (d *Database) CopyForNewDatabase() *Database {+ if d == nil {+ return nil+ }++ copiedDatabase := *d+ copiedDatabase.ID = uuid.Nil+ // The copy has no backup history of its own, and showing the source's would be a lie.+ copiedDatabase.LastBackupTime = nil+ copiedDatabase.LastBackupErrorMessage = nil+ copiedDatabase.Notifiers = slices.Clone(d.Notifiers)++ copiedDatabase.PostgresqlLogical = nil+ copiedDatabase.PostgresqlPhysical = nil+ copiedDatabase.Mysql = nil+ copiedDatabase.Mariadb = nil+ copiedDatabase.Mongodb = nil++ if d.HealthStatus != nil {+ copiedDatabase.HealthStatus = new(*d.HealthStatus)+ }++ switch d.Type {+ case DatabaseTypePostgresLogical:+ copiedDatabase.PostgresqlLogical = d.PostgresqlLogical.CopyForNewDatabase()+ case DatabaseTypePostgresPhysical:+ copiedDatabase.PostgresqlPhysical = d.PostgresqlPhysical.CopyForNewDatabase()+ case DatabaseTypeMysql:+ copiedDatabase.Mysql = d.Mysql.CopyForNewDatabase()+ case DatabaseTypeMariadb:+ copiedDatabase.Mariadb = d.Mariadb.CopyForNewDatabase()+ case DatabaseTypeMongodb:+ copiedDatabase.Mongodb = d.Mongodb.CopyForNewDatabase()+ }++ return &copiedDatabase+}++// The agent restores into a container it owns, so it never dials the source and has no use for the+// bastion's address or account.+func (d *Database) ClearSshTunnelConfig() {+ if d.PostgresqlLogical != nil {+ d.PostgresqlLogical.SshTunnel = sshtunnel.Config{}+ }++ if d.Mysql != nil {+ d.Mysql.SshTunnel = sshtunnel.Config{}+ }++ if d.Mariadb != nil {+ d.Mariadb.SshTunnel = sshtunnel.Config{}+ }++ if d.Mongodb != nil {+ d.Mongodb.SshTunnel = sshtunnel.Config{}+ }+}+func (d *Database) EncryptSensitiveFields(encryptor encryption.FieldEncryptor) error {if d.PostgresqlLogical != nil {return d.PostgresqlLogical.EncryptSensitiveFields(encryptor)@@ -258,6 +322,43 @@ func (d *Database) PopulateDbData(return nil}+// Dispatches on Type rather than on the first non-nil sub-model, because OpenTunnel dispatches on+// Type too: a row carrying two engine configs would otherwise open the tunnel for one and connect+// with the other, straight past the bastion.+func (d *Database) PopulateVersion(+ logger *slog.Logger,+ encryptor encryption.FieldEncryptor,+) error {+ switch d.Type {+ case DatabaseTypePostgresLogical:+ if d.PostgresqlLogical == nil {+ return errors.New("postgresql logical config is not set")+ }++ return d.PostgresqlLogical.PopulateVersion(logger, encryptor)+ case DatabaseTypeMysql:+ if d.Mysql == nil {+ return errors.New("mysql config is not set")+ }++ return d.Mysql.PopulateVersion(logger, encryptor)+ case DatabaseTypeMariadb:+ if d.Mariadb == nil {+ return errors.New("mariadb config is not set")+ }++ return d.Mariadb.PopulateVersion(logger, encryptor)+ case DatabaseTypeMongodb:+ if d.Mongodb == nil {+ return errors.New("mongodb config is not set")+ }++ return d.Mongodb.PopulateVersion(logger, encryptor)+ default:+ return errors.New("version detection not supported for database type: " + string(d.Type))+ }+}+func (d *Database) Update(incoming *Database) {d.Name = incoming.Named.Type = incoming.Typediff --git a/backend/internal/features/databases/model_test.go b/backend/internal/features/databases/model_test.goindex f0d4ed8c..55d7fb29 100644--- a/backend/internal/features/databases/model_test.go+++ b/backend/internal/features/databases/model_test.go@@ -2,11 +2,23 @@ package databasesimport ("testing"+ "time"+ "github.com/google/uuid""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "databasus-backend/internal/features/databases/databases/mariadb"+ "databasus-backend/internal/features/databases/databases/mongodb"+ "databasus-backend/internal/features/databases/databases/mysql"+ postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"+ postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared"+ "databasus-backend/internal/features/notifiers"+ "databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/encryption""databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/tools")func Test_TestConnection_ForEveryDatabaseType_WithoutEngineConfig_ReturnsErrorInsteadOfPanicking(@@ -74,3 +86,404 @@ func Test_GetRawDbSizeMb_ForEveryDatabaseType_WithoutEngineConfig_ReturnsErrorIn})}}++func Test_PopulateVersion_ForEveryDatabaseType_WithoutEngineConfig_ReturnsErrorInsteadOfPanicking(+ t *testing.T,+) {+ missingConfigCases := []struct {+ databaseType DatabaseType+ errorMessage string+ }{+ {DatabaseTypePostgresLogical, "postgresql logical config is not set"},+ {DatabaseTypeMysql, "mysql config is not set"},+ {DatabaseTypeMariadb, "mariadb config is not set"},+ {DatabaseTypeMongodb, "mongodb config is not set"},+ {+ DatabaseTypePostgresPhysical,+ "version detection not supported for database type: POSTGRES_PHYSICAL",+ },+ {+ DatabaseType("CASSANDRA"),+ "version detection not supported for database type: CASSANDRA",+ },+ }++ for _, missingConfigCase := range missingConfigCases {+ t.Run(string(missingConfigCase.databaseType), func(t *testing.T) {+ databaseWithoutConfig := Database{Type: missingConfigCase.databaseType}++ err := databaseWithoutConfig.PopulateVersion(+ logger.GetLogger(),+ encryption.GetFieldEncryptor(),+ )++ assert.EqualError(t, err, missingConfigCase.errorMessage)+ })+ }+}++// Dispatching on the first non-nil sub-model instead would open the tunnel for Type and connect+// with a different engine, straight past the bastion.+func Test_PopulateVersion_WhenTheDatabaseCarriesAStaleEngineConfig_DispatchesOnTheType(t *testing.T) {+ databaseWithStaleConfig := Database{+ Type: DatabaseTypeMysql,+ Mongodb: filledSourceDatabase(DatabaseTypeMongodb).Mongodb,+ }++ err := databaseWithStaleConfig.PopulateVersion(+ logger.GetLogger(),+ encryption.GetFieldEncryptor(),+ )++ assert.EqualError(t, err, "mysql config is not set")+}++func Test_HideSensitiveData_ForEveryTunnelCapableType_ClearsTheTunnelSecrets(t *testing.T) {+ for _, databaseType := range []DatabaseType{+ DatabaseTypePostgresLogical,+ DatabaseTypeMysql,+ DatabaseTypeMariadb,+ DatabaseTypeMongodb,+ } {+ t.Run(string(databaseType), func(t *testing.T) {+ database := filledSourceDatabase(databaseType)++ database.HideSensitiveData()++ tunnel := getSshTunnelConfig(t, database)+ assert.Empty(t, tunnel.Password)+ assert.Empty(t, tunnel.PrivateKey)+ assert.Empty(t, tunnel.PrivateKeyPassphrase)+ assert.Equal(t, "tunneluser", tunnel.Username, "the address stays readable in the UI")+ assert.True(t, tunnel.IsEnabled)+ })+ }+}++func Test_ClearSshTunnelConfig_ForEveryTunnelCapableType_RemovesTheWholeBlock(t *testing.T) {+ for _, databaseType := range []DatabaseType{+ DatabaseTypePostgresLogical,+ DatabaseTypeMysql,+ DatabaseTypeMariadb,+ DatabaseTypeMongodb,+ } {+ t.Run(string(databaseType), func(t *testing.T) {+ database := filledSourceDatabase(databaseType)++ database.ClearSshTunnelConfig()++ assert.Equal(t, sshtunnel.Config{}, getSshTunnelConfig(t, database))+ })+ }+}++func getSshTunnelConfig(t *testing.T, database *Database) sshtunnel.Config {+ t.Helper()++ switch database.Type {+ case DatabaseTypePostgresLogical:+ return database.PostgresqlLogical.SshTunnel+ case DatabaseTypeMysql:+ return database.Mysql.SshTunnel+ case DatabaseTypeMariadb:+ return database.Mariadb.SshTunnel+ case DatabaseTypeMongodb:+ return database.Mongodb.SshTunnel+ }++ t.Fatalf("no ssh tunnel config for database type %s", database.Type)++ return sshtunnel.Config{}+}++// These compare whole structs on purpose: a field added to an engine model tomorrow has to fail+// here rather than quietly vanish from every copied database.++func filledSshTunnel() sshtunnel.Config {+ return sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 2222,+ Username: "tunneluser",+ Password: "enc:tunnelpassword",+ PrivateKey: "enc:privatekey",+ PrivateKeyPassphrase: "enc:passphrase",+ }+}++func filledSourceDatabase(databaseType DatabaseType) *Database {+ lastBackupTime := time.Date(2026, 8, 12, 10, 0, 0, 0, time.UTC)+ lastBackupErrorMessage := "previous failure"+ healthStatus := HealthStatusAvailable+ workspaceID := uuid.New()+ databaseID := uuid.New()+ databaseName := "sourcedb"+ systemIdentifier := "7300000000000000000"+ walSegmentSizeBytes := int64(16 * 1024 * 1024)+ mongodbPort := 27017++ database := &Database{+ ID: databaseID,+ WorkspaceID: &workspaceID,+ Name: "Source",+ Type: databaseType,+ Notifiers: []notifiers.Notifier{+ {ID: uuid.New(), WorkspaceID: workspaceID, Name: "Ops channel"},+ },+ LastBackupTime: &lastBackupTime,+ LastBackupErrorMessage: &lastBackupErrorMessage,+ HealthStatus: &healthStatus,+ }++ switch databaseType {+ case DatabaseTypePostgresLogical:+ database.PostgresqlLogical = &postgresql_logical.PostgresqlLogicalDatabase{+ ID: uuid.New(),+ DatabaseID: &databaseID,+ Version: tools.PostgresqlVersion16,+ Host: "db.internal",+ Port: 5432,+ Username: "testuser",+ Password: "enc:testpassword",+ Database: &databaseName,+ SslMode: postgresql_shared.PostgresSslModeRequire,+ SslClientCert: "clientcert",+ SslClientKey: "enc:clientkey",+ SslRootCert: "rootcert",+ SshTunnel: filledSshTunnel(),+ // Set as if the source had just been reached through a tunnel, which is the state the+ // copy must not inherit.+ LocalTunnelEndpoint: &sshtunnel.Endpoint{Host: "127.0.0.1", Port: 41000},+ IncludeSchemas: []string{"public", "reporting"},+ ExcludeTables: []string{"audit_log"},+ CpuCount: 4,+ IsSkipUserMappings: true,+ }+ case DatabaseTypePostgresPhysical:+ database.PostgresqlPhysical = &postgresql_physical.PostgresqlPhysicalDatabase{+ ID: uuid.New(),+ DatabaseID: &databaseID,+ Version: tools.PostgresqlVersion17,+ BackupType: postgresql_physical.BackupTypeFullOnly,+ Host: "db.internal",+ Port: 5432,+ Username: "testuser",+ Password: "enc:testpassword",+ SslMode: postgresql_shared.PostgresSslModeRequire,+ SslClientCert: "clientcert",+ SslClientKey: "enc:clientkey",+ SslRootCert: "rootcert",+ ReplicationSlotName: "databasus_slot_deadbeef",+ SystemIdentifier: &systemIdentifier,+ WalSegmentSizeBytes: &walSegmentSizeBytes,+ }+ case DatabaseTypeMysql:+ database.Mysql = &mysql.MysqlDatabase{+ ID: uuid.New(),+ DatabaseID: &databaseID,+ Version: tools.MysqlVersion84,+ Host: "db.internal",+ Port: 3306,+ Username: "testuser",+ Password: "enc:testpassword",+ Database: &databaseName,+ IsHttps: true,+ SshTunnel: filledSshTunnel(),+ ExcludeTables: []string{"audit_log"},+ Privileges: "SELECT,LOCK TABLES",+ }+ case DatabaseTypeMariadb:+ database.Mariadb = &mariadb.MariadbDatabase{+ ID: uuid.New(),+ DatabaseID: &databaseID,+ Version: tools.MariadbVersion114,+ Host: "db.internal",+ Port: 3306,+ Username: "testuser",+ Password: "enc:testpassword",+ Database: &databaseName,+ IsHttps: true,+ IsExcludeEvents: true,+ IsSkipGaleraDisable: true,+ SshTunnel: filledSshTunnel(),+ ExcludeTables: []string{"audit_log"},+ Privileges: "SELECT,LOCK TABLES",+ }+ case DatabaseTypeMongodb:+ database.Mongodb = &mongodb.MongodbDatabase{+ ID: uuid.New(),+ DatabaseID: &databaseID,+ Version: tools.MongodbVersion7,+ Host: "db.internal",+ Port: &mongodbPort,+ Username: "testuser",+ Password: "enc:testpassword",+ Database: "sourcedb",+ AuthDatabase: "admin",+ IsHttps: true,+ IsDirectConnection: true,+ CpuCount: 4,+ SshTunnel: filledSshTunnel(),+ ExcludeCollections: []string{"sessions"},+ }+ }++ return database+}++func Test_CopyForNewDatabase_WhenTheSourceIsPostgresqlLogical_KeepsEveryConfiguredField(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypePostgresLogical)++ copiedEngine := sourceDatabase.CopyForNewDatabase().PostgresqlLogical+ require.NotNil(t, copiedEngine)++ sourceEngineWithoutIdentity := *sourceDatabase.PostgresqlLogical+ sourceEngineWithoutIdentity.ID = uuid.Nil+ sourceEngineWithoutIdentity.DatabaseID = nil+ sourceEngineWithoutIdentity.LocalTunnelEndpoint = nil++ assert.Equal(t, sourceEngineWithoutIdentity, *copiedEngine)+ assert.NotSame(t, sourceDatabase.PostgresqlLogical.Database, copiedEngine.Database)+}++// The endpoint belongs to the operation that opened the tunnel, so a copy inheriting it would point+// at a forwarder that closed with that operation.+func Test_CopyForNewDatabase_WhenTheSourceIsPostgresqlLogical_DropsTheLocalTunnelEndpoint(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypePostgresLogical)+ require.NotNil(t, sourceDatabase.PostgresqlLogical.LocalTunnelEndpoint)++ copiedEngine := sourceDatabase.CopyForNewDatabase().PostgresqlLogical+ require.NotNil(t, copiedEngine)++ assert.Nil(t, copiedEngine.LocalTunnelEndpoint)+}++func Test_CopyForNewDatabase_WhenTheSourceIsMysql_KeepsEveryConfiguredField(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMysql)++ copiedEngine := sourceDatabase.CopyForNewDatabase().Mysql+ require.NotNil(t, copiedEngine)++ sourceEngineWithoutIdentity := *sourceDatabase.Mysql+ sourceEngineWithoutIdentity.ID = uuid.Nil+ sourceEngineWithoutIdentity.DatabaseID = nil++ assert.Equal(t, sourceEngineWithoutIdentity, *copiedEngine)+ assert.NotSame(t, sourceDatabase.Mysql.Database, copiedEngine.Database)+}++func Test_CopyForNewDatabase_WhenTheSourceIsMariadb_KeepsEveryConfiguredField(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMariadb)++ copiedEngine := sourceDatabase.CopyForNewDatabase().Mariadb+ require.NotNil(t, copiedEngine)++ sourceEngineWithoutIdentity := *sourceDatabase.Mariadb+ sourceEngineWithoutIdentity.ID = uuid.Nil+ sourceEngineWithoutIdentity.DatabaseID = nil++ assert.Equal(t, sourceEngineWithoutIdentity, *copiedEngine)+ assert.NotSame(t, sourceDatabase.Mariadb.Database, copiedEngine.Database)+}++func Test_CopyForNewDatabase_WhenTheSourceIsMongodb_KeepsEveryConfiguredField(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMongodb)++ copiedEngine := sourceDatabase.CopyForNewDatabase().Mongodb+ require.NotNil(t, copiedEngine)++ sourceEngineWithoutIdentity := *sourceDatabase.Mongodb+ sourceEngineWithoutIdentity.ID = uuid.Nil+ sourceEngineWithoutIdentity.DatabaseID = nil++ assert.Equal(t, sourceEngineWithoutIdentity, *copiedEngine)+}++func Test_CopyForNewDatabase_WhenTheSourceIsMongodb_GivesTheCopyItsOwnPortPointer(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMongodb)++ copiedEngine := sourceDatabase.CopyForNewDatabase().Mongodb+ require.NotNil(t, copiedEngine)++ *copiedEngine.Port = 27018++ assert.Equal(t, 27017, *sourceDatabase.Mongodb.Port)+}++func Test_CopyForNewDatabase_WhenTheMongodbSourceUsesSrv_KeepsTheSrvFlag(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMongodb)+ // SRV and a tunnel are mutually exclusive, so the flag can only be exercised untunneled.+ sourceDatabase.Mongodb.SshTunnel = sshtunnel.Config{}+ sourceDatabase.Mongodb.IsSrv = true+ sourceDatabase.Mongodb.Port = nil++ copiedEngine := sourceDatabase.CopyForNewDatabase().Mongodb+ require.NotNil(t, copiedEngine)++ assert.True(t, copiedEngine.IsSrv)+ assert.Nil(t, copiedEngine.Port)+}++// The inverse of the other engines: inheriting the slot name would leave two databases driving one+// replication slot on the source cluster, and BeforeCreate only mints a new one when it is empty.+func Test_CopyForNewDatabase_WhenTheSourceIsPostgresqlPhysical_DoesNotInheritServerManagedState(+ t *testing.T,+) {+ sourceDatabase := filledSourceDatabase(DatabaseTypePostgresPhysical)++ copiedEngine := sourceDatabase.CopyForNewDatabase().PostgresqlPhysical+ require.NotNil(t, copiedEngine)++ assert.Empty(t, copiedEngine.ReplicationSlotName)+ assert.Nil(t, copiedEngine.SystemIdentifier)+ assert.Nil(t, copiedEngine.WalSegmentSizeBytes)++ sourceEngineWithoutIdentity := *sourceDatabase.PostgresqlPhysical+ sourceEngineWithoutIdentity.ID = uuid.Nil+ sourceEngineWithoutIdentity.DatabaseID = nil+ sourceEngineWithoutIdentity.ReplicationSlotName = ""+ sourceEngineWithoutIdentity.SystemIdentifier = nil+ sourceEngineWithoutIdentity.WalSegmentSizeBytes = nil++ assert.Equal(t, sourceEngineWithoutIdentity, *copiedEngine)+ assert.Equal(t, "databasus_slot_deadbeef", sourceDatabase.PostgresqlPhysical.ReplicationSlotName)+}++func Test_CopyForNewDatabase_DropsIdentityAndBackupHistory(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMysql)++ copiedDatabase := sourceDatabase.CopyForNewDatabase()++ assert.Equal(t, uuid.Nil, copiedDatabase.ID)+ assert.Nil(t, copiedDatabase.LastBackupTime)+ assert.Nil(t, copiedDatabase.LastBackupErrorMessage)+ assert.Equal(t, sourceDatabase.WorkspaceID, copiedDatabase.WorkspaceID)+ assert.Equal(t, *sourceDatabase.HealthStatus, *copiedDatabase.HealthStatus)+ assert.NotSame(t, sourceDatabase.HealthStatus, copiedDatabase.HealthStatus)+}++// The only many2many on Database: a copy that lost its notifiers would back up in silence.+func Test_CopyForNewDatabase_WhenTheSourceHasNotifiers_CopiesThemIntoItsOwnSlice(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMysql)+ require.NotEmpty(t, sourceDatabase.Notifiers)++ copiedDatabase := sourceDatabase.CopyForNewDatabase()++ assert.Equal(t, sourceDatabase.Notifiers, copiedDatabase.Notifiers)+ assert.NotSame(t, &sourceDatabase.Notifiers[0], &copiedDatabase.Notifiers[0])+}++// A shallow copy of Database carries all five engine pointers, and a copy that answers to two+// engines at once would confuse every type switch downstream.+func Test_CopyForNewDatabase_WhenTheSourceCarriesAStaleEngineConfig_KeepsOnlyTheMatchingOne(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypeMysql)+ sourceDatabase.Mongodb = filledSourceDatabase(DatabaseTypeMongodb).Mongodb++ copiedDatabase := sourceDatabase.CopyForNewDatabase()++ assert.NotNil(t, copiedDatabase.Mysql)+ assert.Nil(t, copiedDatabase.Mongodb)+ assert.Nil(t, copiedDatabase.PostgresqlLogical)+ assert.Nil(t, copiedDatabase.PostgresqlPhysical)+ assert.Nil(t, copiedDatabase.Mariadb)+}diff --git a/backend/internal/features/databases/service.go b/backend/internal/features/databases/service.goindex ccbf4900..045383bb 100644--- a/backend/internal/features/databases/service.go+++ b/backend/internal/features/databases/service.go@@ -13,11 +13,6 @@ import (audit_logs "databasus-backend/internal/features/audit_logs"physical_core_service "databasus-backend/internal/features/backups/backups/core/physical/service"- "databasus-backend/internal/features/databases/databases/mariadb"- "databasus-backend/internal/features/databases/databases/mongodb"- "databasus-backend/internal/features/databases/databases/mysql"- postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"- 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"@@ -87,14 +82,34 @@ func (s *DatabaseService) CreateDatabase(return nil, err}- if err := database.PopulateDbData(s.logger, s.fieldEncryptor); err != nil {+ // The database has no ID until it is saved, so the workspace is all there is to correlate on.+ logger := s.logger.With("workspace_id", workspaceID)++ tunneledDatabase, err := OpenTunnel(context.Background(), OpenTunnelSpec{+ Database: database,+ Logger: logger,+ Encryptor: s.fieldEncryptor,+ })+ if err != nil {+ return nil, err+ }++ defer tunneledDatabase.Close()++ // Never reassign database here: the original is what gets encrypted and saved below, and the+ // copy carries a loopback address, an ephemeral port and a disabled tunnel.+ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()++ if err := databaseThroughTunnel.PopulateDbData(logger, s.fieldEncryptor); err != nil {return nil, fmt.Errorf("failed to auto-detect database data: %w", err)}- if err := database.TestConnection(s.logger, s.fieldEncryptor); err != nil {+ if err := databaseThroughTunnel.TestConnection(logger, s.fieldEncryptor); err != nil {return nil, err}+ tunneledDatabase.CopyDiscoveredMetadataToOriginal()+if err := database.EncryptSensitiveFields(s.fieldEncryptor); err != nil {return nil, fmt.Errorf("failed to encrypt sensitive fields: %w", err)}@@ -158,14 +173,32 @@ func (s *DatabaseService) UpdateDatabase(return err}- if err := existingDatabase.PopulateDbData(s.logger, s.fieldEncryptor); err != nil {+ logger := s.logger.With("database_id", existingDatabase.ID)++ tunneledDatabase, err := OpenTunnel(context.Background(), OpenTunnelSpec{+ Database: existingDatabase,+ Logger: logger,+ Encryptor: s.fieldEncryptor,+ })+ if err != nil {+ return err+ }++ defer tunneledDatabase.Close()++ // Never reassign existingDatabase here: it is what gets encrypted and saved below.+ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()++ if err := databaseThroughTunnel.PopulateDbData(logger, s.fieldEncryptor); err != nil {return fmt.Errorf("failed to auto-detect database data: %w", err)}- if err := existingDatabase.TestConnection(s.logger, s.fieldEncryptor); err != nil {+ if err := databaseThroughTunnel.TestConnection(logger, s.fieldEncryptor); err != nil {return err}+ tunneledDatabase.CopyDiscoveredMetadataToOriginal()+oldName := existingDatabase.Nameif err := existingDatabase.EncryptSensitiveFields(s.fieldEncryptor); err != nil {@@ -386,13 +419,25 @@ func (s *DatabaseService) TestDatabaseConnection(return errors.New("insufficient permissions to test connection for this database")}- err = database.TestConnection(s.logger, s.fieldEncryptor)+ logger := s.logger.With("database_id", database.ID)++ tunneledDatabase, err := OpenTunnel(context.Background(), OpenTunnelSpec{+ Database: database,+ Logger: logger,+ Encryptor: s.fieldEncryptor,+ })if err != nil {- lastSaveError := err.Error()- database.LastBackupErrorMessage = &lastSaveErrorreturn err}+ defer tunneledDatabase.Close()++ if err := tunneledDatabase.GetDatabaseThroughTunnel().TestConnection(logger, s.fieldEncryptor); err != nil {+ return err+ }++ tunneledDatabase.CopyDiscoveredMetadataToOriginal()+database.LastBackupErrorMessage = nil_, err = s.dbRepository.Save(database)@@ -411,7 +456,20 @@ func (s *DatabaseService) TestDatabaseConnectionDirect(return err}- return usingDatabase.TestConnection(s.logger, s.fieldEncryptor)+ logger := s.logger.With("database_id", usingDatabase.ID)++ tunneledDatabase, err := OpenTunnel(context.Background(), OpenTunnelSpec{+ Database: usingDatabase,+ Logger: logger,+ Encryptor: s.fieldEncryptor,+ })+ if err != nil {+ return err+ }++ defer tunneledDatabase.Close()++ return tunneledDatabase.GetDatabaseThroughTunnel().TestConnection(logger, s.fieldEncryptor)}func (s *DatabaseService) GetDatabaseByID(@@ -476,99 +534,8 @@ func (s *DatabaseService) CopyDatabase(return nil, errors.New("insufficient permissions to copy this database")}- newDatabase := &Database{- ID: uuid.Nil,- WorkspaceID: existingDatabase.WorkspaceID,- Name: existingDatabase.Name + " (Copy)",- Type: existingDatabase.Type,- Notifiers: existingDatabase.Notifiers,- LastBackupTime: nil,- LastBackupErrorMessage: nil,- HealthStatus: existingDatabase.HealthStatus,- }-- switch existingDatabase.Type {- case DatabaseTypePostgresLogical:- if existingDatabase.PostgresqlLogical != nil {- newDatabase.PostgresqlLogical = &postgresql_logical.PostgresqlLogicalDatabase{- ID: uuid.Nil,- DatabaseID: nil,- Version: existingDatabase.PostgresqlLogical.Version,- Host: existingDatabase.PostgresqlLogical.Host,- Port: existingDatabase.PostgresqlLogical.Port,- Username: existingDatabase.PostgresqlLogical.Username,- Password: existingDatabase.PostgresqlLogical.Password,- Database: existingDatabase.PostgresqlLogical.Database,- SslMode: existingDatabase.PostgresqlLogical.SslMode,- SslClientCert: existingDatabase.PostgresqlLogical.SslClientCert,- SslClientKey: existingDatabase.PostgresqlLogical.SslClientKey,- SslRootCert: existingDatabase.PostgresqlLogical.SslRootCert,- IncludeSchemas: existingDatabase.PostgresqlLogical.IncludeSchemas,- CpuCount: existingDatabase.PostgresqlLogical.CpuCount,- }- }- case DatabaseTypePostgresPhysical:- if existingDatabase.PostgresqlPhysical != nil {- newDatabase.PostgresqlPhysical = &postgresql_physical.PostgresqlPhysicalDatabase{- ID: uuid.Nil,- DatabaseID: nil,- Version: existingDatabase.PostgresqlPhysical.Version,- BackupType: existingDatabase.PostgresqlPhysical.BackupType,- Host: existingDatabase.PostgresqlPhysical.Host,- Port: existingDatabase.PostgresqlPhysical.Port,- Username: existingDatabase.PostgresqlPhysical.Username,- Password: existingDatabase.PostgresqlPhysical.Password,- SslMode: existingDatabase.PostgresqlPhysical.SslMode,- SslClientCert: existingDatabase.PostgresqlPhysical.SslClientCert,- SslClientKey: existingDatabase.PostgresqlPhysical.SslClientKey,- SslRootCert: existingDatabase.PostgresqlPhysical.SslRootCert,- }- }- case DatabaseTypeMysql:- if existingDatabase.Mysql != nil {- newDatabase.Mysql = &mysql.MysqlDatabase{- ID: uuid.Nil,- DatabaseID: nil,- Version: existingDatabase.Mysql.Version,- Host: existingDatabase.Mysql.Host,- Port: existingDatabase.Mysql.Port,- Username: existingDatabase.Mysql.Username,- Password: existingDatabase.Mysql.Password,- Database: existingDatabase.Mysql.Database,- IsHttps: existingDatabase.Mysql.IsHttps,- }- }- case DatabaseTypeMariadb:- if existingDatabase.Mariadb != nil {- newDatabase.Mariadb = &mariadb.MariadbDatabase{- ID: uuid.Nil,- DatabaseID: nil,- Version: existingDatabase.Mariadb.Version,- Host: existingDatabase.Mariadb.Host,- Port: existingDatabase.Mariadb.Port,- Username: existingDatabase.Mariadb.Username,- Password: existingDatabase.Mariadb.Password,- Database: existingDatabase.Mariadb.Database,- IsHttps: existingDatabase.Mariadb.IsHttps,- }- }- case DatabaseTypeMongodb:- if existingDatabase.Mongodb != nil {- newDatabase.Mongodb = &mongodb.MongodbDatabase{- ID: uuid.Nil,- DatabaseID: nil,- Version: existingDatabase.Mongodb.Version,- Host: existingDatabase.Mongodb.Host,- Port: existingDatabase.Mongodb.Port,- Username: existingDatabase.Mongodb.Username,- Password: existingDatabase.Mongodb.Password,- Database: existingDatabase.Mongodb.Database,- AuthDatabase: existingDatabase.Mongodb.AuthDatabase,- IsHttps: existingDatabase.Mongodb.IsHttps,- CpuCount: existingDatabase.Mongodb.CpuCount,- }- }- }+ newDatabase := existingDatabase.CopyForNewDatabase()+ newDatabase.Name = existingDatabase.Name + " (Copy)"if err := newDatabase.Validate(); err != nil {return nil, err@@ -740,7 +707,20 @@ func (s *DatabaseService) IsUserReadOnly(ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)defer cancel()- return usingDatabase.IsUserReadOnly(ctx, s.logger, s.fieldEncryptor)+ logger := s.logger.With("database_id", usingDatabase.ID)++ tunneledDatabase, err := OpenTunnel(ctx, OpenTunnelSpec{+ Database: usingDatabase,+ Logger: logger,+ Encryptor: s.fieldEncryptor,+ })+ if err != nil {+ return false, nil, err+ }++ defer tunneledDatabase.Close()++ return tunneledDatabase.GetDatabaseThroughTunnel().IsUserReadOnly(ctx, logger, s.fieldEncryptor)}func (s *DatabaseService) CreateReadOnlyUser(@@ -795,25 +775,39 @@ func (s *DatabaseService) CreateReadOnlyUser(ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()+ logger := s.logger.With("database_id", usingDatabase.ID)++ tunneledDatabase, err := OpenTunnel(ctx, OpenTunnelSpec{+ Database: usingDatabase,+ Logger: logger,+ Encryptor: s.fieldEncryptor,+ })+ if err != nil {+ return "", "", err+ }++ defer tunneledDatabase.Close()++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()+var username, password string- var err errorswitch usingDatabase.Type {case DatabaseTypePostgresLogical:- username, password, err = usingDatabase.PostgresqlLogical.CreateReadOnlyUser(- ctx, s.logger, s.fieldEncryptor,+ username, password, err = databaseThroughTunnel.PostgresqlLogical.CreateReadOnlyUser(+ ctx, logger, s.fieldEncryptor,)case DatabaseTypeMysql:- username, password, err = usingDatabase.Mysql.CreateReadOnlyUser(- ctx, s.logger, s.fieldEncryptor,+ username, password, err = databaseThroughTunnel.Mysql.CreateReadOnlyUser(+ ctx, logger, s.fieldEncryptor,)case DatabaseTypeMariadb:- username, password, err = usingDatabase.Mariadb.CreateReadOnlyUser(- ctx, s.logger, s.fieldEncryptor,+ username, password, err = databaseThroughTunnel.Mariadb.CreateReadOnlyUser(+ ctx, logger, s.fieldEncryptor,)case DatabaseTypeMongodb:- username, password, err = usingDatabase.Mongodb.CreateReadOnlyUser(- ctx, s.logger, s.fieldEncryptor,+ username, password, err = databaseThroughTunnel.Mongodb.CreateReadOnlyUser(+ ctx, logger, s.fieldEncryptor,)default:return "", "", errors.New("read-only user creation not supported for this database type")diff --git a/backend/internal/features/databases/testing.go b/backend/internal/features/databases/testing.goindex 684a4eb2..44afd99d 100644--- a/backend/internal/features/databases/testing.go+++ b/backend/internal/features/databases/testing.go@@ -12,6 +12,7 @@ import ("databasus-backend/internal/config""databasus-backend/internal/features/databases/databases/mariadb""databasus-backend/internal/features/databases/databases/mongodb"+ "databasus-backend/internal/features/databases/databases/mysql"postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared"@@ -218,6 +219,20 @@ func GetTestMariadbConfig(host string, port int) *mariadb.MariadbDatabase {}}+// The caller owns the container lifecycle (host/port come from a testcontainers endpoint),+// which keeps this file free of the testcontainers dependency.+func GetTestMysqlConfig(host string, port int) *mysql.MysqlDatabase {+ testDbName := "testdb"+ return &mysql.MysqlDatabase{+ Version: tools.MysqlVersion80,+ Host: host,+ Port: port,+ Username: "testuser",+ Password: "testpassword",+ Database: &testDbName,+ }+}+// GetTestMongodbConfig builds a Mongo 7.0 database config pointing at host:port. The// caller owns the container lifecycle (host/port come from a testcontainers endpoint),// keeping this file free of the testcontainers dependency.diff --git a/backend/internal/features/databases/tunneled_database.go b/backend/internal/features/databases/tunneled_database.gonew file mode 100644index 00000000..381497fc--- /dev/null+++ b/backend/internal/features/databases/tunneled_database.go@@ -0,0 +1,170 @@+package databases++import (+ "context"+ "log/slog"++ "databasus-backend/internal/features/databases/databases/mariadb"+ "databasus-backend/internal/features/databases/databases/mongodb"+ "databasus-backend/internal/features/databases/databases/mysql"+ postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"+ "databasus-backend/internal/util/encryption"+)++type OpenTunnelSpec struct {+ Database *Database+ Logger *slog.Logger+ Encryptor encryption.FieldEncryptor+}++// GetDatabaseThroughTunnel is deliberately absent: every engine hands back its own model type, and+// the swap happens inside the type switch anyway.+type engineTunnel interface {+ CopyDiscoveredMetadataToOriginal()+ Close()+}++type TunneledDatabase struct {+ databaseThroughTunnel *Database+ tunneledEngine engineTunnel+}++// Ctx bounds opening the tunnel; the forwarder then lives until Close.+func OpenTunnel(ctx context.Context, spec OpenTunnelSpec) (*TunneledDatabase, error) {+ if spec.Database == nil {+ return &TunneledDatabase{}, nil+ }++ // The copy carries the forwarded port and a disabled tunnel, so it must never reach Save.+ databaseThroughTunnel := *spec.Database++ tunneledDatabase := &TunneledDatabase{databaseThroughTunnel: &databaseThroughTunnel}++ var err error++ switch spec.Database.Type {+ case DatabaseTypePostgresLogical:+ err = tunneledDatabase.openPostgresqlLogicalTunnel(ctx, spec)+ case DatabaseTypeMysql:+ err = tunneledDatabase.openMysqlTunnel(ctx, spec)+ case DatabaseTypeMariadb:+ err = tunneledDatabase.openMariadbTunnel(ctx, spec)+ case DatabaseTypeMongodb:+ err = tunneledDatabase.openMongodbTunnel(ctx, spec)+ }++ if err != nil {+ return nil, err+ }++ if tunneledDatabase.tunneledEngine == nil {+ tunneledDatabase.databaseThroughTunnel = spec.Database+ }++ return tunneledDatabase, nil+}++func (t *TunneledDatabase) GetDatabaseThroughTunnel() *Database {+ if t == nil {+ return nil+ }++ return t.databaseThroughTunnel+}++func (t *TunneledDatabase) CopyDiscoveredMetadataToOriginal() {+ if t == nil || t.tunneledEngine == nil {+ return+ }++ t.tunneledEngine.CopyDiscoveredMetadataToOriginal()+}++func (t *TunneledDatabase) Close() {+ if t == nil || t.tunneledEngine == nil {+ return+ }++ t.tunneledEngine.Close()+}++// A nil tunneledEngine is what makes OpenTunnel hand back spec.Database rather than the copy.+func (t *TunneledDatabase) openPostgresqlLogicalTunnel(ctx context.Context, spec OpenTunnelSpec) error {+ if spec.Database.PostgresqlLogical == nil || !spec.Database.PostgresqlLogical.SshTunnel.IsEnabled {+ return nil+ }++ tunneledEngine, err := postgresql_logical.OpenTunnel(ctx, postgresql_logical.OpenTunnelSpec{+ Database: spec.Database.PostgresqlLogical,+ Logger: spec.Logger,+ Encryptor: spec.Encryptor,+ })+ if err != nil {+ return err+ }++ t.tunneledEngine = tunneledEngine+ t.databaseThroughTunnel.PostgresqlLogical = tunneledEngine.GetDatabaseThroughTunnel()++ return nil+}++func (t *TunneledDatabase) openMysqlTunnel(ctx context.Context, spec OpenTunnelSpec) error {+ if spec.Database.Mysql == nil || !spec.Database.Mysql.SshTunnel.IsEnabled {+ return nil+ }++ tunneledEngine, err := mysql.OpenTunnel(ctx, mysql.OpenTunnelSpec{+ Database: spec.Database.Mysql,+ Logger: spec.Logger,+ Encryptor: spec.Encryptor,+ })+ if err != nil {+ return err+ }++ t.tunneledEngine = tunneledEngine+ t.databaseThroughTunnel.Mysql = tunneledEngine.GetDatabaseThroughTunnel()++ return nil+}++func (t *TunneledDatabase) openMariadbTunnel(ctx context.Context, spec OpenTunnelSpec) error {+ if spec.Database.Mariadb == nil || !spec.Database.Mariadb.SshTunnel.IsEnabled {+ return nil+ }++ tunneledEngine, err := mariadb.OpenTunnel(ctx, mariadb.OpenTunnelSpec{+ Database: spec.Database.Mariadb,+ Logger: spec.Logger,+ Encryptor: spec.Encryptor,+ })+ if err != nil {+ return err+ }++ t.tunneledEngine = tunneledEngine+ t.databaseThroughTunnel.Mariadb = tunneledEngine.GetDatabaseThroughTunnel()++ return nil+}++func (t *TunneledDatabase) openMongodbTunnel(ctx context.Context, spec OpenTunnelSpec) error {+ if spec.Database.Mongodb == nil || !spec.Database.Mongodb.SshTunnel.IsEnabled {+ return nil+ }++ tunneledEngine, err := mongodb.OpenTunnel(ctx, mongodb.OpenTunnelSpec{+ Database: spec.Database.Mongodb,+ Logger: spec.Logger,+ Encryptor: spec.Encryptor,+ })+ if err != nil {+ return err+ }++ t.tunneledEngine = tunneledEngine+ t.databaseThroughTunnel.Mongodb = tunneledEngine.GetDatabaseThroughTunnel()++ return nil+}diff --git a/backend/internal/features/databases/tunneled_database_test.go b/backend/internal/features/databases/tunneled_database_test.gonew file mode 100644index 00000000..5db3e8db--- /dev/null+++ b/backend/internal/features/databases/tunneled_database_test.go@@ -0,0 +1,35 @@+package databases++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/databases/databases/mysql"+)++// Close and CopyDiscoveredMetadataToOriginal delegate through an interface, and a passthrough leaves+// it nil rather than holding a nil-safe pointer, so the guard is the only thing between a disabled+// tunnel and a panic on every deferred Close.+func Test_CloseTunneledDatabase_WhenTheTunnelIsDisabled_DoesNotPanic(t *testing.T) {+ database := &Database{+ Type: DatabaseTypeMysql,+ Mysql: &mysql.MysqlDatabase{Host: "db.internal", Port: 3306},+ }++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ assert.NotPanics(t, tunneledDatabase.Close)+ assert.NotPanics(t, tunneledDatabase.CopyDiscoveredMetadataToOriginal)+ assert.Same(t, database, tunneledDatabase.GetDatabaseThroughTunnel())+}++func Test_CloseTunneledDatabase_WhenTheDatabaseIsNil_DoesNotPanic(t *testing.T) {+ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{})+ require.NoError(t, err)++ assert.NotPanics(t, tunneledDatabase.Close)+ assert.Nil(t, tunneledDatabase.GetDatabaseThroughTunnel())+}diff --git a/backend/internal/features/restores/restoring/restorer.go b/backend/internal/features/restores/restoring/restorer.goindex 8ff934d4..2bec6976 100644--- a/backend/internal/features/restores/restoring/restorer.go+++ b/backend/internal/features/restores/restoring/restorer.go@@ -116,14 +116,40 @@ func (r *Restorer) MakeRestore(restoreID uuid.UUID) {Mongodb: dbCache.MongodbDatabase,}- if err := restoringToDB.PopulateDbData(r.logger, r.fieldEncryptor); err != nil {+ // The restore target is the only endpoint this function connects to, so one tunnel covers+ // version detection, the TimescaleDB hooks and pg_restore itself.+ logger := r.logger.With("restore_id", restore.ID)++ tunneledDatabase, err := databases.OpenTunnel(ctx, databases.OpenTunnelSpec{+ Database: restoringToDB,+ Logger: logger,+ Encryptor: r.fieldEncryptor,+ })+ if err != nil {+ errMsg := fmt.Sprintf("failed to open the SSH tunnel to the restore target: %v", err)+ restore.FailMessage = &errMsg+ restore.Status = restores_core.RestoreStatusFailed+ restore.RestoreDurationMs = time.Since(start).Milliseconds()++ if err := r.restoreRepository.Save(restore); err != nil {+ logger.Error("failed to save restore", "error", err)+ }++ return+ }++ defer tunneledDatabase.Close()++ restoringToDBThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()++ if err := restoringToDBThroughTunnel.PopulateDbData(logger, r.fieldEncryptor); err != nil {errMsg := fmt.Sprintf("failed to auto-detect database data: %v", err)restore.FailMessage = &errMsgrestore.Status = restores_core.RestoreStatusFailedrestore.RestoreDurationMs = time.Since(start).Milliseconds()if err := r.restoreRepository.Save(restore); err != nil {- r.logger.Error("Failed to save restore", "error", err)+ logger.Error("failed to save restore", "error", err)}return@@ -144,7 +170,7 @@ func (r *Restorer) MakeRestore(restoreID uuid.UUID) {backupConfig,*restore,database,- restoringToDB,+ restoringToDBThroughTunnel,backup,storage,restoreOptions,@@ -191,7 +217,7 @@ func (r *Restorer) MakeRestore(restoreID uuid.UUID) {restore.RestoreDurationMs = time.Since(start).Milliseconds()if err := r.restoreRepository.Save(restore); err != nil {- r.logger.Error("Failed to save restore", "error", err)+ logger.Error("failed to save restore", "error", err)}return@@ -201,7 +227,7 @@ func (r *Restorer) MakeRestore(restoreID uuid.UUID) {restore.RestoreDurationMs = time.Since(start).Milliseconds()if err := r.restoreRepository.Save(restore); err != nil {- r.logger.Error("Failed to save restore", "error", err)+ logger.Error("failed to save restore", "error", err)return}diff --git a/backend/internal/features/restores/service.go b/backend/internal/features/restores/service.goindex 38213def..0c3bdc16 100644--- a/backend/internal/features/restores/service.go+++ b/backend/internal/features/restores/service.go@@ -1,6 +1,7 @@package restoresimport (+ "context""errors""fmt""log/slog"@@ -128,6 +129,10 @@ func (s *RestoreService) RestoreBackupWithAuth(return err}+ if err := s.populateRestoreTargetVersionThroughTunnel(backupDatabase, requestDTO); err != nil {+ return err+ }+if err := s.validateVersionCompatibility(backupDatabase, requestDTO); err != nil {return err}@@ -243,44 +248,6 @@ func (s *RestoreService) validateVersionCompatibility(backupDatabase *databases.Database,requestDTO restores_core.RestoreBackupRequest,) error {- // populate version- if requestDTO.MariadbDatabase != nil {- err := requestDTO.MariadbDatabase.PopulateVersion(- s.logger,- s.fieldEncryptor,- )- if err != nil {- return err- }- }- if requestDTO.MysqlDatabase != nil {- err := requestDTO.MysqlDatabase.PopulateVersion(- s.logger,- s.fieldEncryptor,- )- if err != nil {- return err- }- }- if requestDTO.PostgresqlLogicalDatabase != nil {- err := requestDTO.PostgresqlLogicalDatabase.PopulateVersion(- s.logger,- s.fieldEncryptor,- )- if err != nil {- return err- }- }- if requestDTO.MongodbDatabase != nil {- err := requestDTO.MongodbDatabase.PopulateVersion(- s.logger,- s.fieldEncryptor,- )- if err != nil {- return err- }- }-switch backupDatabase.Type {case databases.DatabaseTypePostgresLogical:if requestDTO.PostgresqlLogicalDatabase == nil {@@ -335,6 +302,43 @@ func (s *RestoreService) validateVersionCompatibility(return nil}+// The restore target arrives as bare engine models in the request DTO, so it is assembled into the+// Database the generic tunnel dispatcher works from, the same way the restorer itself does.+func (s *RestoreService) populateRestoreTargetVersionThroughTunnel(+ backupDatabase *databases.Database,+ requestDTO restores_core.RestoreBackupRequest,+) error {+ restoreTarget := &databases.Database{+ Type: backupDatabase.Type,+ PostgresqlLogical: requestDTO.PostgresqlLogicalDatabase,+ Mysql: requestDTO.MysqlDatabase,+ Mariadb: requestDTO.MariadbDatabase,+ Mongodb: requestDTO.MongodbDatabase,+ }++ tunneledDatabase, err := databases.OpenTunnel(context.Background(), databases.OpenTunnelSpec{+ Database: restoreTarget,+ Logger: s.logger,+ Encryptor: s.fieldEncryptor,+ })+ if err != nil {+ return err+ }++ defer tunneledDatabase.Close()++ if err := tunneledDatabase.GetDatabaseThroughTunnel().PopulateVersion(+ s.logger,+ s.fieldEncryptor,+ ); err != nil {+ return err+ }++ tunneledDatabase.CopyDiscoveredMetadataToOriginal()++ return nil+}+func (s *RestoreService) validateDiskSpace(backup *backups_core_logical.LogicalBackup,requestDTO restores_core.RestoreBackupRequest,diff --git a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.goindex e6db5f46..6d93c589 100644--- a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go+++ b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go@@ -751,7 +751,6 @@ func (uc *RestorePostgresqlBackupUsecase) executePgRestore(return nil}-// setupPgRestoreEnvironment configures environment variables for pg_restorefunc (uc *RestorePostgresqlBackupUsecase) setupPgRestoreEnvironment(cmd *exec.Cmd,credentials *postgresql_shared.CredentialTempFiles,@@ -760,6 +759,7 @@ func (uc *RestorePostgresqlBackupUsecase) setupPgRestoreEnvironment(cmd.Env = os.Environ()cmd.Env = append(cmd.Env, "PGPASSFILE="+credentials.PgpassPath)+ cmd.Env = append(cmd.Env, postgresql_shared.GetPgHostAddrEnv(pgConfig.CredentialSpec())...)uc.logger.Info("Using temporary .pgpass file for authentication","pgpassFile", credentials.PgpassPath,diff --git a/backend/internal/features/sshtunnel/auth.go b/backend/internal/features/sshtunnel/auth.gonew file mode 100644index 00000000..ef601183--- /dev/null+++ b/backend/internal/features/sshtunnel/auth.go@@ -0,0 +1,75 @@+package sshtunnel++import (+ "errors"+ "fmt"++ "golang.org/x/crypto/ssh"++ "databasus-backend/internal/util/encryption"+)++func buildAuthMethods(config Config, encryptor encryption.FieldEncryptor) ([]ssh.AuthMethod, error) {+ var authMethods []ssh.AuthMethod++ if config.Password != "" {+ password, err := decryptIfNeeded(config.Password, encryptor)+ if err != nil {+ return nil, fmt.Errorf("failed to decrypt the SSH tunnel password: %w", err)+ }++ authMethods = append(authMethods, ssh.Password(password))+ }++ if config.PrivateKey != "" {+ signer, err := buildPrivateKeySigner(config, encryptor)+ if err != nil {+ return nil, err+ }++ authMethods = append(authMethods, ssh.PublicKeys(signer))+ }++ if len(authMethods) == 0 {+ return nil, errors.New("SSH tunnel requires either a password or a private key")+ }++ return authMethods, nil+}++func buildPrivateKeySigner(config Config, encryptor encryption.FieldEncryptor) (ssh.Signer, error) {+ privateKey, err := decryptIfNeeded(config.PrivateKey, encryptor)+ if err != nil {+ return nil, fmt.Errorf("failed to decrypt the SSH tunnel private key: %w", err)+ }++ if config.PrivateKeyPassphrase == "" {+ signer, err := ssh.ParsePrivateKey([]byte(privateKey))+ if err != nil {+ return nil, fmt.Errorf("failed to parse the SSH tunnel private key: %w", err)+ }++ return signer, nil+ }++ passphrase, err := decryptIfNeeded(config.PrivateKeyPassphrase, encryptor)+ if err != nil {+ return nil, fmt.Errorf("failed to decrypt the SSH tunnel private key passphrase: %w", err)+ }++ signer, err := ssh.ParsePrivateKeyWithPassphrase([]byte(privateKey), []byte(passphrase))+ if err != nil {+ return nil, fmt.Errorf("failed to parse the SSH tunnel private key: %w", err)+ }++ return signer, nil+}++// A restore target config is never persisted, so it arrives in plaintext with a nil encryptor.+func decryptIfNeeded(value string, encryptor encryption.FieldEncryptor) (string, error) {+ if encryptor == nil {+ return value, nil+ }++ return encryptor.Decrypt(value)+}diff --git a/backend/internal/features/sshtunnel/doc.go b/backend/internal/features/sshtunnel/doc.gonew file mode 100644index 00000000..feca0f5f--- /dev/null+++ b/backend/internal/features/sshtunnel/doc.go@@ -0,0 +1,6 @@+// Package sshtunnel forwards a local loopback port to a database that is only reachable from+// inside a customer's perimeter, through an SSH bastion.+//+// Callers hand the forwarder's local endpoint to whatever dials the database - a CLI tool's+// -h/-p arguments, a driver DSN - so nothing downstream needs to know a tunnel exists.+package sshtunneldiff --git a/backend/internal/features/sshtunnel/dto.go b/backend/internal/features/sshtunnel/dto.gonew file mode 100644index 00000000..af74a469--- /dev/null+++ b/backend/internal/features/sshtunnel/dto.go@@ -0,0 +1,30 @@+package sshtunnel++import (+ "log/slog"+ "net"+ "strconv"+ "time"++ "databasus-backend/internal/util/encryption"+)++type Endpoint struct {+ Host string+ Port int+}++func (e Endpoint) String() string {+ return net.JoinHostPort(e.Host, strconv.Itoa(e.Port))+}++type OpenSpec struct {+ Config Config+ Target Endpoint+ Encryptor encryption.FieldEncryptor+ Logger *slog.Logger++ // Zero or negative selects defaultHandshakeTimeout. The dialer bounds the TCP connect, but+ // nothing bounds the SSH handshake, so a bastion that accepts and then says nothing needs this.+ HandshakeTimeout time.Duration+}diff --git a/backend/internal/features/sshtunnel/errors.go b/backend/internal/features/sshtunnel/errors.gonew file mode 100644index 00000000..5a807387--- /dev/null+++ b/backend/internal/features/sshtunnel/errors.go@@ -0,0 +1,7 @@+package sshtunnel++import "errors"++// Returned when a connection reaches the forwarder after Close: an expected shutdown race, not a+// tunnel failure, so callers can tell it apart from a bastion that is genuinely unreachable.+var ErrForwarderClosed = errors.New("ssh tunnel forwarder is closed")diff --git a/backend/internal/features/sshtunnel/forwarder.go b/backend/internal/features/sshtunnel/forwarder.gonew file mode 100644index 00000000..d1fbbe78--- /dev/null+++ b/backend/internal/features/sshtunnel/forwarder.go@@ -0,0 +1,337 @@+package sshtunnel++import (+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net"+ "sync"+ "time"++ "golang.org/x/crypto/ssh"++ "databasus-backend/internal/util/logger"+)++const (+ bastionDialTimeout = 30 * time.Second+ defaultHandshakeTimeout = 30 * time.Second+ acceptErrorBackoff = 100 * time.Millisecond+)++// The local port stays fixed for the whole lifetime while the SSH client underneath is+// re-established on demand. The WAL supervisor copies the rewritten host and port once at startup+// and then runs for days, so a listener that moved after a network blip would leave it pointing at+// a dead port.+type Forwarder struct {+ target Endpoint+ localEndpoint Endpoint+ listener net.Listener+ clientConfig *ssh.ClientConfig+ bastionAddress string+ logger *slog.Logger+ handshakeTimeout time.Duration++ waitGroup sync.WaitGroup+ done chan struct{}+ closeOnce sync.Once++ // Cancelled by Close so a redial in flight against an unreachable bastion gives up at once+ // instead of holding clientMutex for the full dial timeout.+ lifetime context.Context+ cancelLifetime context.CancelFunc++ // Seam: a bastion whose TCP connect never completes is the only way to exercise Close+ // cancelling a redial in flight, and no real address does that reliably on every host.+ dialBastionConn func(ctx context.Context, address string) (net.Conn, error)++ clientMutex sync.Mutex+ client *ssh.Client+ isClosed bool+}++// Ctx bounds the first dial only. The forwarder outlives the request that opened it, so redials run+// on its own lifetime instead, and Close is what ends it.+func Open(ctx context.Context, spec OpenSpec) (*Forwarder, error) {+ authMethods, err := buildAuthMethods(spec.Config, spec.Encryptor)+ if err != nil {+ return nil, err+ }++ var listenConfig net.ListenConfig++ listener, err := listenConfig.Listen(ctx, "tcp", "127.0.0.1:0")+ if err != nil {+ return nil, fmt.Errorf("failed to open local SSH tunnel port: %w", err)+ }++ localAddress, isTCPAddress := listener.Addr().(*net.TCPAddr)+ if !isTCPAddress {+ _ = listener.Close()++ return nil, errors.New("failed to resolve the local SSH tunnel port")+ }++ bastionAddress := Endpoint{Host: spec.Config.Host, Port: spec.Config.Port}.String()++ // The accept and keepalive loops log from background goroutines, long after Open returned and+ // with no request scope of their own, so the tunnel they belong to has to be attached here.+ // slog.Default is deliberately not the fallback: nothing calls slog.SetDefault, so it would+ // bypass the multi-handler and those warnings would never reach log aggregation.+ forwarderLogger := spec.Logger+ if forwarderLogger == nil {+ forwarderLogger = logger.GetLogger()+ }++ forwarderLogger = forwarderLogger.With(+ "ssh_tunnel_host", bastionAddress,+ "ssh_tunnel_target", spec.Target.String(),+ )++ handshakeTimeout := spec.HandshakeTimeout+ if handshakeTimeout <= 0 {+ handshakeTimeout = defaultHandshakeTimeout+ }++ lifetime, cancelLifetime := context.WithCancel(context.WithoutCancel(ctx))++ forwarder := &Forwarder{+ target: spec.Target,+ localEndpoint: Endpoint{Host: "127.0.0.1", Port: localAddress.Port},+ listener: listener,+ clientConfig: &ssh.ClientConfig{+ User: spec.Config.Username,+ Auth: authMethods,+ // Accepted risk: the bastion's host key is not pinned, so the credentials are+ // presented to whatever answers its address. Config carries no fingerprint to+ // verify against; this matches the existing SFTP storage backend.+ HostKeyCallback: ssh.InsecureIgnoreHostKey(),+ },+ bastionAddress: bastionAddress,+ logger: forwarderLogger,+ handshakeTimeout: handshakeTimeout,+ done: make(chan struct{}),+ lifetime: lifetime,+ cancelLifetime: cancelLifetime,+ dialBastionConn: dialBastionConnOverTCP,+ }++ if err := forwarder.dialAndCacheBastion(ctx); err != nil {+ cancelLifetime()+ _ = listener.Close()++ return nil, err+ }++ forwarder.waitGroup.Go(forwarder.runAcceptLoop)+ forwarder.waitGroup.Go(forwarder.runKeepalive)++ return forwarder, nil+}++func (f *Forwarder) GetLocalEndpoint() Endpoint {+ return f.localEndpoint+}++func (f *Forwarder) Close() {+ f.closeOnce.Do(func() {+ close(f.done)+ // Before taking clientMutex: a redial holding it aborts only once its context is cancelled.+ f.cancelLifetime()+ _ = f.listener.Close()+ f.markClosedAndCloseClient()+ })++ f.waitGroup.Wait()+}++func (f *Forwarder) runAcceptLoop() {+ for {+ localConn, err := f.listener.Accept()+ if err != nil {+ if errors.Is(err, net.ErrClosed) {+ return+ }++ f.logger.Warn("ssh tunnel failed to accept a local connection", "error", err)++ select {+ case <-f.done:+ return+ case <-time.After(acceptErrorBackoff):+ continue+ }+ }++ f.waitGroup.Go(func() { f.forwardConnection(localConn) })+ }+}++func (f *Forwarder) forwardConnection(localConn net.Conn) {+ targetConn, err := f.dialTarget()+ if err != nil {+ _ = localConn.Close()++ // Losing a connection to a concurrent Close is the expected shutdown race, not a fault.+ if !errors.Is(err, ErrForwarderClosed) {+ f.logger.Warn("ssh tunnel failed to reach the database", "error", err)+ }++ return+ }++ // Both directions close both ends: whichever side finishes first unblocks the other, which+ // would otherwise sit in io.Copy until Close.+ closeBothEnds := func() {+ _ = localConn.Close()+ _ = targetConn.Close()+ }++ var copyGroup sync.WaitGroup++ copyGroup.Go(func() {+ defer closeBothEnds()++ _, _ = io.Copy(targetConn, localConn)+ })++ copyGroup.Go(func() {+ defer closeBothEnds()++ _, _ = io.Copy(localConn, targetConn)+ })++ copyGroup.Wait()+}++// The database client on the other end of the local port will not retry for us, so a session that+// died since the previous connection has to be replaced within this call.+func (f *Forwarder) dialTarget() (net.Conn, error) {+ client, err := f.getOrDialBastion()+ if err != nil {+ return nil, err+ }++ targetConn, err := client.Dial("tcp", f.target.String())+ if err == nil {+ return targetConn, nil+ }++ // A refused or filtered target is the database's problem, not the transport's: the bastion+ // answered. Discarding a healthy session here would re-authenticate on every connection.+ var openChannelError *ssh.OpenChannelError+ if errors.As(err, &openChannelError) {+ return nil, fmt.Errorf("failed to reach the database through the SSH tunnel host: %w", err)+ }++ f.discardClient(client)++ client, err = f.getOrDialBastion()+ if err != nil {+ return nil, err+ }++ targetConn, err = client.Dial("tcp", f.target.String())+ if err != nil {+ return nil, fmt.Errorf("failed to reach the database through the SSH tunnel host: %w", err)+ }++ return targetConn, nil+}++func (f *Forwarder) getOrDialBastion() (*ssh.Client, error) {+ f.clientMutex.Lock()+ defer f.clientMutex.Unlock()++ if f.client != nil {+ return f.client, nil+ }++ ctx, cancel := context.WithTimeout(f.lifetime, bastionDialTimeout)+ defer cancel()++ if err := f.dialAndCacheBastionLocked(ctx); err != nil {+ return nil, err+ }++ return f.client, nil+}++func (f *Forwarder) dialAndCacheBastion(ctx context.Context) error {+ f.clientMutex.Lock()+ defer f.clientMutex.Unlock()++ return f.dialAndCacheBastionLocked(ctx)+}++func (f *Forwarder) dialAndCacheBastionLocked(ctx context.Context) error {+ // A connection accepted just before Close would otherwise open a session that nothing is left+ // to close, and hold Close in its Wait until the remote peer hangs up.+ if f.isClosed {+ return ErrForwarderClosed+ }++ bastionConn, err := f.dialBastionConn(ctx, f.bastionAddress)+ if err != nil {+ return fmt.Errorf("failed to dial the SSH tunnel host: %w", err)+ }++ if err := bastionConn.SetDeadline(time.Now().Add(f.handshakeTimeout)); err != nil {+ _ = bastionConn.Close()++ return fmt.Errorf("failed to bound the SSH tunnel handshake: %w", err)+ }++ sshConn, channels, requests, err := ssh.NewClientConn(bastionConn, f.bastionAddress, f.clientConfig)+ if err != nil {+ _ = bastionConn.Close()++ return fmt.Errorf("failed to authenticate with the SSH tunnel host: %w", err)+ }++ // The deadline bounded the handshake only. Forwarded traffic must not inherit it, or every+ // dump longer than the handshake bound would be cut off mid-stream.+ if err := bastionConn.SetDeadline(time.Time{}); err != nil {+ _ = sshConn.Close()++ return fmt.Errorf("failed to clear the SSH tunnel handshake deadline: %w", err)+ }++ f.client = ssh.NewClient(sshConn, channels, requests)++ return nil+}++func dialBastionConnOverTCP(ctx context.Context, address string) (net.Conn, error) {+ dialer := net.Dialer{Timeout: bastionDialTimeout}++ return dialer.DialContext(ctx, "tcp", address)+}++func (f *Forwarder) discardClient(deadClient *ssh.Client) {+ f.clientMutex.Lock()+ defer f.clientMutex.Unlock()++ if f.client != deadClient {+ return+ }++ _ = f.client.Close()+ f.client = nil+}++func (f *Forwarder) markClosedAndCloseClient() {+ f.clientMutex.Lock()+ defer f.clientMutex.Unlock()++ f.isClosed = true++ if f.client == nil {+ return+ }++ _ = f.client.Close()+ f.client = nil+}diff --git a/backend/internal/features/sshtunnel/forwarder_test.go b/backend/internal/features/sshtunnel/forwarder_test.gonew file mode 100644index 00000000..72ba4ad1--- /dev/null+++ b/backend/internal/features/sshtunnel/forwarder_test.go@@ -0,0 +1,429 @@+package sshtunnel++import (+ "context"+ "fmt"+ "io"+ "net"+ "os"+ "path/filepath"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/testing/containers"+)++// The bastion's sshd also listens on 2222, which is never published to the host, so forwarding+// there proves bytes reach the far side without a second container. Port 22 would be a bad target:+// on a machine that runs its own sshd, a forwarder that dialled the host loopback instead of going+// through the bastion would still read a banner and pass.+const (+ bastionInternalPort = 2222+ sshBannerPrefix = "SSH-2.0-"+)++func startTestBastion(t *testing.T) containers.Endpoint {+ t.Helper()++ return containers.StartSshBastion(t)+}++func readTestKey(t *testing.T, name string) string {+ t.Helper()++ key, err := os.ReadFile(filepath.Join(containers.GetSshBastionTestdataDir(t), name))+ require.NoError(t, err)++ return string(key)+}++func bastionConfig(bastion containers.Endpoint) Config {+ return Config{+ IsEnabled: true,+ Host: bastion.Host,+ Port: bastion.Port,+ Username: containers.SshBastionUsername,+ Password: containers.SshBastionPassword,+ }+}++func openTestForwarder(t *testing.T, config Config) *Forwarder {+ t.Helper()++ forwarder, err := Open(t.Context(), OpenSpec{+ Config: config,+ Target: Endpoint{Host: "127.0.0.1", Port: bastionInternalPort},+ Logger: logger.GetLogger(),+ })+ require.NoError(t, err)++ t.Cleanup(forwarder.Close)++ return forwarder+}++func readBannerThroughTunnel(forwarder *Forwarder) error {+ conn, err := net.DialTimeout("tcp", forwarder.GetLocalEndpoint().String(), 15*time.Second)+ if err != nil {+ return err+ }++ defer conn.Close()++ if err := conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil {+ return err+ }++ banner := make([]byte, len(sshBannerPrefix))+ if _, err := io.ReadFull(conn, banner); err != nil {+ return err+ }++ if string(banner) != sshBannerPrefix {+ return fmt.Errorf("expected %q through the tunnel, got %q", sshBannerPrefix, string(banner))+ }++ return nil+}++func assertTargetReachableThroughTunnel(t *testing.T, forwarder *Forwarder) {+ t.Helper()++ require.NoError(t, readBannerThroughTunnel(forwarder))+}++// Negative control for every other test in this file: it pins that the target port really is+// unreachable without the tunnel. Without it, a forwarder that stopped tunnelling and dialled+// the target directly would keep all the happy-path tests green.+func Test_TargetPort_WithoutTheTunnel_IsUnreachableFromTheHost(t *testing.T) {+ bastion := startTestBastion(t)++ conn, err := net.DialTimeout(+ "tcp",+ Endpoint{Host: bastion.Host, Port: bastionInternalPort}.String(),+ 5*time.Second,+ )+ if err == nil {+ _ = conn.Close()+ }++ require.Error(t, err, "the bastion's internal port must not be published, or the tunnel tests prove nothing")+}++func Test_Forwarder_WithPasswordAuth_ForwardsBytesToTarget(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))++ assertTargetReachableThroughTunnel(t, forwarder)+}++func Test_Forwarder_WithPrivateKeyAuth_ForwardsBytesToTarget(t *testing.T) {+ bastion := startTestBastion(t)++ config := bastionConfig(bastion)+ config.Password = ""+ config.PrivateKey = readTestKey(t, "test_key")++ forwarder := openTestForwarder(t, config)++ assertTargetReachableThroughTunnel(t, forwarder)+}++func Test_Forwarder_WithPassphraseProtectedPrivateKey_ForwardsBytesToTarget(t *testing.T) {+ bastion := startTestBastion(t)++ config := bastionConfig(bastion)+ config.Password = ""+ config.PrivateKey = readTestKey(t, "test_key_passphrase")+ config.PrivateKeyPassphrase = "testpassphrase"++ forwarder := openTestForwarder(t, config)++ assertTargetReachableThroughTunnel(t, forwarder)+}++// Every other test passes a nil encryptor, but a persisted database always has one. Handing the+// ciphertext straight to ssh.Password would leave the whole suite green and the feature dead.+// Split per credential so a break in one decryption path cannot hide behind the other auth method.+func Test_Open_WithEncryptedPassword_DecryptsItBeforeAuthenticating(t *testing.T) {+ bastion := startTestBastion(t)++ encryptor := prefixingEncryptor{}++ config := bastionConfig(bastion)+ require.NoError(t, config.EncryptSensitiveFields(encryptor))+ require.NotEqual(t, containers.SshBastionPassword, config.Password)++ assertTargetReachableThroughTunnel(t, openEncryptedForwarder(t, config, encryptor))+}++func Test_Open_WithEncryptedPrivateKeyAndPassphrase_DecryptsThemBeforeAuthenticating(t *testing.T) {+ bastion := startTestBastion(t)++ encryptor := prefixingEncryptor{}++ config := bastionConfig(bastion)+ config.Password = ""+ config.PrivateKey = readTestKey(t, "test_key_passphrase")+ config.PrivateKeyPassphrase = "testpassphrase"++ require.NoError(t, config.EncryptSensitiveFields(encryptor))+ require.NotEqual(t, "testpassphrase", config.PrivateKeyPassphrase)++ assertTargetReachableThroughTunnel(t, openEncryptedForwarder(t, config, encryptor))+}++func openEncryptedForwarder(t *testing.T, config Config, encryptor prefixingEncryptor) *Forwarder {+ t.Helper()++ forwarder, err := Open(t.Context(), OpenSpec{+ Config: config,+ Target: Endpoint{Host: "127.0.0.1", Port: bastionInternalPort},+ Encryptor: encryptor,+ Logger: logger.GetLogger(),+ })+ require.NoError(t, err)++ t.Cleanup(forwarder.Close)++ return forwarder+}++func Test_Open_WhenPasswordIsWrong_ReturnsErrorWithoutLeakingTheSecret(t *testing.T) {+ bastion := startTestBastion(t)++ config := bastionConfig(bastion)+ config.Password = "definitely-not-the-password"++ forwarder, err := Open(t.Context(), OpenSpec{+ Config: config,+ Target: Endpoint{Host: "127.0.0.1", Port: bastionInternalPort},+ Logger: logger.GetLogger(),+ })++ require.Error(t, err)+ assert.Nil(t, forwarder)+ assert.NotContains(t, err.Error(), config.Password)+}++func Test_Open_WhenPassphraseIsWrong_ReturnsError(t *testing.T) {+ bastion := startTestBastion(t)++ config := bastionConfig(bastion)+ config.Password = ""+ config.PrivateKey = readTestKey(t, "test_key_passphrase")+ config.PrivateKeyPassphrase = "wrong-passphrase"++ forwarder, err := Open(t.Context(), OpenSpec{+ Config: config,+ Target: Endpoint{Host: "127.0.0.1", Port: bastionInternalPort},+ Logger: logger.GetLogger(),+ })++ require.Error(t, err)+ assert.Nil(t, forwarder)+ assert.NotContains(t, err.Error(), config.PrivateKeyPassphrase)+}++func Test_Close_ReleasesTheLocalPort(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))+ localEndpoint := forwarder.GetLocalEndpoint()++ assertTargetReachableThroughTunnel(t, forwarder)++ forwarder.Close()++ conn, err := net.DialTimeout("tcp", localEndpoint.String(), 5*time.Second)+ if err == nil {+ _ = conn.Close()+ }++ assert.Error(t, err)+}++// A connection that got past Accept before Close must not be able to open a fresh bastion session:+// nothing would be left to close it, and Close would sit in its Wait until the far end hung up.+// Driving the guard directly rather than racing Close against live traffic, because the race window+// is far too narrow to hit on purpose - a timing-based test here passes with the guard removed.+func Test_GetOrDialBastion_AfterClose_RefusesToOpenANewSession(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))+ assertTargetReachableThroughTunnel(t, forwarder)++ forwarder.Close()++ client, err := forwarder.getOrDialBastion()++ require.ErrorIs(t, err, ErrForwarderClosed)+ assert.Nil(t, client)++ forwarder.clientMutex.Lock()+ defer forwarder.clientMutex.Unlock()++ assert.Nil(t, forwarder.client, "a session opened after Close would never be closed")+}++// Close cancels the redial context before taking clientMutex. Without that, a redial parked on a+// TCP connect to an unreachable bastion holds the mutex for the full dial timeout, and Close waits+// behind it. Exercised through the dial seam because no real address stalls a connect on every host.+func Test_Close_WhileARedialIsStuckOnConnect_CancelsItInsteadOfWaitingOutTheTimeout(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))++ dialStarted := make(chan struct{})++ var dialStartedOnce sync.Once++ forwarder.dialBastionConn = func(ctx context.Context, _ string) (net.Conn, error) {+ dialStartedOnce.Do(func() { close(dialStarted) })++ <-ctx.Done()++ return nil, ctx.Err()+ }++ forwarder.clientMutex.Lock()+ cachedClient := forwarder.client+ forwarder.clientMutex.Unlock()++ forwarder.discardClient(cachedClient)++ go func() { _, _ = forwarder.getOrDialBastion() }()++ <-dialStarted++ closed := make(chan struct{})++ go func() {+ forwarder.Close()+ close(closed)+ }()++ select {+ case <-closed:+ case <-time.After(bastionDialTimeout / 3):+ t.Fatal("Close waited on the stuck redial instead of cancelling it")+ }+}++// A bastion address that completes the TCP connect and then says nothing is what a blackholing+// middlebox or a wrong port looks like. ssh.ClientConfig.Timeout does not cover the handshake, so+// without an explicit deadline this blocks forever while holding clientMutex, taking Close with it.+func Test_Open_WhenBastionAcceptsButNeverHandshakes_FailsInsteadOfHanging(t *testing.T) {+ silentBastion, err := net.Listen("tcp", "127.0.0.1:0")+ require.NoError(t, err)++ t.Cleanup(func() { _ = silentBastion.Close() })++ go func() {+ for {+ conn, err := silentBastion.Accept()+ if err != nil {+ return+ }++ t.Cleanup(func() { _ = conn.Close() })+ }+ }()++ silentAddress, isTCPAddress := silentBastion.Addr().(*net.TCPAddr)+ require.True(t, isTCPAddress)++ opened := make(chan error, 1)++ go func() {+ forwarder, err := Open(t.Context(), OpenSpec{+ Config: Config{+ IsEnabled: true,+ Host: "127.0.0.1",+ Port: silentAddress.Port,+ Username: containers.SshBastionUsername,+ Password: containers.SshBastionPassword,+ },+ Target: Endpoint{Host: "127.0.0.1", Port: bastionInternalPort},+ Logger: logger.GetLogger(),+ HandshakeTimeout: 2 * time.Second,+ })+ if forwarder != nil {+ forwarder.Close()+ }++ opened <- err+ }()++ select {+ case err := <-opened:+ require.Error(t, err)+ case <-time.After(15 * time.Second):+ t.Fatal("Open blocked on the SSH handshake instead of timing out")+ }+}++func Test_Close_CalledTwice_DoesNotPanic(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))++ forwarder.Close()+ forwarder.Close()+}++// The cached client dies between operations far more often than it dies mid-dial - a bastion+// restart, an idle timeout, a NAT drop. Every waiting connection then discovers the corpse at+// once, so the redial has to be serialized or the losers leak clients and goroutines.+func Test_Forwarder_WhenCachedClientIsDead_ConcurrentConnectionsAllRecover(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))++ assertTargetReachableThroughTunnel(t, forwarder)++ var redialCount atomic.Int32++ dialOverTCP := forwarder.dialBastionConn+ forwarder.dialBastionConn = func(ctx context.Context, address string) (net.Conn, error) {+ redialCount.Add(1)++ return dialOverTCP(ctx, address)+ }++ forwarder.clientMutex.Lock()+ require.NotNil(t, forwarder.client)+ require.NoError(t, forwarder.client.Close())+ forwarder.clientMutex.Unlock()++ const concurrentConnections = 8++ // testify's FailNow only works on the goroutine running the test, so each connection reports+ // back and the assertions happen after the group is joined.+ connectionErrors := make([]error, concurrentConnections)++ var connectionGroup sync.WaitGroup++ for connectionIndex := range concurrentConnections {+ connectionGroup.Go(func() {+ connectionErrors[connectionIndex] = readBannerThroughTunnel(forwarder)+ })+ }++ connectionGroup.Wait()++ for connectionIndex, connectionError := range connectionErrors {+ assert.NoErrorf(t, connectionError, "connection %d failed to recover", connectionIndex)+ }++ // Not exactly one: dialTarget releases clientMutex between discardClient and its retry, so a+ // second waiter can slip in. Unserialized it would be one per connection.+ assert.Less(t, redialCount.Load(), int32(3), "the redial must be serialized, or the losers leak sessions")+}diff --git a/backend/internal/features/sshtunnel/keepalive.go b/backend/internal/features/sshtunnel/keepalive.gonew file mode 100644index 00000000..c61caaf4--- /dev/null+++ b/backend/internal/features/sshtunnel/keepalive.go@@ -0,0 +1,56 @@+package sshtunnel++import (+ "time"++ "golang.org/x/crypto/ssh"+)++const (+ keepaliveInterval = 30 * time.Second+ keepaliveTimeout = 15 * time.Second+)++func (f *Forwarder) runKeepalive() {+ ticker := time.NewTicker(keepaliveInterval)+ defer ticker.Stop()++ for {+ select {+ case <-f.done:+ return+ case <-ticker.C:+ f.clientMutex.Lock()+ client := f.client+ f.clientMutex.Unlock()++ if client == nil {+ continue+ }++ if !isKeepaliveAnswered(client) {+ f.logger.Warn("ssh tunnel keepalive went unanswered, reconnecting on next use")+ f.discardClient(client)+ }+ }+ }+}++// ssh.SendRequest takes no timeout and blocks forever on a connection that died without a FIN -+// the exact failure keepalive exists to detect - so it must never run on a goroutine that Close+// waits for. The orphaned goroutine unblocks once discardClient closes the client.+func isKeepaliveAnswered(client *ssh.Client) bool {+ keepaliveAnswer := make(chan error, 1)++ go func() {+ _, _, err := client.SendRequest("[email protected]", true, nil)+ keepaliveAnswer <- err+ }()++ select {+ case err := <-keepaliveAnswer:+ return err == nil+ case <-time.After(keepaliveTimeout):+ return false+ }+}diff --git a/backend/internal/features/sshtunnel/model.go b/backend/internal/features/sshtunnel/model.gonew file mode 100644index 00000000..1b5ec5bd--- /dev/null+++ b/backend/internal/features/sshtunnel/model.go@@ -0,0 +1,103 @@+package sshtunnel++import (+ "errors"++ "databasus-backend/internal/util/encryption"+)++// Consumers must embed this with gorm:"embedded;embeddedPrefix:ssh_" so each engine table owns its+// own bastion columns; the column names below assume that prefix.+type Config struct {+ IsEnabled bool `json:"isEnabled" gorm:"column:is_enabled;type:boolean;not null;default:false"`+ Host string `json:"host" gorm:"column:host;type:text;not null;default:''"`+ Port int `json:"port" gorm:"column:port;type:integer;not null;default:22"`+ Username string `json:"username" gorm:"column:username;type:text;not null;default:''"`+ Password string `json:"password" gorm:"column:password;type:text;not null;default:''"`+ PrivateKey string `json:"privateKey" gorm:"column:private_key;type:text;not null;default:''"`+ PrivateKeyPassphrase string `json:"privateKeyPassphrase" gorm:"column:private_key_passphrase;type:text;not null;default:''"`+}++func (c *Config) Validate() error {+ if c == nil || !c.IsEnabled {+ return nil+ }++ if c.Host == "" {+ return errors.New("SSH tunnel host is required")+ }++ if c.Port <= 0 || c.Port > 65535 {+ return errors.New("SSH tunnel port must be between 1 and 65535")+ }++ if c.Username == "" {+ return errors.New("SSH tunnel username is required")+ }++ if c.Password == "" && c.PrivateKey == "" {+ return errors.New("SSH tunnel requires either a password or a private key")+ }++ return nil+}++func (c *Config) HideSensitiveData() {+ if c == nil {+ return+ }++ c.Password = ""+ c.PrivateKey = ""+ c.PrivateKeyPassphrase = ""+}++func (c *Config) Update(incomingConfig *Config) {+ if c == nil || incomingConfig == nil {+ return+ }++ c.IsEnabled = incomingConfig.IsEnabled+ c.Host = incomingConfig.Host+ c.Port = incomingConfig.Port+ c.Username = incomingConfig.Username++ // A blank secret means "keep the stored one" - the edit form never receives+ // them back from the API, so overwriting on blank would wipe them.+ if incomingConfig.Password != "" {+ c.Password = incomingConfig.Password+ }++ if incomingConfig.PrivateKey != "" {+ c.PrivateKey = incomingConfig.PrivateKey+ }++ if incomingConfig.PrivateKeyPassphrase != "" {+ c.PrivateKeyPassphrase = incomingConfig.PrivateKeyPassphrase+ }+}++func (c *Config) EncryptSensitiveFields(encryptor encryption.FieldEncryptor) error {+ if c == nil {+ return nil+ }++ for _, field := range []*string{+ &c.Password,+ &c.PrivateKey,+ &c.PrivateKeyPassphrase,+ } {+ if *field == "" {+ continue+ }++ encrypted, err := encryptor.Encrypt(*field)+ if err != nil {+ return err+ }++ *field = encrypted+ }++ return nil+}diff --git a/backend/internal/features/sshtunnel/model_test.go b/backend/internal/features/sshtunnel/model_test.gonew file mode 100644index 00000000..9f0838cd--- /dev/null+++ b/backend/internal/features/sshtunnel/model_test.go@@ -0,0 +1,174 @@+package sshtunnel++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// The real encryptor resolves its key through the secret-key service and a database; these tests+// only cover which fields get walked and which are skipped. It prefixes unconditionally, including+// the empty string, so that dropping the skip-empty guard in EncryptSensitiveFields is visible.+type prefixingEncryptor struct{}++func (prefixingEncryptor) Encrypt(plaintext string) (string, error) {+ return "enc:" + plaintext, nil+}++func (prefixingEncryptor) Decrypt(ciphertext string) (string, error) {+ return strings.TrimPrefix(ciphertext, "enc:"), nil+}++func enabledConfig() Config {+ return Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ }+}++func Test_Validate_WhenTunnelIsDisabled_IgnoresEmptyFields(t *testing.T) {+ config := Config{}++ assert.NoError(t, config.Validate())+}++func Test_Validate_WhenTunnelIsEnabledAndComplete_ReturnsNoError(t *testing.T) {+ config := enabledConfig()++ assert.NoError(t, config.Validate())+}++func Test_Validate_WhenHostIsMissing_ReturnsError(t *testing.T) {+ config := enabledConfig()+ config.Host = ""++ assert.Error(t, config.Validate())+}++func Test_Validate_WhenUsernameIsMissing_ReturnsError(t *testing.T) {+ config := enabledConfig()+ config.Username = ""++ assert.Error(t, config.Validate())+}++func Test_Validate_WhenPortIsOutOfRange_ReturnsError(t *testing.T) {+ for _, port := range []int{0, -1, 65536} {+ config := enabledConfig()+ config.Port = port++ assert.Error(t, config.Validate(), "port %d must be rejected", port)+ }+}++func Test_Validate_WhenNeitherPasswordNorPrivateKeyIsSet_ReturnsError(t *testing.T) {+ config := enabledConfig()+ config.Password = ""+ config.PrivateKey = ""++ assert.Error(t, config.Validate())+}++func Test_Validate_WhenOnlyPrivateKeyIsSet_ReturnsNoError(t *testing.T) {+ config := enabledConfig()+ config.Password = ""+ config.PrivateKey = "-----BEGIN OPENSSH PRIVATE KEY-----"++ assert.NoError(t, config.Validate())+}++func Test_HideSensitiveData_WhenCalled_ClearsSecretsAndKeepsTheRest(t *testing.T) {+ config := enabledConfig()+ config.PrivateKey = "private-key"+ config.PrivateKeyPassphrase = "passphrase"++ config.HideSensitiveData()++ assert.Empty(t, config.Password)+ assert.Empty(t, config.PrivateKey)+ assert.Empty(t, config.PrivateKeyPassphrase)+ assert.Equal(t, "bastion.example.com", config.Host)+ assert.Equal(t, "tunneluser", config.Username)+ assert.True(t, config.IsEnabled)+}++func Test_HideSensitiveData_WhenReceiverIsNil_DoesNotPanic(t *testing.T) {+ var config *Config++ config.HideSensitiveData()+}++// The edit form never receives the stored secrets back, so it submits them blank. Overwriting on+// blank would wipe the bastion credentials on every unrelated edit.+func Test_Update_WithBlankSecrets_KeepsTheStoredOnes(t *testing.T) {+ storedConfig := enabledConfig()+ storedConfig.PrivateKey = "stored-private-key"+ storedConfig.PrivateKeyPassphrase = "stored-passphrase"++ storedConfig.Update(&Config{+ IsEnabled: true,+ Host: "new-bastion.example.com",+ Port: 2222,+ Username: "newuser",+ })++ assert.Equal(t, "tunnelpassword", storedConfig.Password)+ assert.Equal(t, "stored-private-key", storedConfig.PrivateKey)+ assert.Equal(t, "stored-passphrase", storedConfig.PrivateKeyPassphrase)+ assert.Equal(t, "new-bastion.example.com", storedConfig.Host)+ assert.Equal(t, 2222, storedConfig.Port)+ assert.Equal(t, "newuser", storedConfig.Username)+}++func Test_Update_WithNewSecrets_ReplacesTheStoredOnes(t *testing.T) {+ storedConfig := enabledConfig()+ storedConfig.PrivateKey = "stored-private-key"++ incomingConfig := enabledConfig()+ incomingConfig.Password = "new-password"+ incomingConfig.PrivateKey = "new-private-key"+ incomingConfig.PrivateKeyPassphrase = "new-passphrase"++ storedConfig.Update(&incomingConfig)++ assert.Equal(t, "new-password", storedConfig.Password)+ assert.Equal(t, "new-private-key", storedConfig.PrivateKey)+ assert.Equal(t, "new-passphrase", storedConfig.PrivateKeyPassphrase)+}++func Test_Update_WhenTunnelIsDisabledInIncoming_TurnsItOff(t *testing.T) {+ storedConfig := enabledConfig()++ storedConfig.Update(+ &Config{IsEnabled: false, Host: storedConfig.Host, Port: storedConfig.Port, Username: storedConfig.Username},+ )++ assert.False(t, storedConfig.IsEnabled)+ assert.Equal(t, "tunnelpassword", storedConfig.Password)+}++func Test_EncryptSensitiveFields_WhenCalled_EncryptsSecretsAndSkipsEmptyOnes(t *testing.T) {+ encryptor := prefixingEncryptor{}++ config := enabledConfig()+ config.PrivateKey = "private-key"++ require.NoError(t, config.EncryptSensitiveFields(encryptor))++ assert.NotEqual(t, "tunnelpassword", config.Password)+ assert.NotEqual(t, "private-key", config.PrivateKey)+ assert.Empty(t, config.PrivateKeyPassphrase)++ decryptedPassword, err := encryptor.Decrypt(config.Password)+ require.NoError(t, err)+ assert.Equal(t, "tunnelpassword", decryptedPassword)++ decryptedPrivateKey, err := encryptor.Decrypt(config.PrivateKey)+ require.NoError(t, err)+ assert.Equal(t, "private-key", decryptedPrivateKey)+}diff --git a/backend/internal/features/tests/logical/mariadb/sshtunnel_test.go b/backend/internal/features/tests/logical/mariadb/sshtunnel_test.gonew file mode 100644index 00000000..9fdce231--- /dev/null+++ b/backend/internal/features/tests/logical/mariadb/sshtunnel_test.go@@ -0,0 +1,113 @@+package mariadb_logical++import (+ "fmt"+ "net/http"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/jmoiron/sqlx"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/config"+ backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"+ backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical"+ "databasus-backend/internal/features/databases"+ mariadbtypes "databasus-backend/internal/features/databases/databases/mariadb"+ restores_core "databasus-backend/internal/features/restores/core"+ "databasus-backend/internal/features/storages"+ logicaltesting "databasus-backend/internal/features/tests/logical/shared"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ test_utils "databasus-backend/internal/util/testing"+ "databasus-backend/internal/util/testing/containers"+ "databasus-backend/internal/util/tools"+)++const bastionedMariadbImage = "mariadb:11.4"++func bastionedMariadbConfig(+ topology containers.BastionedDatabase,+ databaseName string,+) *mariadbtypes.MariadbDatabase {+ return &mariadbtypes.MariadbDatabase{+ Host: topology.Database.Host,+ Port: topology.Database.Port,+ Username: "root",+ Password: containers.MariadbRootPassword,+ Database: &databaseName,+ Version: tools.MariadbVersion114,+ SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ }+}++func openTestTunnelToMariadb(t *testing.T, topology containers.BastionedDatabase, databaseName string) *sqlx.DB {+ t.Helper()++ localEndpoint := logicaltesting.OpenForwardedEndpoint(t, topology)++ connection, err := sqlx.Connect("mysql", fmt.Sprintf(+ "root:%s@tcp(%s:%d)/%s?parseTime=true",+ containers.MariadbRootPassword, localEndpoint.Host, localEndpoint.Port, databaseName,+ ))+ require.NoError(t, err)+ t.Cleanup(func() { _ = connection.Close() })++ return connection+}++func Test_MariadbBackupRestore_OverSshTunnel_RestoresData(t *testing.T) {+ topology := containers.StartMariadbBehindSshBastion(t, bastionedMariadbImage)+ sourceConnection := openTestTunnelToMariadb(t, topology, containers.MariadbDatabase)++ setupMariadbTestData(t, sourceConnection)++ router := logicaltesting.CreateTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("MariaDB SSH Tunnel Workspace", user, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ storage := storages.CreateTestStorage(workspace.ID)+ t.Cleanup(func() { storages.RemoveTestStorage(storage.ID) })++ database := logicaltesting.SubmitCreateDatabase(t, router, "MariaDB cycle over SSH tunnel",+ databases.Database{+ Name: "Bastioned MariaDB cycle",+ WorkspaceID: &workspace.ID,+ Type: databases.DatabaseTypeMariadb,+ Mariadb: bastionedMariadbConfig(topology, containers.MariadbDatabase),+ }, user.Token)++ t.Cleanup(func() {+ test_utils.MakeDeleteRequest(t, router, "/api/v1/databases/"+database.ID.String(),+ "Bearer "+user.Token, http.StatusNoContent)+ })++ 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)+ require.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)++ t.Cleanup(func() {+ _ = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))+ })++ restoredDatabaseName := "restoreddb_mariadb_ssh_tunnel"+ _, err := sourceConnection.Exec("CREATE DATABASE " + restoredDatabaseName)+ require.NoError(t, err)++ logicaltesting.SubmitRestore(t, router, backup.ID,+ restores_core.RestoreBackupRequest{+ MariadbDatabase: bastionedMariadbConfig(topology, restoredDatabaseName),+ }, user.Token)++ restore := waitForMariadbRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)+ require.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)++ verifyMariadbDataIntegrity(t, sourceConnection, openTestTunnelToMariadb(t, topology, restoredDatabaseName))+}diff --git a/backend/internal/features/tests/logical/mongodb/sshtunnel_test.go b/backend/internal/features/tests/logical/mongodb/sshtunnel_test.gonew file mode 100644index 00000000..514265ad--- /dev/null+++ b/backend/internal/features/tests/logical/mongodb/sshtunnel_test.go@@ -0,0 +1,109 @@+package mongodb_logical++import (+ "net/http"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ "databasus-backend/internal/config"+ backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"+ backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical"+ "databasus-backend/internal/features/databases"+ mongodbtypes "databasus-backend/internal/features/databases/databases/mongodb"+ restores_core "databasus-backend/internal/features/restores/core"+ "databasus-backend/internal/features/storages"+ logicaltesting "databasus-backend/internal/features/tests/logical/shared"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ test_utils "databasus-backend/internal/util/testing"+ "databasus-backend/internal/util/testing/containers"+ "databasus-backend/internal/util/tools"+)++const bastionedMongodbImage = "mongo:7.0"++func bastionedMongodbConfig(+ topology containers.BastionedDatabase,+ databaseName string,+) *mongodbtypes.MongodbDatabase {+ return &mongodbtypes.MongodbDatabase{+ Host: topology.Database.Host,+ Port: new(topology.Database.Port),+ Username: containers.MongodbUsername,+ Password: containers.MongodbPassword,+ Database: databaseName,+ AuthDatabase: containers.MongodbAuthDatabase,+ CpuCount: 1,+ Version: tools.MongodbVersion7,+ SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ }+}++// The forwarded endpoint stands in for the container's own address, so the shared connect helper+// works unchanged.+func openTestTunnelToMongodb(t *testing.T, topology containers.BastionedDatabase) *MongodbContainer {+ t.Helper()++ localEndpoint := logicaltesting.OpenForwardedEndpoint(t, topology)++ return connectToMongodbEndpoint(t, containers.Endpoint{+ Host: localEndpoint.Host,+ Port: localEndpoint.Port,+ }, tools.MongodbVersion7)+}++func Test_MongodbBackupRestore_OverSshTunnel_RestoresData(t *testing.T) {+ topology := containers.StartMongodbBehindSshBastion(t, bastionedMongodbImage)+ sourceContainer := openTestTunnelToMongodb(t, topology)++ setupMongodbTestData(t, sourceContainer)++ router := logicaltesting.CreateTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("MongoDB SSH Tunnel Workspace", user, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ storage := storages.CreateTestStorage(workspace.ID)+ t.Cleanup(func() { storages.RemoveTestStorage(storage.ID) })++ database := logicaltesting.SubmitCreateDatabase(t, router, "MongoDB cycle over SSH tunnel",+ databases.Database{+ Name: "Bastioned MongoDB cycle",+ WorkspaceID: &workspace.ID,+ Type: databases.DatabaseTypeMongodb,+ Mongodb: bastionedMongodbConfig(topology, containers.MongodbDatabase),+ }, user.Token)++ t.Cleanup(func() {+ test_utils.MakeDeleteRequest(t, router, "/api/v1/databases/"+database.ID.String(),+ "Bearer "+user.Token, http.StatusNoContent)+ })++ 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)+ require.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)++ t.Cleanup(func() {+ _ = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))+ })++ restoredDatabaseName := "restoreddb_mongodb_ssh_tunnel"++ logicaltesting.SubmitRestore(t, router, backup.ID,+ restores_core.RestoreBackupRequest{+ MongodbDatabase: bastionedMongodbConfig(topology, restoredDatabaseName),+ }, user.Token)++ restore := waitForMongodbRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)+ require.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)++ verifyMongodbDataIntegrity(t, sourceContainer, restoredDatabaseName)+}diff --git a/backend/internal/features/tests/logical/mysql/sshtunnel_test.go b/backend/internal/features/tests/logical/mysql/sshtunnel_test.gonew file mode 100644index 00000000..66451a6e--- /dev/null+++ b/backend/internal/features/tests/logical/mysql/sshtunnel_test.go@@ -0,0 +1,113 @@+package mysql_logical++import (+ "fmt"+ "net/http"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/jmoiron/sqlx"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/config"+ backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"+ backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical"+ "databasus-backend/internal/features/databases"+ mysqltypes "databasus-backend/internal/features/databases/databases/mysql"+ restores_core "databasus-backend/internal/features/restores/core"+ "databasus-backend/internal/features/storages"+ logicaltesting "databasus-backend/internal/features/tests/logical/shared"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ test_utils "databasus-backend/internal/util/testing"+ "databasus-backend/internal/util/testing/containers"+ "databasus-backend/internal/util/tools"+)++const bastionedMysqlImage = "mysql:8.4"++func bastionedMysqlConfig(+ topology containers.BastionedDatabase,+ databaseName string,+) *mysqltypes.MysqlDatabase {+ return &mysqltypes.MysqlDatabase{+ Host: topology.Database.Host,+ Port: topology.Database.Port,+ Username: "root",+ Password: containers.MysqlRootPassword,+ Database: &databaseName,+ Version: tools.MysqlVersion84,+ SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ }+}++func openTestTunnelToMysql(t *testing.T, topology containers.BastionedDatabase, databaseName string) *sqlx.DB {+ t.Helper()++ localEndpoint := logicaltesting.OpenForwardedEndpoint(t, topology)++ connection, err := sqlx.Connect("mysql", fmt.Sprintf(+ "root:%s@tcp(%s:%d)/%s?parseTime=true",+ containers.MysqlRootPassword, localEndpoint.Host, localEndpoint.Port, databaseName,+ ))+ require.NoError(t, err)+ t.Cleanup(func() { _ = connection.Close() })++ return connection+}++func Test_MysqlBackupRestore_OverSshTunnel_RestoresData(t *testing.T) {+ topology := containers.StartMysqlBehindSshBastion(t, bastionedMysqlImage)+ sourceConnection := openTestTunnelToMysql(t, topology, containers.MysqlDatabase)++ setupMysqlTestData(t, sourceConnection)++ router := logicaltesting.CreateTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("MySQL SSH Tunnel Workspace", user, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ storage := storages.CreateTestStorage(workspace.ID)+ t.Cleanup(func() { storages.RemoveTestStorage(storage.ID) })++ database := logicaltesting.SubmitCreateDatabase(t, router, "MySQL cycle over SSH tunnel",+ databases.Database{+ Name: "Bastioned MySQL cycle",+ WorkspaceID: &workspace.ID,+ Type: databases.DatabaseTypeMysql,+ Mysql: bastionedMysqlConfig(topology, containers.MysqlDatabase),+ }, user.Token)++ t.Cleanup(func() {+ test_utils.MakeDeleteRequest(t, router, "/api/v1/databases/"+database.ID.String(),+ "Bearer "+user.Token, http.StatusNoContent)+ })++ 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)+ require.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)++ t.Cleanup(func() {+ _ = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))+ })++ restoredDatabaseName := "restoreddb_mysql_ssh_tunnel"+ _, err := sourceConnection.Exec("CREATE DATABASE " + restoredDatabaseName)+ require.NoError(t, err)++ logicaltesting.SubmitRestore(t, router, backup.ID,+ restores_core.RestoreBackupRequest{+ MysqlDatabase: bastionedMysqlConfig(topology, restoredDatabaseName),+ }, user.Token)++ restore := waitForMysqlRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)+ require.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)++ verifyMysqlDataIntegrity(t, sourceConnection, openTestTunnelToMysql(t, topology, restoredDatabaseName))+}diff --git a/backend/internal/features/tests/logical/postgresql/sshtunnel_test.go b/backend/internal/features/tests/logical/postgresql/sshtunnel_test.gonew file mode 100644index 00000000..1c187841--- /dev/null+++ b/backend/internal/features/tests/logical/postgresql/sshtunnel_test.go@@ -0,0 +1,115 @@+package postgresql_logical++import (+ "fmt"+ "net/http"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/jmoiron/sqlx"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/config"+ backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"+ backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical"+ "databasus-backend/internal/features/databases"+ postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"+ restores_core "databasus-backend/internal/features/restores/core"+ "databasus-backend/internal/features/storages"+ logicaltesting "databasus-backend/internal/features/tests/logical/shared"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ test_utils "databasus-backend/internal/util/testing"+ "databasus-backend/internal/util/testing/containers"+)++func bastionedPostgresConfig(+ topology containers.BastionedDatabase,+) *postgresql_logical.PostgresqlLogicalDatabase {+ databaseName := containers.PostgresDatabase++ return &postgresql_logical.PostgresqlLogicalDatabase{+ Host: topology.Database.Host,+ Port: topology.Database.Port,+ Username: containers.PostgresUsername,+ Password: containers.PostgresPassword,+ Database: &databaseName,+ CpuCount: 1,+ SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ }+}++func openTestTunnelTo(t *testing.T, topology containers.BastionedDatabase, databaseName string) *sqlx.DB {+ t.Helper()++ localEndpoint := logicaltesting.OpenForwardedEndpoint(t, topology)++ connection, err := sqlx.Connect("postgres", fmt.Sprintf(+ "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",+ localEndpoint.Host, localEndpoint.Port,+ containers.PostgresUsername, containers.PostgresPassword, databaseName,+ ))+ require.NoError(t, err)+ t.Cleanup(func() { _ = connection.Close() })++ return connection+}++func Test_PostgresqlBackupRestore_OverSshTunnel_RestoresData(t *testing.T) {+ topology := containers.StartPostgresBehindSshBastion(t, "postgres:16")+ sourceConnection := openTestTunnelTo(t, topology, containers.PostgresDatabase)++ tableName := "test_data_ssh_tunnel"+ _, err := sourceConnection.Exec(createAndFillTableQuery(tableName))+ require.NoError(t, err)++ router := logicaltesting.CreateTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("SSH Tunnel Cycle Workspace", user, router)+ t.Cleanup(func() { workspaces_testing.RemoveTestWorkspace(workspace, router) })++ storage := storages.CreateTestStorage(workspace.ID)+ t.Cleanup(func() { storages.RemoveTestStorage(storage.ID) })++ database := logicaltesting.SubmitCreateDatabase(t, router, "Postgres cycle over SSH tunnel",+ databases.Database{+ Name: "Bastioned PG cycle",+ WorkspaceID: &workspace.ID,+ Type: databases.DatabaseTypePostgresLogical,+ PostgresqlLogical: bastionedPostgresConfig(topology),+ }, user.Token)++ t.Cleanup(func() {+ test_utils.MakeDeleteRequest(t, router, "/api/v1/databases/"+database.ID.String(),+ "Bearer "+user.Token, http.StatusNoContent)+ })++ 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)+ require.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)++ t.Cleanup(func() {+ _ = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))+ })++ restoredDatabaseName := "restoreddb_ssh_tunnel"+ _, err = sourceConnection.Exec("CREATE DATABASE " + restoredDatabaseName)+ require.NoError(t, err)++ restoreTarget := bastionedPostgresConfig(topology)+ restoreTarget.Database = &restoredDatabaseName++ logicaltesting.SubmitRestore(t, router, backup.ID,+ restores_core.RestoreBackupRequest{PostgresqlLogicalDatabase: restoreTarget}, user.Token)++ restore := waitForRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)+ require.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)++ verifyDataIntegrity(t, sourceConnection, openTestTunnelTo(t, topology, restoredDatabaseName), tableName)+}diff --git a/backend/internal/features/tests/logical/shared/sshtunnel.go b/backend/internal/features/tests/logical/shared/sshtunnel.gonew file mode 100644index 00000000..2182092c--- /dev/null+++ b/backend/internal/features/tests/logical/shared/sshtunnel.go@@ -0,0 +1,38 @@+package logicaltesting++import (+ "testing"++ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/testing/containers"+)++func BuildBastionTunnelConfig(topology containers.BastionedDatabase) sshtunnel.Config {+ return sshtunnel.Config{+ IsEnabled: true,+ Host: topology.Bastion.Host,+ Port: topology.Bastion.Port,+ Username: containers.SshBastionUsername,+ Password: containers.SshBastionPassword,+ }+}++// The test has no other route to the bastioned database, so it reaches it the same way the backup+// does. That is the point of the topology rather than a limitation of it. The forwarder itself+// stays here and closes with the test; callers only need the address to dial.+func OpenForwardedEndpoint(t *testing.T, topology containers.BastionedDatabase) sshtunnel.Endpoint {+ t.Helper()++ forwarder, err := sshtunnel.Open(t.Context(), sshtunnel.OpenSpec{+ Config: BuildBastionTunnelConfig(topology),+ Target: sshtunnel.Endpoint{Host: topology.Database.Host, Port: topology.Database.Port},+ Logger: logger.GetLogger(),+ })+ require.NoError(t, err)+ t.Cleanup(forwarder.Close)++ return forwarder.GetLocalEndpoint()+}diff --git a/backend/internal/features/verification/runs/service.go b/backend/internal/features/verification/runs/service.goindex ba65a0f0..5bfbc615 100644--- a/backend/internal/features/verification/runs/service.go+++ b/backend/internal/features/verification/runs/service.go@@ -747,6 +747,7 @@ func validateDatabaseIsVerifiable(database *databases.Database) error {func sanitizeDatabaseForAgent(database *databases.Database) *databases.Database {database.HideSensitiveData()database.Notifiers = nil+ database.ClearSshTunnelConfig()return database}diff --git a/backend/internal/util/testing/containers/containers.go b/backend/internal/util/testing/containers/containers.goindex 95c922e7..4ec7248b 100644--- a/backend/internal/util/testing/containers/containers.go+++ b/backend/internal/util/testing/containers/containers.go@@ -6,9 +6,12 @@ package containersimport ("context"+ "strconv"+ "strings""testing""github.com/testcontainers/testcontainers-go"+ "github.com/testcontainers/testcontainers-go/network")// dataDirTmpfsOptions mounts a container's data directory on tmpfs (RAM) instead of the overlay@@ -33,6 +36,72 @@ type ContainerHandle struct {Container testcontainers.Container}+// For tests that need one container reachable only from another rather than from the host.+func StartNetwork(t *testing.T) string {+ t.Helper()++ testNetwork, err := network.New(context.Background())+ if err != nil {+ t.Fatalf("failed to create test network: %v", err)+ }++ t.Cleanup(func() {+ if err := testNetwork.Remove(context.Background()); err != nil {+ t.Logf("failed to remove test network: %v", err)+ }+ })++ return testNetwork.Name+}++// Publishing no ports leaves the server unreachable from the host, dialable only by another+// container on the network. The Endpoint each Start*OnNetwork returns is that in-network+// address, which is what an SSH bastion on the same network resolves.+type OnNetworkSpec struct {+ Image string+ Placement NetworkPlacement+}++type NetworkPlacement struct {+ NetworkName string+ Alias string+}++// The engine port consts are testcontainers-shaped ("5432/tcp"); an unpublished container is dialed+// by that raw number rather than by a mapped one.+func getPortNumber(exposedPort string) int {+ number, _, _ := strings.Cut(exposedPort, "/")++ port, err := strconv.Atoi(number)+ if err != nil {+ panic("malformed exposed port " + exposedPort)+ }++ return port+}++func startUnpublished(t *testing.T, req testcontainers.ContainerRequest, placement NetworkPlacement) {+ t.Helper()++ req.ExposedPorts = nil+ req.Networks = []string{placement.NetworkName}+ req.NetworkAliases = map[string][]string{placement.NetworkName: {placement.Alias}}++ container, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{+ ContainerRequest: req,+ Started: true,+ })+ if err != nil {+ t.Fatalf("failed to start %s container: %v", req.Image, err)+ }++ t.Cleanup(func() {+ if err := container.Terminate(context.Background()); err != nil {+ t.Logf("failed to terminate %s container: %v", req.Image, err)+ }+ })+}+func start(t *testing.T, req testcontainers.ContainerRequest, mappedPort string) Endpoint {t.Helper()diff --git a/backend/internal/util/testing/containers/mariadb.go b/backend/internal/util/testing/containers/mariadb.goindex 0e62c99d..fd5fcbd8 100644--- a/backend/internal/util/testing/containers/mariadb.go+++ b/backend/internal/util/testing/containers/mariadb.go@@ -54,6 +54,17 @@ func StartMariadb(t *testing.T, image string) Endpoint {return start(t, mariadbRequest(image), mariadbPort)}+func StartMariadbOnNetwork(t *testing.T, spec OnNetworkSpec) Endpoint {+ t.Helper()++ req := mariadbRequest(spec.Image)+ req.WaitingFor = mysqlFamilyReadyOnNetwork("mariadb-admin", MariadbRootPassword)++ startUnpublished(t, req, spec.Placement)++ return Endpoint{Host: spec.Placement.Alias, Port: getPortNumber(mariadbPort)}+}+// StartMariadbSSL boots a MariaDB server that rejects unencrypted connections. MariaDB// auto-generates its self-signed server certificates only from 11.4, so an older image leaves the// server unreachable and burns the full readiness timeout. The test connects with tlsInsecure anddiff --git a/backend/internal/util/testing/containers/mongodb.go b/backend/internal/util/testing/containers/mongodb.goindex 57f1faae..a8e3ce0e 100644--- a/backend/internal/util/testing/containers/mongodb.go+++ b/backend/internal/util/testing/containers/mongodb.go@@ -62,6 +62,19 @@ func StartMongodb(t *testing.T, image string) Endpoint {return start(t, mongodbRequest(image), mongodbPort)}+func StartMongodbOnNetwork(t *testing.T, spec OnNetworkSpec) Endpoint {+ t.Helper()++ req := mongodbRequest(spec.Image)+ // wait.ForListeningPort resolves the published host port, and this container has none.+ req.WaitingFor = wait.ForLog("Waiting for connections").+ WithOccurrence(2).WithStartupTimeout(mongodbStartupTimeout)++ startUnpublished(t, req, spec.Placement)++ return Endpoint{Host: spec.Placement.Alias, Port: getPortNumber(mongodbPort)}+}+// StartMongodbSSL boots a requireTLS mongod, copying the server key/cert from pemPath and crtPath// into the container. tlsAllowConnectionsWithoutCertificates lets clients connect without a client// cert (the SSL test uses tlsInsecure).diff --git a/backend/internal/util/testing/containers/mysql.go b/backend/internal/util/testing/containers/mysql.goindex a3567b09..c9529397 100644--- a/backend/internal/util/testing/containers/mysql.go+++ b/backend/internal/util/testing/containers/mysql.go@@ -45,6 +45,20 @@ type mysqlFamilyReadinessSpec struct {IsSslRequired bool}+// mysqlFamilyReadyOnNetwork is the unpublished-container counterpart of mysqlFamilyReady, which+// cannot be used there because wait.ForSQL resolves a published host port. Forcing TCP is what+// keeps the probe honest: the entrypoint's temporary initdb server runs with --skip-networking, so+// it cannot answer, and the probe only passes once the real server is listening.+func mysqlFamilyReadyOnNetwork(adminBinary, rootPassword string) wait.Strategy {+ return wait.ForExec([]string{+ adminBinary, "ping",+ "--protocol=TCP",+ "--host=127.0.0.1",+ "--user=root",+ "--password=" + rootPassword,+ }).WithExitCode(0).WithStartupTimeout(mysqlStartupTimeout)+}+// mysqlFamilyReady completes a real handshake rather than counting "ready for connections" log// lines: the entrypoint's temporary socket-only initdb server logs that phrase too, and MySQL 8.x// adds two more lines from X Plugin, so no fixed occurrence identifies the real server across the@@ -121,6 +135,17 @@ func StartMysql(t *testing.T, image string) Endpoint {return start(t, mysqlRequest(image), mysqlPort)}+func StartMysqlOnNetwork(t *testing.T, spec OnNetworkSpec) Endpoint {+ t.Helper()++ req := mysqlRequest(spec.Image)+ req.WaitingFor = mysqlFamilyReadyOnNetwork("mysqladmin", MysqlRootPassword)++ startUnpublished(t, req, spec.Placement)++ return Endpoint{Host: spec.Placement.Alias, Port: getPortNumber(mysqlPort)}+}+// StartMysqlWithoutCompression stands in for managed endpoints whose proxy cannot negotiate// compression even though the server advertises it (issue #687).func StartMysqlWithoutCompression(t *testing.T, image string) Endpoint {diff --git a/backend/internal/util/testing/containers/postgres.go b/backend/internal/util/testing/containers/postgres.goindex 8148dc42..c818157c 100644--- a/backend/internal/util/testing/containers/postgres.go+++ b/backend/internal/util/testing/containers/postgres.go@@ -100,6 +100,19 @@ func StartPostgres(t *testing.T, image string) Endpoint {return start(t, postgresRequest(image), postgresPort)}+func StartPostgresOnNetwork(t *testing.T, spec OnNetworkSpec) Endpoint {+ t.Helper()++ req := postgresRequest(spec.Image)+ // wait.ForListeningPort resolves the published host port, and this container has none.+ req.WaitingFor = wait.ForLog("database system is ready to accept connections").+ WithOccurrence(2).WithStartupTimeout(postgresStartupTimeout)++ startUnpublished(t, req, spec.Placement)++ return Endpoint{Host: spec.Placement.Alias, Port: getPortNumber(postgresPort)}+}+// StartPostgresSSL boots an ssl=on PostgreSQL whose pg_hba.conf rejects non-TLS TCP. The image is// built from contextDir (Dockerfile, server cert/key, pg_hba.conf) because PostgreSQL refuses a key// file that is group/world-readable or not owned by postgres — the Dockerfile chowns+chmods it,diff --git a/backend/internal/util/testing/containers/ssh_bastion.go b/backend/internal/util/testing/containers/ssh_bastion.gonew file mode 100644index 00000000..424187e8--- /dev/null+++ b/backend/internal/util/testing/containers/ssh_bastion.go@@ -0,0 +1,152 @@+package containers++import (+ "path/filepath"+ "runtime"+ "testing"+ "time"++ "github.com/testcontainers/testcontainers-go"+ "github.com/testcontainers/testcontainers-go/wait"+)++// Credentials baked into the test bastion image.+const (+ SshBastionUsername = "testuser"+ SshBastionPassword = "testpassword"+)++const sshBastionPort = "22/tcp"++// The image is built from contextDir rather than pulled because the stock openssh images disagree+// on whether AllowTcpForwarding defaults to yes, and the baked-in authorized_keys has to match the+// private key the test signs with.+func StartSshBastion(t *testing.T) Endpoint {+ t.Helper()++ return start(t, sshBastionRequest(t), sshBastionPort)+}++// Port 22 stays published so the test can dial the bastion; the network membership is what lets the+// bastion in turn reach containers that publish nothing.+func StartSshBastionOnNetwork(t *testing.T, networkName string) Endpoint {+ t.Helper()++ req := sshBastionRequest(t)+ req.Networks = []string{networkName}++ return start(t, req, sshBastionPort)+}++// Resolved from this file rather than the working directory: callers live in other packages, and+// testcontainers resolves a relative context against the CWD. Tests that need the key material+// baked into the image read it from here too.+func GetSshBastionTestdataDir(t *testing.T) string {+ t.Helper()++ _, thisFile, _, isResolved := runtime.Caller(0)+ if !isResolved {+ t.Fatal("failed to resolve the ssh bastion testdata directory")+ }++ return filepath.Join(filepath.Dir(thisFile), "testdata", "ssh_bastion")+}++// Database is the in-network address, reachable only through Bastion.+type BastionedDatabase struct {+ Bastion Endpoint+ Database Endpoint+}++// One alias per engine so a run that boots several topologies stays readable in docker inspect.+const (+ bastionedPostgresAlias = "postgres-behind-bastion"+ bastionedMysqlAlias = "mysql-behind-bastion"+ bastionedMariadbAlias = "mariadb-behind-bastion"+ bastionedMongodbAlias = "mongodb-behind-bastion"+)++// The database publishes no ports and the bastion does, so a tunnel is the only way in. Tests+// asserting that traffic really goes through the tunnel need that: a direct route would keep them+// green after the tunnel stopped being used.+func StartPostgresBehindSshBastion(t *testing.T, image string) BastionedDatabase {+ t.Helper()++ networkName := StartNetwork(t)++ return BastionedDatabase{+ Bastion: StartSshBastionOnNetwork(t, networkName),+ Database: StartPostgresOnNetwork(t, OnNetworkSpec{+ Image: image,+ Placement: NetworkPlacement{+ NetworkName: networkName,+ Alias: bastionedPostgresAlias,+ },+ }),+ }+}++func StartMysqlBehindSshBastion(t *testing.T, image string) BastionedDatabase {+ t.Helper()++ networkName := StartNetwork(t)++ return BastionedDatabase{+ Bastion: StartSshBastionOnNetwork(t, networkName),+ Database: StartMysqlOnNetwork(t, OnNetworkSpec{+ Image: image,+ Placement: NetworkPlacement{+ NetworkName: networkName,+ Alias: bastionedMysqlAlias,+ },+ }),+ }+}++func StartMariadbBehindSshBastion(t *testing.T, image string) BastionedDatabase {+ t.Helper()++ networkName := StartNetwork(t)++ return BastionedDatabase{+ Bastion: StartSshBastionOnNetwork(t, networkName),+ Database: StartMariadbOnNetwork(t, OnNetworkSpec{+ Image: image,+ Placement: NetworkPlacement{+ NetworkName: networkName,+ Alias: bastionedMariadbAlias,+ },+ }),+ }+}++func StartMongodbBehindSshBastion(t *testing.T, image string) BastionedDatabase {+ t.Helper()++ networkName := StartNetwork(t)++ return BastionedDatabase{+ Bastion: StartSshBastionOnNetwork(t, networkName),+ Database: StartMongodbOnNetwork(t, OnNetworkSpec{+ Image: image,+ Placement: NetworkPlacement{+ NetworkName: networkName,+ Alias: bastionedMongodbAlias,+ },+ }),+ }+}++func sshBastionRequest(t *testing.T) testcontainers.ContainerRequest {+ return testcontainers.ContainerRequest{+ FromDockerfile: testcontainers.FromDockerfile{+ Context: GetSshBastionTestdataDir(t),+ Dockerfile: "Dockerfile",+ Repo: "databasus-test-ssh-bastion",+ Tag: "latest",+ KeepImage: true,+ },+ ExposedPorts: []string{sshBastionPort},+ WaitingFor: wait.ForListeningPort(sshBastionPort).WithStartupTimeout(120 * time.Second),+ }+}diff --git a/backend/internal/util/testing/containers/testdata/ssh_bastion/Dockerfile b/backend/internal/util/testing/containers/testdata/ssh_bastion/Dockerfilenew file mode 100644index 00000000..a22ec4b9--- /dev/null+++ b/backend/internal/util/testing/containers/testdata/ssh_bastion/Dockerfile@@ -0,0 +1,17 @@+FROM alpine:3.21++RUN apk add --no-cache openssh-server \+ && ssh-keygen -A \+ && adduser -D -s /bin/sh testuser \+ && echo 'testuser:testpassword' | chpasswd++COPY sshd_config /etc/ssh/sshd_config+COPY authorized_keys /home/testuser/.ssh/authorized_keys++RUN chown -R testuser:testuser /home/testuser/.ssh \+ && chmod 700 /home/testuser/.ssh \+ && chmod 600 /home/testuser/.ssh/authorized_keys++EXPOSE 22++CMD ["/usr/sbin/sshd", "-D", "-e"]diff --git a/backend/internal/util/testing/containers/testdata/ssh_bastion/README.md b/backend/internal/util/testing/containers/testdata/ssh_bastion/README.mdnew file mode 100644index 00000000..2e2b7b91--- /dev/null+++ b/backend/internal/util/testing/containers/testdata/ssh_bastion/README.md@@ -0,0 +1,43 @@+# SSH bastion test fixture++Throwaway credentials for the SSH tunnel tests. **None of this material is secret, and none of it+grants access to anything** - the keys are generated for this directory, live only inside a+container built at test time, and are regenerated by anyone who wants to.++A secret scanner will flag `test_key` and `test_key_passphrase` as private keys. That is expected,+and matches the already-committed PEM material under `internal/features/tests/logical/postgresql/testdata/`.++## Files++| File | What it is |+|---|---|+| `Dockerfile` | Alpine + OpenSSH bastion. Creates the `testuser` account and sets its password. |+| `sshd_config` | Permits TCP forwarding and adds a second listener on 2222. |+| `authorized_keys` | Public halves of both keys below. |+| `test_key` | Passphrase-less ed25519 private key, for the public-key auth test. |+| `test_key_passphrase` | ed25519 private key protected with the passphrase `testpassphrase`. |++Account baked into the image: `testuser` / `testpassword`.++## Why sshd listens on 2222++The tunnel tests forward to port 2222 rather than 22. Port 2222 is never published to the host, so+a forwarder that stopped tunnelling and dialled the host loopback instead cannot accidentally reach+a developer's or CI runner's own sshd and pass. `Test_TargetPort_WithoutTheTunnel_IsUnreachableFromTheHost`+pins that property.++## Regenerating++```sh+cd backend/internal/util/testing/containers/testdata/ssh_bastion+rm -f test_key test_key_passphrase authorized_keys++ssh-keygen -t ed25519 -N "" -C "databasus-sshtunnel-test" -f test_key+mv test_key.pub authorized_keys++ssh-keygen -t ed25519 -N "testpassphrase" -C "databasus-sshtunnel-test-passphrase" -f test_key_passphrase+cat test_key_passphrase.pub >> authorized_keys+rm test_key_passphrase.pub+```++The passphrase is asserted verbatim in `forwarder_test.go`; changing it means changing the test.diff --git a/backend/internal/util/testing/containers/testdata/ssh_bastion/authorized_keys b/backend/internal/util/testing/containers/testdata/ssh_bastion/authorized_keysnew file mode 100644index 00000000..0af62817--- /dev/null+++ b/backend/internal/util/testing/containers/testdata/ssh_bastion/authorized_keys@@ -0,0 +1,2 @@+ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEUx+3MxWV9rIzO0nYGz4JkkRxaXdxfUT+HXC9RkBCKU databasus-sshtunnel-test+ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG0MC2x6chd7UfwDyBl8CIcmoJzSTo7wFJdqovAGxSfJ databasus-sshtunnel-test-passphrasediff --git a/backend/internal/util/testing/containers/testdata/ssh_bastion/sshd_config b/backend/internal/util/testing/containers/testdata/ssh_bastion/sshd_confignew file mode 100644index 00000000..43e39c17--- /dev/null+++ b/backend/internal/util/testing/containers/testdata/ssh_bastion/sshd_config@@ -0,0 +1,27 @@+Port 22++# The tunnel tests forward to this second port instead of 22. It is never published to the host,+# so a forwarder that dialled the host loopback rather than going through the bastion cannot+# accidentally reach a developer's or CI runner's own sshd and pass.+Port 2222++AddressFamily any+ListenAddress 0.0.0.0++HostKey /etc/ssh/ssh_host_ed25519_key+HostKey /etc/ssh/ssh_host_rsa_key++PermitRootLogin no+PasswordAuthentication yes+PubkeyAuthentication yes+AuthorizedKeysFile .ssh/authorized_keys+PermitEmptyPasswords no+UsePAM no++AllowTcpForwarding yes+GatewayPorts no+X11Forwarding no+AllowAgentForwarding no++Subsystem sftp /usr/lib/ssh/sftp-server+LogLevel INFOdiff --git a/backend/internal/util/testing/containers/testdata/ssh_bastion/test_key b/backend/internal/util/testing/containers/testdata/ssh_bastion/test_keynew file mode 100644index 00000000..1984fa95--- /dev/null+++ b/backend/internal/util/testing/containers/testdata/ssh_bastion/test_key@@ -0,0 +1,7 @@+-----BEGIN OPENSSH PRIVATE KEY-----+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW+QyNTUxOQAAACBFMftzMVlfayMztJ2Bs+CZJEcWl3cX1E/h1wvUZAQilAAAAKBVN10UVTdd+FAAAAAtzc2gtZWQyNTUxOQAAACBFMftzMVlfayMztJ2Bs+CZJEcWl3cX1E/h1wvUZAQilA+AAAEBSNFTn7MLEDhTBXbD5Jt4iXaAsbHxV4GSeH9TJFyXw10Ux+3MxWV9rIzO0nYGz4Jkk+RxaXdxfUT+HXC9RkBCKUAAAAGGRhdGFiYXN1cy1zc2h0dW5uZWwtdGVzdAECAwQF+-----END OPENSSH PRIVATE KEY-----diff --git a/backend/internal/util/testing/containers/testdata/ssh_bastion/test_key_passphrase b/backend/internal/util/testing/containers/testdata/ssh_bastion/test_key_passphrasenew file mode 100644index 00000000..5cb361c1--- /dev/null+++ b/backend/internal/util/testing/containers/testdata/ssh_bastion/test_key_passphrase@@ -0,0 +1,8 @@+-----BEGIN OPENSSH PRIVATE KEY-----+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABCTGbNAO2+d2rMIcQZcpb2HYAAAAGAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIG0MC2x6chd7UfwD+yBl8CIcmoJzSTo7wFJdqovAGxSfJAAAAsGohanm+uBX8JYWaSPGStzG1zzqW3JEajuaBqT+HB+cMPj11TgXsU7ZQ0VPUbT9m00sVVmsyGJQig/cYAn31kIldPgC5mc0ZGvKnYvRcMEvGC+75yWDxbUxHrbOccZU+A/fH27h3bUwTeE45l8MaVxLjSdOgZn4ZX9tGMQeKaO5KlckUSVzE+YWnhNsUFLPTOVI5SykN1f6g+fAWJvmv96jSFu0MGHc+PwXI4NRKfAXWmqH+-----END OPENSSH PRIVATE KEY-----diff --git a/backend/migrations/20260812115746_add_ssh_tunnel_to_logical_databases.sql b/backend/migrations/20260812115746_add_ssh_tunnel_to_logical_databases.sqlnew file mode 100644index 00000000..0b2c2582--- /dev/null+++ b/backend/migrations/20260812115746_add_ssh_tunnel_to_logical_databases.sql@@ -0,0 +1,173 @@+-- +goose Up+-- +goose StatementBegin+ALTER TABLE postgresql_logical_databases+ ADD COLUMN IF NOT EXISTS ssh_is_enabled BOOLEAN NOT NULL DEFAULT FALSE;++ALTER TABLE postgresql_logical_databases+ ADD COLUMN IF NOT EXISTS ssh_host TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_logical_databases+ ADD COLUMN IF NOT EXISTS ssh_port INTEGER NOT NULL DEFAULT 22;++ALTER TABLE postgresql_logical_databases+ ADD COLUMN IF NOT EXISTS ssh_username TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_logical_databases+ ADD COLUMN IF NOT EXISTS ssh_password TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_logical_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_logical_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key_passphrase TEXT NOT NULL DEFAULT '';++ALTER TABLE mysql_databases+ ADD COLUMN IF NOT EXISTS ssh_is_enabled BOOLEAN NOT NULL DEFAULT FALSE;++ALTER TABLE mysql_databases+ ADD COLUMN IF NOT EXISTS ssh_host TEXT NOT NULL DEFAULT '';++ALTER TABLE mysql_databases+ ADD COLUMN IF NOT EXISTS ssh_port INTEGER NOT NULL DEFAULT 22;++ALTER TABLE mysql_databases+ ADD COLUMN IF NOT EXISTS ssh_username TEXT NOT NULL DEFAULT '';++ALTER TABLE mysql_databases+ ADD COLUMN IF NOT EXISTS ssh_password TEXT NOT NULL DEFAULT '';++ALTER TABLE mysql_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key TEXT NOT NULL DEFAULT '';++ALTER TABLE mysql_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key_passphrase TEXT NOT NULL DEFAULT '';++ALTER TABLE mariadb_databases+ ADD COLUMN IF NOT EXISTS ssh_is_enabled BOOLEAN NOT NULL DEFAULT FALSE;++ALTER TABLE mariadb_databases+ ADD COLUMN IF NOT EXISTS ssh_host TEXT NOT NULL DEFAULT '';++ALTER TABLE mariadb_databases+ ADD COLUMN IF NOT EXISTS ssh_port INTEGER NOT NULL DEFAULT 22;++ALTER TABLE mariadb_databases+ ADD COLUMN IF NOT EXISTS ssh_username TEXT NOT NULL DEFAULT '';++ALTER TABLE mariadb_databases+ ADD COLUMN IF NOT EXISTS ssh_password TEXT NOT NULL DEFAULT '';++ALTER TABLE mariadb_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key TEXT NOT NULL DEFAULT '';++ALTER TABLE mariadb_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key_passphrase TEXT NOT NULL DEFAULT '';++ALTER TABLE mongodb_databases+ ADD COLUMN IF NOT EXISTS ssh_is_enabled BOOLEAN NOT NULL DEFAULT FALSE;++ALTER TABLE mongodb_databases+ ADD COLUMN IF NOT EXISTS ssh_host TEXT NOT NULL DEFAULT '';++ALTER TABLE mongodb_databases+ ADD COLUMN IF NOT EXISTS ssh_port INTEGER NOT NULL DEFAULT 22;++ALTER TABLE mongodb_databases+ ADD COLUMN IF NOT EXISTS ssh_username TEXT NOT NULL DEFAULT '';++ALTER TABLE mongodb_databases+ ADD COLUMN IF NOT EXISTS ssh_password TEXT NOT NULL DEFAULT '';++ALTER TABLE mongodb_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key TEXT NOT NULL DEFAULT '';++ALTER TABLE mongodb_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key_passphrase TEXT NOT NULL DEFAULT '';+-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin+ALTER TABLE mongodb_databases+ DROP COLUMN IF EXISTS ssh_private_key_passphrase;++ALTER TABLE mongodb_databases+ DROP COLUMN IF EXISTS ssh_private_key;++ALTER TABLE mongodb_databases+ DROP COLUMN IF EXISTS ssh_password;++ALTER TABLE mongodb_databases+ DROP COLUMN IF EXISTS ssh_username;++ALTER TABLE mongodb_databases+ DROP COLUMN IF EXISTS ssh_port;++ALTER TABLE mongodb_databases+ DROP COLUMN IF EXISTS ssh_host;++ALTER TABLE mongodb_databases+ DROP COLUMN IF EXISTS ssh_is_enabled;++ALTER TABLE mariadb_databases+ DROP COLUMN IF EXISTS ssh_private_key_passphrase;++ALTER TABLE mariadb_databases+ DROP COLUMN IF EXISTS ssh_private_key;++ALTER TABLE mariadb_databases+ DROP COLUMN IF EXISTS ssh_password;++ALTER TABLE mariadb_databases+ DROP COLUMN IF EXISTS ssh_username;++ALTER TABLE mariadb_databases+ DROP COLUMN IF EXISTS ssh_port;++ALTER TABLE mariadb_databases+ DROP COLUMN IF EXISTS ssh_host;++ALTER TABLE mariadb_databases+ DROP COLUMN IF EXISTS ssh_is_enabled;++ALTER TABLE mysql_databases+ DROP COLUMN IF EXISTS ssh_private_key_passphrase;++ALTER TABLE mysql_databases+ DROP COLUMN IF EXISTS ssh_private_key;++ALTER TABLE mysql_databases+ DROP COLUMN IF EXISTS ssh_password;++ALTER TABLE mysql_databases+ DROP COLUMN IF EXISTS ssh_username;++ALTER TABLE mysql_databases+ DROP COLUMN IF EXISTS ssh_port;++ALTER TABLE mysql_databases+ DROP COLUMN IF EXISTS ssh_host;++ALTER TABLE mysql_databases+ DROP COLUMN IF EXISTS ssh_is_enabled;++ALTER TABLE postgresql_logical_databases+ DROP COLUMN IF EXISTS ssh_private_key_passphrase;++ALTER TABLE postgresql_logical_databases+ DROP COLUMN IF EXISTS ssh_private_key;++ALTER TABLE postgresql_logical_databases+ DROP COLUMN IF EXISTS ssh_password;++ALTER TABLE postgresql_logical_databases+ DROP COLUMN IF EXISTS ssh_username;++ALTER TABLE postgresql_logical_databases+ DROP COLUMN IF EXISTS ssh_port;++ALTER TABLE postgresql_logical_databases+ DROP COLUMN IF EXISTS ssh_host;++ALTER TABLE postgresql_logical_databases+ DROP COLUMN IF EXISTS ssh_is_enabled;+-- +goose StatementEnddiff --git a/frontend/src/entity/databases/index.ts b/frontend/src/entity/databases/index.tsindex 2fd52674..56ae83d6 100644--- a/frontend/src/entity/databases/index.ts+++ b/frontend/src/entity/databases/index.ts@@ -18,11 +18,19 @@ export {physicalConnectionErrorContent,} from './model/postgresql/physical/physicalConnectionErrorContent';export { PostgresqlVersion } from './model/postgresql/PostgresqlVersion';+export { type SshTunnelConfig } from './model/sshtunnel/SshTunnelConfig';+export {+ DEFAULT_SSH_PORT,+ createEmptySshTunnelConfig,+} from './model/sshtunnel/createEmptySshTunnelConfig';+export { isSshTunnelReadyToTest } from './model/sshtunnel/isSshTunnelReadyToTest';+export { hasStoredSshTunnelSecrets } from './model/sshtunnel/hasStoredSshTunnelSecrets';export { type MysqlDatabase } from './model/mysql/MysqlDatabase';export { MysqlVersion } from './model/mysql/MysqlVersion';export { type MariadbDatabase } from './model/mariadb/MariadbDatabase';export { MariadbVersion } from './model/mariadb/MariadbVersion';export { type MongodbDatabase } from './model/mongodb/MongodbDatabase';export { MongodbVersion } from './model/mongodb/MongodbVersion';+export { disableSrvWhenTunneled } from './model/mongodb/disableSrvWhenTunneled';export { type IsReadOnlyResponse } from './model/IsReadOnlyResponse';export { type CreateReadOnlyUserResponse } from './model/CreateReadOnlyUserResponse';diff --git a/frontend/src/entity/databases/model/mariadb/MariadbDatabase.ts b/frontend/src/entity/databases/model/mariadb/MariadbDatabase.tsindex 441efda6..b462392f 100644--- a/frontend/src/entity/databases/model/mariadb/MariadbDatabase.ts+++ b/frontend/src/entity/databases/model/mariadb/MariadbDatabase.ts@@ -1,3 +1,4 @@+import type { SshTunnelConfig } from '../sshtunnel/SshTunnelConfig';import type { MariadbVersion } from './MariadbVersion';export interface MariadbDatabase {@@ -9,6 +10,7 @@ export interface MariadbDatabase {password: string;database?: string;isHttps: boolean;+ sshTunnel?: SshTunnelConfig;isExcludeEvents?: boolean;isSkipGaleraDisable?: boolean;excludeTables?: string[];diff --git a/frontend/src/entity/databases/model/mongodb/MongodbDatabase.ts b/frontend/src/entity/databases/model/mongodb/MongodbDatabase.tsindex 79abdf47..970fade3 100644--- a/frontend/src/entity/databases/model/mongodb/MongodbDatabase.ts+++ b/frontend/src/entity/databases/model/mongodb/MongodbDatabase.ts@@ -1,3 +1,4 @@+import type { SshTunnelConfig } from '../sshtunnel/SshTunnelConfig';import type { MongodbVersion } from './MongodbVersion';export interface MongodbDatabase {@@ -13,5 +14,6 @@ export interface MongodbDatabase {isSrv: boolean;isDirectConnection: boolean;cpuCount: number;+ sshTunnel?: SshTunnelConfig;excludeCollections?: string[];}diff --git a/frontend/src/entity/databases/model/mongodb/disableSrvWhenTunneled.test.ts b/frontend/src/entity/databases/model/mongodb/disableSrvWhenTunneled.test.tsnew file mode 100644index 00000000..c171e464--- /dev/null+++ b/frontend/src/entity/databases/model/mongodb/disableSrvWhenTunneled.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import type { SshTunnelConfig } from '../sshtunnel/SshTunnelConfig';+import type { MongodbDatabase } from './MongodbDatabase';+import { MongodbVersion } from './MongodbVersion';+import { disableSrvWhenTunneled } from './disableSrvWhenTunneled';++const enabledTunnel = (): SshTunnelConfig => ({+ isEnabled: true,+ host: 'bastion.example.com',+ port: 22,+ username: 'tunneluser',+ password: 'tunnelpassword',+ privateKey: '',+ privateKeyPassphrase: '',+});++const srvDatabase = (sshTunnel?: SshTunnelConfig): MongodbDatabase => ({+ id: 'db-1',+ version: MongodbVersion.V7,+ host: 'cluster0.example.mongodb.net',+ port: 27017,+ username: 'testuser',+ password: 'testpassword',+ database: 'testdb',+ authDatabase: 'admin',+ isHttps: false,+ isSrv: true,+ isDirectConnection: false,+ cpuCount: 1,+ sshTunnel,+});++describe('disableSrvWhenTunneled', () => {+ it('turns SRV off when the tunnel is enabled', () => {+ expect(disableSrvWhenTunneled(srvDatabase(enabledTunnel())).isSrv).toBe(false);+ });++ it('leaves SRV alone when there is no tunnel', () => {+ expect(disableSrvWhenTunneled(srvDatabase()).isSrv).toBe(true);+ expect(+ disableSrvWhenTunneled(srvDatabase({ ...enabledTunnel(), isEnabled: false })).isSrv,+ ).toBe(true);+ });++ it('does not touch direct connection, which the backend forces per operation', () => {+ expect(disableSrvWhenTunneled(srvDatabase(enabledTunnel())).isDirectConnection).toBe(false);+ });++ it('returns the same object when nothing changes', () => {+ const database = srvDatabase();++ expect(disableSrvWhenTunneled(database)).toBe(database);+ });+});diff --git a/frontend/src/entity/databases/model/mongodb/disableSrvWhenTunneled.ts b/frontend/src/entity/databases/model/mongodb/disableSrvWhenTunneled.tsnew file mode 100644index 00000000..b26230b3--- /dev/null+++ b/frontend/src/entity/databases/model/mongodb/disableSrvWhenTunneled.ts@@ -0,0 +1,12 @@+import type { MongodbDatabase } from './MongodbDatabase';++/**+ * SRV resolves its own host list from DNS and never carries a port, so it can never travel through+ * a forwarded local port. The backend rejects the combination, so the form must not be able to+ * produce it - including via a pasted mongodb+srv:// connection string.+ */+export function disableSrvWhenTunneled(mongodb: MongodbDatabase): MongodbDatabase {+ if (!mongodb.sshTunnel?.isEnabled) return mongodb;++ return { ...mongodb, isSrv: false };+}diff --git a/frontend/src/entity/databases/model/mysql/MysqlDatabase.ts b/frontend/src/entity/databases/model/mysql/MysqlDatabase.tsindex 052217e7..8718c71e 100644--- a/frontend/src/entity/databases/model/mysql/MysqlDatabase.ts+++ b/frontend/src/entity/databases/model/mysql/MysqlDatabase.ts@@ -1,3 +1,4 @@+import type { SshTunnelConfig } from '../sshtunnel/SshTunnelConfig';import type { MysqlVersion } from './MysqlVersion';export interface MysqlDatabase {@@ -10,5 +11,6 @@ export interface MysqlDatabase {password: string;database?: string;isHttps: boolean;+ sshTunnel?: SshTunnelConfig;excludeTables?: string[];}diff --git a/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.ts b/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.tsindex a4839df1..334a6eb2 100644--- a/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.ts+++ b/frontend/src/entity/databases/model/postgresql/PostgresqlLogicalDatabase.ts@@ -1,3 +1,4 @@+import type { SshTunnelConfig } from '../sshtunnel/SshTunnelConfig';import type { PostgresSslMode } from './PostgresSslMode';import type { PostgresqlVersion } from './PostgresqlVersion';@@ -18,6 +19,9 @@ export interface PostgresqlLogicalDatabase {sslClientKey?: string;sslRootCert?: string;+ // When enabled, host and port above address the database as the bastion sees it.+ sshTunnel?: SshTunnelConfig;+// backup settingsincludeSchemas?: string[];excludeTables?: string[];diff --git a/frontend/src/entity/databases/model/sshtunnel/SshTunnelConfig.ts b/frontend/src/entity/databases/model/sshtunnel/SshTunnelConfig.tsnew file mode 100644index 00000000..3a63ff96--- /dev/null+++ b/frontend/src/entity/databases/model/sshtunnel/SshTunnelConfig.ts@@ -0,0 +1,9 @@+export interface SshTunnelConfig {+ isEnabled: boolean;+ host: string;+ port: number;+ username: string;+ password: string;+ privateKey: string;+ privateKeyPassphrase: string;+}diff --git a/frontend/src/entity/databases/model/sshtunnel/createEmptySshTunnelConfig.ts b/frontend/src/entity/databases/model/sshtunnel/createEmptySshTunnelConfig.tsnew file mode 100644index 00000000..365e317a--- /dev/null+++ b/frontend/src/entity/databases/model/sshtunnel/createEmptySshTunnelConfig.ts@@ -0,0 +1,15 @@+import type { SshTunnelConfig } from './SshTunnelConfig';++export const DEFAULT_SSH_PORT = 22;++export function createEmptySshTunnelConfig(): SshTunnelConfig {+ return {+ isEnabled: false,+ host: '',+ port: DEFAULT_SSH_PORT,+ username: '',+ password: '',+ privateKey: '',+ privateKeyPassphrase: '',+ };+}diff --git a/frontend/src/entity/databases/model/sshtunnel/hasStoredSshTunnelSecrets.test.ts b/frontend/src/entity/databases/model/sshtunnel/hasStoredSshTunnelSecrets.test.tsnew file mode 100644index 00000000..5c16898c--- /dev/null+++ b/frontend/src/entity/databases/model/sshtunnel/hasStoredSshTunnelSecrets.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import type { SshTunnelConfig } from './SshTunnelConfig';+import { hasStoredSshTunnelSecrets } from './hasStoredSshTunnelSecrets';++const enabledTunnel = (): SshTunnelConfig => ({+ isEnabled: true,+ host: 'bastion.example.com',+ port: 22,+ username: 'tunneluser',+ password: '',+ privateKey: '',+ privateKeyPassphrase: '',+});++describe('hasStoredSshTunnelSecrets', () => {+ it('is true for a saved database whose tunnel is enabled', () => {+ expect(hasStoredSshTunnelSecrets(enabledTunnel(), 'db-1')).toBe(true);+ });++ it('is false while the database is still being created', () => {+ expect(hasStoredSshTunnelSecrets(enabledTunnel(), undefined)).toBe(false);+ });++ it('is false for a saved database that never had a tunnel', () => {+ expect(hasStoredSshTunnelSecrets(undefined, 'db-1')).toBe(false);+ expect(hasStoredSshTunnelSecrets({ ...enabledTunnel(), isEnabled: false }, 'db-1')).toBe(false);+ });+});diff --git a/frontend/src/entity/databases/model/sshtunnel/hasStoredSshTunnelSecrets.ts b/frontend/src/entity/databases/model/sshtunnel/hasStoredSshTunnelSecrets.tsnew file mode 100644index 00000000..9a71ced7--- /dev/null+++ b/frontend/src/entity/databases/model/sshtunnel/hasStoredSshTunnelSecrets.ts@@ -0,0 +1,12 @@+import type { SshTunnelConfig } from './SshTunnelConfig';++/**+ * Answers from the saved database, never from the edited copy: a database that never had a tunnel+ * would otherwise show the masked placeholder the moment the checkbox is ticked.+ */+export function hasStoredSshTunnelSecrets(+ sshTunnel: SshTunnelConfig | undefined,+ databaseId: string | undefined,+): boolean {+ return !!databaseId && !!sshTunnel?.isEnabled;+}diff --git a/frontend/src/entity/databases/model/sshtunnel/isSshTunnelReadyToTest.test.ts b/frontend/src/entity/databases/model/sshtunnel/isSshTunnelReadyToTest.test.tsnew file mode 100644index 00000000..a34a4ba0--- /dev/null+++ b/frontend/src/entity/databases/model/sshtunnel/isSshTunnelReadyToTest.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import type { SshTunnelConfig } from './SshTunnelConfig';+import { createEmptySshTunnelConfig } from './createEmptySshTunnelConfig';+import { isSshTunnelReadyToTest } from './isSshTunnelReadyToTest';++function enabledTunnel(): SshTunnelConfig {+ return {+ ...createEmptySshTunnelConfig(),+ isEnabled: true,+ host: 'bastion.example.com',+ username: 'tunneluser',+ password: 'tunnelpassword',+ };+}++describe('isSshTunnelReadyToTest', () => {+ it('accepts a missing config, since the tunnel is optional', () => {+ expect(isSshTunnelReadyToTest(undefined, false)).toBe(true);+ });++ it('ignores an incomplete config while the tunnel is off', () => {+ expect(isSshTunnelReadyToTest(createEmptySshTunnelConfig(), false)).toBe(true);+ });++ it('accepts a complete config with a password', () => {+ expect(isSshTunnelReadyToTest(enabledTunnel(), false)).toBe(true);+ });++ it('accepts a private key instead of a password', () => {+ expect(+ isSshTunnelReadyToTest({ ...enabledTunnel(), password: '', privateKey: 'key' }, false),+ ).toBe(true);+ });++ it.each(['host', 'username'] as const)('rejects a missing %s', (field) => {+ expect(isSshTunnelReadyToTest({ ...enabledTunnel(), [field]: '' }, false)).toBe(false);+ });++ it('rejects a missing port', () => {+ expect(isSshTunnelReadyToTest({ ...enabledTunnel(), port: 0 }, false)).toBe(false);+ });++ it('rejects a missing secret when creating', () => {+ expect(isSshTunnelReadyToTest({ ...enabledTunnel(), password: '' }, false)).toBe(false);+ });++ it('accepts a missing secret when one is already stored', () => {+ expect(isSshTunnelReadyToTest({ ...enabledTunnel(), password: '' }, true)).toBe(true);+ });+});diff --git a/frontend/src/entity/databases/model/sshtunnel/isSshTunnelReadyToTest.ts b/frontend/src/entity/databases/model/sshtunnel/isSshTunnelReadyToTest.tsnew file mode 100644index 00000000..cc316440--- /dev/null+++ b/frontend/src/entity/databases/model/sshtunnel/isSshTunnelReadyToTest.ts@@ -0,0 +1,18 @@+import type { SshTunnelConfig } from './SshTunnelConfig';++/**+ * Secrets are only required when creating: an existing database keeps the ones already stored, and+ * the edit form never receives them back from the API.+ */+export function isSshTunnelReadyToTest(+ sshTunnel: SshTunnelConfig | undefined,+ hasStoredSecrets: boolean,+): boolean {+ if (!sshTunnel?.isEnabled) return true;++ if (!sshTunnel.host) return false;+ if (!sshTunnel.port) return false;+ if (!sshTunnel.username) return false;++ return hasStoredSecrets || !!sshTunnel.password || !!sshTunnel.privateKey;+}diff --git a/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsxindex e3616ee8..18e53860 100644--- a/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsx@@ -2,12 +2,18 @@ import { CopyOutlined, DownOutlined, InfoCircleOutlined, UpOutlined } from '@antimport { App, Button, Checkbox, Input, InputNumber, Select, Switch, Tooltip } from 'antd';import { useEffect, useState } from 'react';-import { type Database, databaseApi } from '../../../../entity/databases';+import {+ type Database,+ databaseApi,+ hasStoredSshTunnelSecrets,+ isSshTunnelReadyToTest,+} from '../../../../entity/databases';import { MariadbConnectionStringParser } from '../../../../entity/databases/model/mariadb/MariadbConnectionStringParser';import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';import { ClipboardPasteModalComponent } from '../../../../shared/ui';+import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {database: Database;@@ -170,6 +176,8 @@ export const EditMariaDbSpecificDataComponent = ({if (!editingDatabase) return null;+ const hasStoredSshSecrets = hasStoredSshTunnelSecrets(database.mariadb?.sshTunnel, database.id);+let isAllFieldsFilled = true;if (!editingDatabase.mariadb?.host) isAllFieldsFilled = false;if (!editingDatabase.mariadb?.port) isAllFieldsFilled = false;@@ -177,9 +185,16 @@ export const EditMariaDbSpecificDataComponent = ({if (!editingDatabase.id && !editingDatabase.mariadb?.password) isAllFieldsFilled = false;if (!editingDatabase.mariadb?.database) isAllFieldsFilled = false;+ if (!isSshTunnelReadyToTest(editingDatabase.mariadb?.sshTunnel, hasStoredSshSecrets))+ isAllFieldsFilled = false;++ // Behind a bastion a loopback address names the database as the bastion sees it, so the hint+ // about reaching a local database would be wrong.+ const isTunnelEnabled = !!editingDatabase.mariadb?.sshTunnel?.isEnabled;const isLocalhostDb =- editingDatabase.mariadb?.host?.includes('localhost') ||- editingDatabase.mariadb?.host?.includes('127.0.0.1');+ !isTunnelEnabled &&+ (editingDatabase.mariadb?.host?.includes('localhost') ||+ editingDatabase.mariadb?.host?.includes('127.0.0.1'));return (<div>@@ -317,6 +332,20 @@ export const EditMariaDbSpecificDataComponent = ({</div>)}+ <EditSshTunnelComponent+ sshTunnel={editingDatabase.mariadb?.sshTunnel}+ hasStoredSecrets={hasStoredSshSecrets}+ onChange={(sshTunnel) => {+ if (!editingDatabase.mariadb) return;++ setEditingDatabase({+ ...editingDatabase,+ mariadb: { ...editingDatabase.mariadb, sshTunnel },+ });+ setIsConnectionTested(false);+ }}+ />+<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Use HTTPS</div><Switchdiff --git a/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsxindex 1cb66774..9a280ebb 100644--- a/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsx@@ -2,12 +2,19 @@ import { CopyOutlined, DownOutlined, InfoCircleOutlined, UpOutlined } from '@antimport { App, Button, Input, InputNumber, Select, Switch, Tooltip } from 'antd';import { useEffect, useState } from 'react';-import { type Database, databaseApi } from '../../../../entity/databases';+import {+ type Database,+ databaseApi,+ disableSrvWhenTunneled,+ hasStoredSshTunnelSecrets,+ isSshTunnelReadyToTest,+} from '../../../../entity/databases';import { MongodbConnectionStringParser } from '../../../../entity/databases/model/mongodb/MongodbConnectionStringParser';import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';import { ClipboardPasteModalComponent } from '../../../../shared/ui';+import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {database: Database;@@ -76,7 +83,7 @@ export const EditMongoDbSpecificDataComponent = ({const updatedDatabase: Database = {...editingDatabase,- mongodb: {+ mongodb: disableSrvWhenTunneled({...editingDatabase.mongodb,host: result.host,port: result.port,@@ -88,7 +95,7 @@ export const EditMongoDbSpecificDataComponent = ({isSrv: result.isSrv,isDirectConnection: result.isDirectConnection,cpuCount: 1,- },+ }),};if (result.isSrv || result.isDirectConnection) {@@ -186,6 +193,8 @@ export const EditMongoDbSpecificDataComponent = ({const isSrvConnection = editingDatabase.mongodb?.isSrv || false;+ const hasStoredSshSecrets = hasStoredSshTunnelSecrets(database.mongodb?.sshTunnel, database.id);+let isAllFieldsFilled = true;if (!editingDatabase.mongodb?.host) isAllFieldsFilled = false;if (!isSrvConnection && !editingDatabase.mongodb?.port) isAllFieldsFilled = false;@@ -193,9 +202,16 @@ export const EditMongoDbSpecificDataComponent = ({if (!editingDatabase.id && !editingDatabase.mongodb?.password) isAllFieldsFilled = false;if (!editingDatabase.mongodb?.database) isAllFieldsFilled = false;+ if (!isSshTunnelReadyToTest(editingDatabase.mongodb?.sshTunnel, hasStoredSshSecrets))+ isAllFieldsFilled = false;++ // Behind a bastion a loopback address names the database as the bastion sees it, so the hint+ // about reaching a local database would be wrong.+ const isTunnelEnabled = !!editingDatabase.mongodb?.sshTunnel?.isEnabled;const isLocalhostDb =- editingDatabase.mongodb?.host?.includes('localhost') ||- editingDatabase.mongodb?.host?.includes('127.0.0.1');+ !isTunnelEnabled &&+ (editingDatabase.mongodb?.host?.includes('localhost') ||+ editingDatabase.mongodb?.host?.includes('127.0.0.1'));return (<div>@@ -335,6 +351,21 @@ export const EditMongoDbSpecificDataComponent = ({</div>)}+ <EditSshTunnelComponent+ sshTunnel={editingDatabase.mongodb?.sshTunnel}+ hasStoredSecrets={hasStoredSshSecrets}+ onChange={(sshTunnel) => {+ if (!editingDatabase.mongodb) return;++ setEditingDatabase({+ ...editingDatabase,+ mongodb: disableSrvWhenTunneled({ ...editingDatabase.mongodb, sshTunnel }),+ });+ setShowAdvanced(true);+ setIsConnectionTested(false);+ }}+ />+<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Use HTTPS</div><Switch@@ -403,6 +434,7 @@ export const EditMongoDbSpecificDataComponent = ({<div className="flex items-center"><Switchchecked={editingDatabase.mongodb?.isSrv || false}+ disabled={isTunnelEnabled}onChange={(checked) => {if (!editingDatabase.mongodb) return;@@ -416,7 +448,11 @@ export const EditMongoDbSpecificDataComponent = ({/><TooltipclassName="cursor-pointer"- title="Enable for MongoDB Atlas SRV connections (mongodb+srv://). Port is not required for SRV connections."+ title={+ isTunnelEnabled+ ? 'Not available over an SSH tunnel - SRV resolves its own host list and bypasses the forwarded port.'+ : 'Enable for MongoDB Atlas SRV connections (mongodb+srv://). Port is not required for SRV connections.'+ }><InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} /></Tooltip>@@ -426,8 +462,11 @@ export const EditMongoDbSpecificDataComponent = ({<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Direct connection</div><div className="flex items-center">+ {/* Shown as on but never written: the backend forces it per connection, so the+ stored value still applies once the tunnel is switched off. */}<Switch- checked={editingDatabase.mongodb?.isDirectConnection || false}+ checked={isTunnelEnabled || editingDatabase.mongodb?.isDirectConnection || false}+ disabled={isTunnelEnabled}onChange={(checked) => {if (!editingDatabase.mongodb) return;@@ -441,7 +480,11 @@ export const EditMongoDbSpecificDataComponent = ({/><TooltipclassName="cursor-pointer"- title="Connect directly to a single server, skipping replica set discovery. Useful when the server is behind a load balancer, proxy or tunnel."+ title={+ isTunnelEnabled+ ? 'Forced on while the SSH tunnel is enabled - a tunnel exposes a single address, so replica set discovery cannot be used.'+ : 'Connect directly to a single server, skipping replica set discovery. Useful when the server is behind a load balancer, proxy or tunnel.'+ }><InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} /></Tooltip>diff --git a/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsxindex 3ff58a1a..d753f510 100644--- a/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsx@@ -2,12 +2,18 @@ import { CopyOutlined, DownOutlined, InfoCircleOutlined, UpOutlined } from '@antimport { App, Button, Input, InputNumber, Select, Switch, Tooltip } from 'antd';import { useEffect, useState } from 'react';-import { type Database, databaseApi } from '../../../../entity/databases';+import {+ type Database,+ databaseApi,+ hasStoredSshTunnelSecrets,+ isSshTunnelReadyToTest,+} from '../../../../entity/databases';import { MySqlConnectionStringParser } from '../../../../entity/databases/model/mysql/MySqlConnectionStringParser';import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';import { ClipboardPasteModalComponent } from '../../../../shared/ui';+import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {database: Database;@@ -167,16 +173,24 @@ export const EditMySqlSpecificDataComponent = ({if (!editingDatabase) return null;+ const hasStoredSshSecrets = hasStoredSshTunnelSecrets(database.mysql?.sshTunnel, database.id);+let isAllFieldsFilled = true;if (!editingDatabase.mysql?.host) isAllFieldsFilled = false;if (!editingDatabase.mysql?.port) isAllFieldsFilled = false;if (!editingDatabase.mysql?.username) isAllFieldsFilled = false;if (!editingDatabase.id && !editingDatabase.mysql?.password) isAllFieldsFilled = false;if (!editingDatabase.mysql?.database) isAllFieldsFilled = false;+ if (!isSshTunnelReadyToTest(editingDatabase.mysql?.sshTunnel, hasStoredSshSecrets))+ isAllFieldsFilled = false;+ // Behind a bastion a loopback address names the database as the bastion sees it, so the hint+ // about reaching a local database would be wrong.+ const isTunnelEnabled = !!editingDatabase.mysql?.sshTunnel?.isEnabled;const isLocalhostDb =- editingDatabase.mysql?.host?.includes('localhost') ||- editingDatabase.mysql?.host?.includes('127.0.0.1');+ !isTunnelEnabled &&+ (editingDatabase.mysql?.host?.includes('localhost') ||+ editingDatabase.mysql?.host?.includes('127.0.0.1'));return (<div>@@ -314,6 +328,20 @@ export const EditMySqlSpecificDataComponent = ({</div>)}+ <EditSshTunnelComponent+ sshTunnel={editingDatabase.mysql?.sshTunnel}+ hasStoredSecrets={hasStoredSshSecrets}+ onChange={(sshTunnel) => {+ if (!editingDatabase.mysql) return;++ setEditingDatabase({+ ...editingDatabase,+ mysql: { ...editingDatabase.mysql, sshTunnel },+ });+ setIsConnectionTested(false);+ }}+ />+<div className="mb-3 flex w-full items-center"><div className="min-w-[150px]">Use HTTPS</div><Switchdiff --git a/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsxindex 1d33e071..390c6c05 100644--- a/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx@@ -7,12 +7,15 @@ import {PostgresSslMode,type PostgresqlLogicalDatabase,databaseApi,+ hasStoredSshTunnelSecrets,+ isSshTunnelReadyToTest,} from '../../../../entity/databases';import { ConnectionStringParser } from '../../../../entity/databases/model/postgresql/ConnectionStringParser';import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';import { ClipboardPasteModalComponent } from '../../../../shared/ui';+import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {database: Database;@@ -366,10 +369,17 @@ export const EditPostgreSqlLogicalSpecificDataComponent = ({if (!editingDatabase.id && !editingDatabase.postgresqlLogical?.password)isAllFieldsFilled = false;if (!editingDatabase.postgresqlLogical?.database) isAllFieldsFilled = false;+ if (!isSshTunnelReadyToTest(editingDatabase.postgresqlLogical?.sshTunnel, hasStoredSshSecrets))+ isAllFieldsFilled = false;++ const isTunnelEnabled = !!editingDatabase.postgresqlLogical?.sshTunnel?.isEnabled;+ // Behind a tunnel a loopback address means "on the bastion", which is the documented setup+ // rather than the mistake this hint warns about.const isLocalhostDb =- editingDatabase.postgresqlLogical?.host?.includes('localhost') ||- editingDatabase.postgresqlLogical?.host?.includes('127.0.0.1');+ !isTunnelEnabled &&+ (editingDatabase.postgresqlLogical?.host?.includes('localhost') ||+ editingDatabase.postgresqlLogical?.host?.includes('127.0.0.1'));const isSupabaseDb =editingDatabase.postgresqlLogical?.host?.includes('supabase') ||@@ -557,6 +567,20 @@ export const EditPostgreSqlLogicalSpecificDataComponent = ({</div>)}+ <EditSshTunnelComponent+ sshTunnel={editingDatabase.postgresqlLogical?.sshTunnel}+ hasStoredSecrets={hasStoredSshSecrets}+ onChange={(sshTunnel) => {+ if (!editingDatabase.postgresqlLogical) return;++ setEditingDatabase({+ ...editingDatabase,+ postgresqlLogical: { ...editingDatabase.postgresqlLogical, sshTunnel },+ });+ setIsConnectionTested(false);+ }}+ />+<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">SSL mode</div><Select@@ -844,6 +868,11 @@ export const EditPostgreSqlLogicalSpecificDataComponent = ({);};+ const hasStoredSshSecrets = hasStoredSshTunnelSecrets(+ database.postgresqlLogical?.sshTunnel,+ database.id,+ );+return (<div>{renderPgDumpForm()}diff --git a/frontend/src/features/databases/ui/edit/EditSshTunnelComponent.tsx b/frontend/src/features/databases/ui/edit/EditSshTunnelComponent.tsxnew file mode 100644index 00000000..83fece31--- /dev/null+++ b/frontend/src/features/databases/ui/edit/EditSshTunnelComponent.tsx@@ -0,0 +1,165 @@+import { InfoCircleOutlined } from '@ant-design/icons';+import { Button, Checkbox, Input, InputNumber, Tooltip } from 'antd';+import { useState } from 'react';++import {+ DEFAULT_SSH_PORT,+ type SshTunnelConfig,+ createEmptySshTunnelConfig,+} from '../../../../entity/databases';++interface Props {+ sshTunnel: SshTunnelConfig | undefined;+ hasStoredSecrets: boolean;+ onChange: (sshTunnel: SshTunnelConfig) => void;+}++export const EditSshTunnelComponent = ({ sshTunnel, hasStoredSecrets, onChange }: Props) => {+ const [isReplacingSecrets, setIsReplacingSecrets] = useState(false);++ const updateField = <Field extends keyof SshTunnelConfig>(+ field: Field,+ value: SshTunnelConfig[Field],+ ) => {+ onChange({ ...currentTunnel, [field]: value });+ };++ const startReplacingSecrets = () => {+ setIsReplacingSecrets(true);+ onChange({ ...currentTunnel, password: '', privateKey: '', privateKeyPassphrase: '' });+ };++ const renderCredentials = () => {+ if (hasStoredSecrets && !isReplacingSecrets) {+ return (+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH credentials</div>+ <div className="flex items-center">+ <span className="mr-3">*************</span>+ <Button size="small" onClick={startReplacingSecrets}>+ Replace+ </Button>+ </div>+ </div>+ );+ }++ return (+ <>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH password</div>+ <Input.Password+ value={currentTunnel.password}+ onChange={(e) => updateField('password', e.target.value)}+ size="small"+ className="max-w-[200px] grow"+ placeholder="Leave empty when using a key"+ autoComplete="off"+ data-1p-ignore+ data-lpignore="true"+ data-form-type="other"+ />+ </div>++ <div className="mb-1 flex w-full items-start">+ <div className="min-w-[150px]">SSH private key</div>+ <Input.TextArea+ value={currentTunnel.privateKey}+ onChange={(e) => updateField('privateKey', e.target.value)}+ size="small"+ className="max-w-[300px] grow"+ placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"+ autoSize={{ minRows: 2, maxRows: 5 }}+ />+ </div>++ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">Key passphrase</div>+ <Input.Password+ value={currentTunnel.privateKeyPassphrase}+ onChange={(e) => updateField('privateKeyPassphrase', e.target.value)}+ size="small"+ className="max-w-[200px] grow"+ placeholder="Only for an encrypted key"+ autoComplete="off"+ data-1p-ignore+ data-lpignore="true"+ data-form-type="other"+ />+ </div>+ </>+ );+ };++ const currentTunnel = sshTunnel ?? createEmptySshTunnelConfig();++ return (+ <>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]" />+ <Checkbox+ checked={currentTunnel.isEnabled}+ onChange={(e) => updateField('isEnabled', e.target.checked)}+ >+ <div className="flex items-center">+ <span>Connect through an SSH tunnel</span>+ <Tooltip+ className="cursor-pointer"+ title="For a database inside a closed network. Databasus connects to the SSH host below, and that host reaches the database using the host and port above."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </Checkbox>+ </div>++ {currentTunnel.isEnabled && (+ <>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH host</div>+ <Input+ value={currentTunnel.host}+ onChange={(e) => updateField('host', e.target.value)}+ size="small"+ className="max-w-[200px] grow"+ placeholder="bastion.example.com"+ />+ </div>++ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]" />+ <div className="text-xs text-gray-500">+ The database host above is resolved by the SSH host, not by Databasus. Use 127.0.0.1+ when the database runs on the SSH host itself.+ </div>+ </div>++ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH port</div>+ <InputNumber+ value={currentTunnel.port}+ onChange={(value) => updateField('port', value ?? DEFAULT_SSH_PORT)}+ size="small"+ className="max-w-[200px] grow"+ min={1}+ max={65535}+ />+ </div>++ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH username</div>+ <Input+ value={currentTunnel.username}+ onChange={(e) => updateField('username', e.target.value)}+ size="small"+ className="max-w-[200px] grow"+ placeholder="Enter SSH username"+ />+ </div>++ {renderCredentials()}+ </>+ )}+ </>+ );+};diff --git a/frontend/src/features/databases/ui/show/ShowMariaDbSpecificDataComponent.tsx b/frontend/src/features/databases/ui/show/ShowMariaDbSpecificDataComponent.tsxindex ed0ba26c..df9018a4 100644--- a/frontend/src/features/databases/ui/show/ShowMariaDbSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/show/ShowMariaDbSpecificDataComponent.tsx@@ -1,4 +1,5 @@import { type Database, MariadbVersion } from '../../../../entity/databases';+import { ShowSshTunnelComponent } from './ShowSshTunnelComponent';interface Props {database: Database;@@ -55,6 +56,7 @@ export const ShowMariaDbSpecificDataComponent = ({ database }: Props) => {<div className="min-w-[150px]">Use HTTPS</div><div>{database.mariadb?.isHttps ? 'Yes' : 'No'}</div></div>+ <ShowSshTunnelComponent sshTunnel={database.mariadb?.sshTunnel} />{database.mariadb?.isExcludeEvents && (<div className="mb-1 flex w-full items-center">diff --git a/frontend/src/features/databases/ui/show/ShowMongoDbSpecificDataComponent.tsx b/frontend/src/features/databases/ui/show/ShowMongoDbSpecificDataComponent.tsxindex d82c02a8..d31f1e14 100644--- a/frontend/src/features/databases/ui/show/ShowMongoDbSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/show/ShowMongoDbSpecificDataComponent.tsx@@ -1,4 +1,5 @@import { type Database } from '../../../../entity/databases';+import { ShowSshTunnelComponent } from './ShowSshTunnelComponent';interface Props {database: Database;@@ -36,6 +37,7 @@ export const ShowMongoDbSpecificDataComponent = ({ database }: Props) => {<div className="min-w-[150px]">Use HTTPS</div><div>{database.mongodb?.isHttps ? 'Yes' : 'No'}</div></div>+ <ShowSshTunnelComponent sshTunnel={database.mongodb?.sshTunnel} /><div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">CPU count</div>diff --git a/frontend/src/features/databases/ui/show/ShowMySqlSpecificDataComponent.tsx b/frontend/src/features/databases/ui/show/ShowMySqlSpecificDataComponent.tsxindex bb2438e1..00627369 100644--- a/frontend/src/features/databases/ui/show/ShowMySqlSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/show/ShowMySqlSpecificDataComponent.tsx@@ -1,4 +1,5 @@import { type Database, MysqlVersion } from '../../../../entity/databases';+import { ShowSshTunnelComponent } from './ShowSshTunnelComponent';interface Props {database: Database;@@ -48,6 +49,7 @@ export const ShowMySqlSpecificDataComponent = ({ database }: Props) => {<div className="min-w-[150px]">Use HTTPS</div><div>{database.mysql?.isHttps ? 'Yes' : 'No'}</div></div>+ <ShowSshTunnelComponent sshTunnel={database.mysql?.sshTunnel} />{!!database.mysql?.excludeTables?.length && (<div className="mb-1 flex w-full items-center">diff --git a/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsxindex 903dbaae..9a616ed3 100644--- a/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/show/ShowPostgreSqlLogicalSpecificDataComponent.tsx@@ -1,4 +1,5 @@import { type Database, PostgresSslMode, PostgresqlVersion } from '../../../../entity/databases';+import { ShowSshTunnelComponent } from './ShowSshTunnelComponent';interface Props {database: Database;@@ -70,6 +71,7 @@ export const ShowPostgreSqlLogicalSpecificDataComponent = ({ database }: Props)<div>*************</div></div>)}+ <ShowSshTunnelComponent sshTunnel={database.postgresqlLogical?.sshTunnel} />{!!database.postgresqlLogical?.includeSchemas?.length && (<div className="mb-1 flex w-full items-center">diff --git a/frontend/src/features/databases/ui/show/ShowSshTunnelComponent.tsx b/frontend/src/features/databases/ui/show/ShowSshTunnelComponent.tsxnew file mode 100644index 00000000..1d220f6d--- /dev/null+++ b/frontend/src/features/databases/ui/show/ShowSshTunnelComponent.tsx@@ -0,0 +1,33 @@+import type { SshTunnelConfig } from '../../../../entity/databases';++interface Props {+ sshTunnel: SshTunnelConfig | undefined;+}++export const ShowSshTunnelComponent = ({ sshTunnel }: Props) => {+ if (!sshTunnel?.isEnabled) return null;++ return (+ <>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH host</div>+ <div>{sshTunnel.host}</div>+ </div>++ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH port</div>+ <div>{sshTunnel.port}</div>+ </div>++ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH username</div>+ <div>{sshTunnel.username}</div>+ </div>++ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">SSH credentials</div>+ <div>*************</div>+ </div>+ </>+ );+};