PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (ssh): Add SSH tunneling for physical backups
Rostislav Dugin73ff380f9cb9
diff --git a/backend/internal/features/backups/backups/backuping/physical/backuper.go b/backend/internal/features/backups/backups/backuping/physical/backuper.goindex 61678d41..ebe849b4 100644--- a/backend/internal/features/backups/backups/backuping/physical/backuper.go+++ b/backend/internal/features/backups/backups/backuping/physical/backuper.go@@ -83,14 +83,16 @@ func (b *PhysicalBackuper) runFullBackup(fullBackup *physical_models.PhysicalFullBackup,isCallNotifier bool,) {- backupCtx, ok := b.loadBackupContext(logger, fullBackup.DatabaseID)+ backupCtx, ok := b.openBackupContext(logger, fullBackup.DatabaseID)if !ok {b.finalizeFullAsError(fullBackup, physical_enums.PhysicalBackupErrorPgBasebackupFailed,- "failed to load backup context")+ "failed to open backup context")return}+ defer backupCtx.Close()+ctx, cancel := context.WithCancel(context.Background())b.taskCancelManager.RegisterTask(fullBackup.ID, cancel)defer b.taskCancelManager.UnregisterTask(fullBackup.ID)@@ -150,14 +152,16 @@ func (b *PhysicalBackuper) runIncrementalBackup(incrBackup *physical_models.PhysicalIncrementalBackup,isCallNotifier bool,) {- backupCtx, ok := b.loadBackupContext(logger, incrBackup.DatabaseID)+ backupCtx, ok := b.openBackupContext(logger, incrBackup.DatabaseID)if !ok {b.finalizeIncrAsError(incrBackup, physical_enums.PhysicalBackupErrorPgBasebackupFailed,- "failed to load backup context")+ "failed to open backup context")return}+ defer backupCtx.Close()+parentRef, err := b.resolveParentManifest(incrBackup)if err != nil {logger.Error("failed to resolve parent manifest", "error", err)@@ -223,7 +227,7 @@ func (b *PhysicalBackuper) runIncrementalBackup(}}-func (b *PhysicalBackuper) loadBackupContext(+func (b *PhysicalBackuper) openBackupContext(logger *slog.Logger,databaseID uuid.UUID,) (*backupContext, bool) {@@ -272,7 +276,29 @@ func (b *PhysicalBackuper) loadBackupContext(masterKey = key}- return &backupContext{cfg, db, storage, masterKey}, true+ // Opened last, because a bail-out after this point would strand a live SSH session and its+ // listener: the caller only gets something to Close once the context is fully built.+ tunnelCtx, cancelTunnelOpen := context.WithTimeout(context.Background(), bastionOpenTimeout)+ defer cancelTunnelOpen()++ tunneledDatabase, err := databases.OpenTunnel(tunnelCtx, databases.OpenTunnelSpec{+ Database: db,+ Logger: logger,+ Encryptor: b.fieldEncryptor,+ })+ if err != nil {+ logger.Error("failed to open ssh tunnel to the source cluster", "error", err)++ return nil, false+ }++ return &backupContext{+ Config: cfg,+ Database: tunneledDatabase.GetDatabaseThroughTunnel(),+ Storage: storage,+ MasterKey: masterKey,+ tunnel: tunneledDatabase,+ }, true}func (b *PhysicalBackuper) resolveParentManifest(diff --git a/backend/internal/features/backups/backups/backuping/physical/backuper_test.go b/backend/internal/features/backups/backups/backuping/physical/backuper_test.goindex a00e462c..84d94713 100644--- a/backend/internal/features/backups/backups/backuping/physical/backuper_test.go+++ b/backend/internal/features/backups/backups/backuping/physical/backuper_test.go@@ -465,21 +465,23 @@ func Test_SendFullBackupNotification_WhenEnabled_FansOutToAllNotifiers(t *testinassert.Equal(t, notifier_models.NotificationTypeBackupSuccess, sender.sentNotifications[0].Notification.Type)}-func Test_LoadBackupContext_WhenNotEncrypted_LeavesMasterKeyEmpty(t *testing.T) {+func Test_OpenBackupContext_WhenNotEncrypted_LeavesMasterKeyEmpty(t *testing.T) {prereqs := seedBackupPrereqs(t)backuper := CreateTestPhysicalBackuper(nil)- backupCtx, ok := backuper.loadBackupContext(logger.GetLogger(), prereqs.DB.ID)+ backupCtx, ok := backuper.openBackupContext(logger.GetLogger(), prereqs.DB.ID)require.True(t, ok)require.NotNil(t, backupCtx)+ defer backupCtx.Close()+assert.Empty(t, backupCtx.MasterKey)assert.NotNil(t, backupCtx.Config)assert.NotNil(t, backupCtx.Database)assert.NotNil(t, backupCtx.Storage)}-func Test_LoadBackupContext_WhenEncrypted_PopulatesMasterKey(t *testing.T) {+func Test_OpenBackupContext_WhenEncrypted_PopulatesMasterKey(t *testing.T) {prereqs := seedBackupPrereqs(t)backuper := CreateTestPhysicalBackuper(nil)@@ -487,14 +489,16 @@ func Test_LoadBackupContext_WhenEncrypted_PopulatesMasterKey(t *testing.T) {_, err := backups_config_physical.GetBackupConfigService().SaveBackupConfig(prereqs.Config)require.NoError(t, err)- backupCtx, ok := backuper.loadBackupContext(logger.GetLogger(), prereqs.DB.ID)+ backupCtx, ok := backuper.openBackupContext(logger.GetLogger(), prereqs.DB.ID)require.True(t, ok)require.NotNil(t, backupCtx)+ defer backupCtx.Close()+assert.NotEmpty(t, backupCtx.MasterKey)}-func Test_LoadBackupContext_WhenConfigHasNoStorageID_ReturnsNotOk(t *testing.T) {+func Test_OpenBackupContext_WhenConfigHasNoStorageID_ReturnsNotOk(t *testing.T) {prereqs := seedBackupPrereqs(t)backuper := CreateTestPhysicalBackuper(nil)@@ -504,7 +508,7 @@ func Test_LoadBackupContext_WhenConfigHasNoStorageID_ReturnsNotOk(t *testing.T)_, err := backups_config_physical.GetBackupConfigService().SaveBackupConfig(prereqs.Config)require.NoError(t, err)- _, ok := backuper.loadBackupContext(logger.GetLogger(), prereqs.DB.ID)+ _, ok := backuper.openBackupContext(logger.GetLogger(), prereqs.DB.ID)assert.False(t, ok)}diff --git a/backend/internal/features/backups/backups/backuping/physical/constants.go b/backend/internal/features/backups/backups/backuping/physical/constants.goindex d714187e..db1496b1 100644--- a/backend/internal/features/backups/backups/backuping/physical/constants.go+++ b/backend/internal/features/backups/backups/backuping/physical/constants.go@@ -3,6 +3,11 @@ package backuping_physicalimport "time"const (+ // Bounds only the first dial and handshake through the bastion — the forwarder then lives until+ // Close, which for a WAL streamer is weeks. Generous because a backup that cannot start is worse+ // than one that starts slowly, and because the alternative to waiting is a missed cadence.+ bastionOpenTimeout = 30 * time.Second+// Scheduler tick and recovery sweep share this cadence. Each tick is a handful// of cheap indexed queries per enabled DB, so a 1 s cadence keeps out-of-cadence// backup triggers and crash recovery near-immediate without meaningful loaddiff --git a/backend/internal/features/backups/backups/backuping/physical/dto.go b/backend/internal/features/backups/backups/backuping/physical/dto.goindex c5e7d0d6..9fdfbee3 100644--- a/backend/internal/features/backups/backups/backuping/physical/dto.go+++ b/backend/internal/features/backups/backups/backuping/physical/dto.go@@ -12,10 +12,19 @@ import ()type backupContext struct {- Config *backups_config_physical.PhysicalBackupConfig- Database *databases.Database+ Config *backups_config_physical.PhysicalBackupConfig++ // The copy reached through the bastion, so everything the run touches — the size probe, the+ // executor's SourceDB, pg_basebackup — dials the forwarded port off one SSH session.+ Database *databases.Database+Storage *storages.StorageMasterKey string+ tunnel *databases.TunneledDatabase+}++func (c *backupContext) Close() {+ c.tunnel.Close()}// chainCandidate pairs a non-extendable chain with its end timestamp so passesdiff --git a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.goindex 882a2a72..3a232359 100644--- a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go+++ b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go@@ -236,6 +236,23 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(return}+ // One SSH session for the whole streamer: pg_receivewal plus the slot-LSN, lag and rotation+ // loops would otherwise handshake with the bastion several times a minute, forever.+ tunnelCtx, cancelTunnelOpen := context.WithTimeout(context.Background(), bastionOpenTimeout)+ defer cancelTunnelOpen()++ tunneledDatabase, err := postgresql_physical.OpenTunnel(tunnelCtx, postgresql_physical.OpenTunnelSpec{+ Database: db.PostgresqlPhysical,+ Logger: logger,+ Encryptor: s.fieldEncryptor,+ })+ if err != nil {+ logger.Error("wal supervisor: failed to open ssh tunnel to the source cluster", "error", err)+ s.releaseClaim(logger, backupConfig.DatabaseID)++ return+ }+// Derive from the supervisor's run ctx so a process shutdown cancels every// streamer; the per-DB cancel (registered with TaskCancelManager + stored on// runningStreamer) handles targeted teardown on disable / demote / db-remove.@@ -254,7 +271,8 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(supervisor := postgresql_executor.NewWalStreamSupervisor(postgresql_executor.WalStreamSpec{DatabaseID: db.ID,- SourceDB: db.PostgresqlPhysical,+ SourceDB: tunneledDatabase.GetDatabaseThroughTunnel(),+ IsBastionReachable: tunneledDatabase.IsBastionReachable,StorageID: storage.ID,Storage: storage,Encryption: backupConfig.Encryption,@@ -280,6 +298,7 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(go func() {defer close(done)+ defer tunneledDatabase.Close()defer s.taskCancelManager.UnregisterTask(db.ID)defer s.removeWatchDirIfRequested(logger, streamer)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot.goindex 2d312b4a..9edca56e 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot.go@@ -28,6 +28,10 @@ const (// hang the boot.startupCleanupTimeout = 5 * time.Second+ // The backup has already finished either way, so the second attempt at dropping+ // the slot must not hold its result hostage to an unreachable source.+ slotDropRetryTimeout = 10 * time.Second+// startupCleanupConcurrency bounds parallel cleanup. With 100+ DBs// configured, unbounded fan-out would saturate Databasus's connection// pool. 10 keeps total boot delay near the slowest 10% of sources.@@ -73,11 +77,18 @@ func WithBackupSlot(defer func() {// Background context so defer runs even when ctx is cancelled.- if dropErr := dropBackupSlotIfExists(context.Background(), conn, slotName); dropErr != nil {+ if dropErr := dropBackupSlotIfExists(context.Background(), conn, slotName); dropErr == nil {+ return+ }++ // The held connection is the first casualty of a network break, and a bastion in front of the+ // source makes those routine. Leaving the slot pins WAL on the source until the next backup+ // runs, which on a weekly full is a week of retained segments.+ if retryErr := dropBackupSlotOverFreshConn(sourceDB, encryptor, slotName); retryErr != nil {logger.Warn("post-backup slot drop failed; will be recovered by next backup or startup cleanup","slot_name", slotName,- "error", dropErr,+ "error", retryErr,)}}()@@ -85,6 +96,23 @@ func WithBackupSlot(return fn()}+func dropBackupSlotOverFreshConn(+ sourceDB *postgresql_physical.PostgresqlPhysicalDatabase,+ encryptor encryption.FieldEncryptor,+ slotName string,+) error {+ ctx, cancel := context.WithTimeout(context.Background(), slotDropRetryTimeout)+ defer cancel()++ conn, err := sourceDB.OpenInspectionConn(ctx, encryptor)+ if err != nil {+ return fmt.Errorf("reopen conn to drop backup slot %q: %w", slotName, err)+ }+ defer func() { _ = conn.Close(context.Background()) }()++ return dropBackupSlotIfExists(ctx, conn, slotName)+}+func dropBackupSlotIfExists(ctx context.Context, conn *pgx.Conn, slotName string) error {_, err := conn.Exec(ctx,`SELECT pg_drop_replication_slot(slot_name)@@ -163,7 +191,21 @@ func RunStartupCleanup(cleanupCtx, cancel := context.WithTimeout(ctx, startupCleanupTimeout)defer cancel()- conn, err := d.OpenInspectionConn(cleanupCtx, encryptor)+ // A bastioned source has to fit its SSH handshake into the same budget. Missing it is a+ // skip, not a leak: WithBackupSlot drops any survivor before it creates the next one.+ tunneledDatabase, err := postgresql_physical.OpenTunnel(cleanupCtx, postgresql_physical.OpenTunnelSpec{+ Database: d,+ Logger: scopedLogger,+ Encryptor: encryptor,+ })+ if err != nil {+ scopedLogger.Warn("startup slot cleanup: skip unreachable bastion", "error", err)+ skippedCount.Store(databaseID, struct{}{})+ return+ }+ defer tunneledDatabase.Close()++ conn, err := tunneledDatabase.GetDatabaseThroughTunnel().OpenInspectionConn(cleanupCtx, encryptor)if err != nil {scopedLogger.Warn("startup slot cleanup: skip unreachable source", "error", err)skippedCount.Store(databaseID, struct{}{})diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.goindex 3f982045..7868a970 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.go@@ -247,6 +247,31 @@ func Test_RunStartupCleanup_DropsOrphanSlots(t *testing.T) {"RunStartupCleanup must drop the per-backup orphan slot")}+// Boot cleanup gets one 5s budget per database, SSH handshake included, and a bastioned source that+// misses it is skipped. What must not happen is missing it because the sweep never tried the tunnel+// at all and dialled an address only the bastion can see.+func Test_RunStartupCleanup_WhenTheSourceIsBehindABastion_DropsOrphanSlots(t *testing.T) {+ fixture := postgresql_executor.SetupPhysicalDBForBackupBehindSshBastion(t)++ slotName := postgresql_executor.SlotName(fixture.DB.PostgresqlPhysical.ID)+ adminConn := postgresql_executor.OpenAdminConn(t, fixture)++ _, err := adminConn.Exec(context.Background(),+ "SELECT pg_create_physical_replication_slot($1, true)", slotName)+ require.NoError(t, err, "pre-create orphan slot")++ t.Cleanup(func() {+ _, _ = adminConn.Exec(context.Background(),+ `SELECT pg_drop_replication_slot(slot_name)+ FROM pg_replication_slots WHERE slot_name = $1`, slotName)+ })++ require.NoError(t, postgresql_executor.RunStartupCleanup(t.Context(), logger.GetLogger(), neverProtected))++ assert.False(t, postgresql_executor.SlotExists(t, adminConn, slotName),+ "the sweep must reach a bastioned source through the tunnel")+}+func Test_RunStartupCleanup_PreservesStreamerSlot(t *testing.T) {fixture := postgresql_executor.SetupPhysicalDBForBackup(t)@@ -311,12 +336,10 @@ func Test_RunStartupCleanup_SkipsUnreachableSource_DoesNotFail(t *testing.T) {"unreachable source must be logged + skipped, not surfaced as a failure")}-// Test_RunStartupCleanup_RecoversOrphanWhenSourceBecomesReachable covers the-// "source DB was down" path: WithBackupSlot's defer drop reuses the same connection,-// so when the source went down mid-backup the drop could not run and the slot was-// left behind. The first boot still cannot reach the source (skip, slot survives);-// the next boot after the source returns must drop the orphan. Without this, a-// transient source outage during a backup would orphan a slot until the next backup.+// The "source DB was down" path, where even the deferred drop's retry on a fresh connection cannot+// get through: the slot is left behind. The first boot still cannot reach the source (skip, slot+// survives); the next boot after the source returns must drop the orphan. Without this, an outage+// spanning the whole backup would orphan a slot until the next one runs.func Test_RunStartupCleanup_RecoversOrphanWhenSourceBecomesReachable(t *testing.T) {fixture := postgresql_executor.SetupPhysicalDBForBackup(t)@@ -839,3 +862,34 @@ func Test_BackupSlot_DroppedAfterCancelledMidRun(t *testing.T) {assert.False(t, postgresql_executor.SlotExists(t, adminConn, slotName),"slot must be dropped after cancellation (defer uses context.Background() so it survives ctx cancel)")}++// A bastion in front of the source makes a mid-backup connection loss routine, and the connection+// that dies is the very one holding the slot open. Without a retry the slot survives until the next+// backup runs, pinning WAL on the source for a whole full-backup cadence.+func Test_WithBackupSlot_WhenTheHeldConnectionDied_DropsTheSlotOverAFreshConnection(t *testing.T) {+ fixture := postgresql_executor.SetupPhysicalDBForBackup(t)++ slotName := postgresql_executor.SlotName(fixture.DB.PostgresqlPhysical.ID)+ adminConn := postgresql_executor.OpenAdminConn(t, fixture)++ err := postgresql_executor.WithBackupSlot(+ t.Context(),+ fixture.DB.PostgresqlPhysical,+ encryption.GetFieldEncryptor(),+ logger.GetLogger(),+ func() error {+ require.True(t, postgresql_executor.SlotExists(t, adminConn, slotName),+ "the slot must be held while the backup runs")++ _, terminateErr := adminConn.Exec(context.Background(),+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = 'postgres' AND pid <> pg_backend_pid()`)++ return terminateErr+ },+ )+ require.NoError(t, err)++ assert.False(t, postgresql_executor.SlotExists(t, adminConn, slotName),+ "the deferred drop must reopen a connection rather than give up on the dead one")+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/pg_basebackup.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/pg_basebackup.goindex 0eb7ce6d..46630429 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/pg_basebackup.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/pg_basebackup.go@@ -90,6 +90,8 @@ func newPgBasebackupCommand(cmd := exec.CommandContext(ctx, pgBin, args...)+ // -h above stays the real host so the certificate and .pgpass still match; PGHOSTADDR is what+ // redirects libpq at the tunnel.cmd.Env = append(os.Environ(),"PGPASSFILE="+creds.PgpassPath,"PGCLIENTENCODING=UTF8",@@ -97,6 +99,7 @@ func newPgBasebackupCommand("LC_ALL=C.UTF-8","LANG=C.UTF-8",)+ cmd.Env = append(cmd.Env, postgresql_shared.GetPgHostAddrEnv(sourceDB.CredentialSpec())...)sslMode := sourceDB.SslModeif sslMode == "" {diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/pg_basebackup_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/pg_basebackup_test.gonew file mode 100644index 00000000..cd0cb9e7--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/pg_basebackup_test.go@@ -0,0 +1,85 @@+package usecases_physical_postgresql++import (+ "slices"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"+ postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared"+ "databasus-backend/internal/features/sshtunnel"+)++const (+ tunneledSourceHost = "cluster.internal"+ forwardedLocalPort = 41000+)++// The copy handed out by OpenTunnel, as the CLI paths receive it: the port already points at the+// forwarder while Host still names the cluster.+func tunneledSourceDatabase() *postgresql_physical.PostgresqlPhysicalDatabase {+ return &postgresql_physical.PostgresqlPhysicalDatabase{+ Host: tunneledSourceHost,+ Port: forwardedLocalPort,+ Username: "replicator",+ ReplicationSlotName: "slot",+ LocalTunnelEndpoint: &sshtunnel.Endpoint{Host: "127.0.0.1", Port: forwardedLocalPort},+ }+}++// libpq connects to hostaddr while still matching the certificate and .pgpass against host, so+// rewriting -h would break sslmode=verify-full and the password lookup at once.+func Test_NewPgBasebackupCommand_WhenTunneled_SendsPgHostAddrAndKeepsTheRealHostFlag(t *testing.T) {+ cmd, err := newPgBasebackupCommand(+ t.Context(),+ "sh",+ tunneledSourceDatabase(),+ &postgresql_shared.CredentialTempFiles{PgpassPath: "/tmp/pgpass"},+ "label",+ physical_enums.PhysicalBackupCompressionNone,+ "",+ )+ require.NoError(t, err)++ assert.Contains(t, cmd.Env, "PGHOSTADDR=127.0.0.1")+ assertHostFlagIsTheRealCluster(t, cmd.Args)+}++func Test_NewPgBasebackupCommand_WithoutATunnel_SendsNoPgHostAddr(t *testing.T) {+ sourceDB := tunneledSourceDatabase()+ sourceDB.LocalTunnelEndpoint = nil++ cmd, err := newPgBasebackupCommand(+ t.Context(),+ "sh",+ sourceDB,+ &postgresql_shared.CredentialTempFiles{PgpassPath: "/tmp/pgpass"},+ "label",+ physical_enums.PhysicalBackupCompressionNone,+ "",+ )+ require.NoError(t, err)++ assertNoPgHostAddr(t, cmd.Env)+}++func assertHostFlagIsTheRealCluster(t *testing.T, args []string) {+ t.Helper()++ hostFlagIndex := slices.Index(args, "-h")+ require.NotEqual(t, -1, hostFlagIndex, "the tools still address the cluster by name")+ require.Less(t, hostFlagIndex+1, len(args))+ assert.Equal(t, tunneledSourceHost, args[hostFlagIndex+1])+}++func assertNoPgHostAddr(t *testing.T, env []string) {+ t.Helper()++ for _, variable := range env {+ assert.NotContains(t, variable, "PGHOSTADDR=",+ "a direct connection must not be redirected anywhere")+ }+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process.goindex 95ce3905..24baaf02 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process.go@@ -139,7 +139,7 @@ func (s *WalStreamSupervisor) spawnAndSupervise(}if isFatalReceivewalError(stderrText) {- logger.Error("pg_receivewal exited with a non-retryable error; marking streamer for reassignment",+ logger.Error("pg_receivewal exited with a non-retryable error","error", waitErr, "stderr", truncateStderr(stderrText))return receiverRunResult{@@ -213,6 +213,8 @@ func newReceivewalCommand(ctx context.Context, spec receivewalCommandSpec) (*execmd := exec.CommandContext(ctx, spec.PgBin, args...)+ // -h above stays the real host so the certificate and .pgpass still match; PGHOSTADDR is what+ // redirects libpq at the tunnel.cmd.Env = append(os.Environ(),"PGPASSFILE="+spec.Creds.PgpassPath,"PGAPPNAME="+receivewalApplicationName(spec.SourceDB),@@ -221,6 +223,7 @@ func newReceivewalCommand(ctx context.Context, spec receivewalCommandSpec) (*exe"LC_ALL=C.UTF-8","LANG=C.UTF-8",)+ cmd.Env = append(cmd.Env, postgresql_shared.GetPgHostAddrEnv(spec.SourceDB.CredentialSpec())...)sslMode := spec.SourceDB.SslModeif sslMode == "" {diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process_test.goindex a888dd0f..8fda6fd1 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/receivewal_process_test.go@@ -79,3 +79,35 @@ func Test_IsResumeMismatchError_WhenTransientStderr_ReturnsFalse(t *testing.T) {require.False(t, isResumeMismatchError([]byte(stderr)), stderr)}}++// The days-long process is the one the forwarder's fixed local port exists for, so its address has+// to arrive the same way pg_basebackup's does: -h keeps the cluster name, PGHOSTADDR does the work.+func Test_NewReceivewalCommand_WhenTunneled_SendsPgHostAddrAndKeepsTheRealHostFlag(t *testing.T) {+ cmd, err := newReceivewalCommand(t.Context(), receivewalCommandSpec{+ PgBin: "sh",+ SourceDB: tunneledSourceDatabase(),+ Creds: &postgresql_shared.CredentialTempFiles{PgpassPath: "/tmp/pgpass"},+ WatchDir: t.TempDir(),+ SlotName: "slot",+ })+ require.NoError(t, err)++ require.Contains(t, cmd.Env, "PGHOSTADDR=127.0.0.1")+ assertHostFlagIsTheRealCluster(t, cmd.Args)+}++func Test_NewReceivewalCommand_WithoutATunnel_SendsNoPgHostAddr(t *testing.T) {+ sourceDB := tunneledSourceDatabase()+ sourceDB.LocalTunnelEndpoint = nil++ cmd, err := newReceivewalCommand(t.Context(), receivewalCommandSpec{+ PgBin: "sh",+ SourceDB: sourceDB,+ Creds: &postgresql_shared.CredentialTempFiles{PgpassPath: "/tmp/pgpass"},+ WatchDir: t.TempDir(),+ SlotName: "slot",+ })+ require.NoError(t, err)++ assertNoPgHostAddr(t, cmd.Env)+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener.goindex 1cd2d3eb..8ca9dc05 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener.go@@ -8,6 +8,7 @@ import ("github.com/google/uuid""databasus-backend/internal/features/databases"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical""databasus-backend/internal/util/encryption")@@ -64,27 +65,54 @@ func (l *PhysicalSlotCleanupListener) OnBeforeDatabaseRemove(databaseID uuid.UUIctx, cancel := context.WithTimeout(context.Background(), slotCleanupDeadline)defer cancel()- conn, err := database.PostgresqlPhysical.OpenInspectionConn(ctx, l.fieldEncryptor)- if err != nil {- logger.Warn("physical slot cleanup: source PG unreachable, leaving slots orphaned", "error", err)-- return nil- }- defer func() { _ = conn.Close(context.Background()) }()-// The per-backup slot is keyed by the PostgresqlPhysical ID (see// WithBackupSlot / RunStartupCleanup), NOT the parent Database ID — the two are// distinct UUIDs. Using databaseID here would drop a name that never existed and// leave the real slot orphaned forever (the DB row is about to be deleted, so// RunStartupCleanup can never recover it).slotName := SlotName(database.PostgresqlPhysical.ID)+ walSlotName := database.PostgresqlPhysical.ReplicationSlotName++ tunneledDatabase, err := postgresql_physical.OpenTunnel(ctx, postgresql_physical.OpenTunnelSpec{+ Database: database.PostgresqlPhysical,+ Logger: logger,+ Encryptor: l.fieldEncryptor,+ })+ if err != nil {+ // Both names go into the message: the row is about to disappear, and with it any record of+ // which cluster to go looking on, so this line is the operator's only handle on them.+ logger.Warn("physical slot cleanup: bastion unreachable, leaving slots orphaned",+ "slot_name", slotName,+ "wal_slot_name", walSlotName,+ "error", err,+ )++ return nil+ }++ defer tunneledDatabase.Close()++ sourceDatabase := tunneledDatabase.GetDatabaseThroughTunnel()++ conn, err := sourceDatabase.OpenInspectionConn(ctx, l.fieldEncryptor)+ if err != nil {+ logger.Warn("physical slot cleanup: source PG unreachable, leaving slots orphaned",+ "slot_name", slotName,+ "wal_slot_name", walSlotName,+ "error", err,+ )++ return nil+ }+ defer func() { _ = conn.Close(context.Background()) }()+if dropErr := dropBackupSlotIfExists(ctx, conn, slotName); dropErr != nil {logger.Warn("physical slot cleanup: per-backup slot drop failed", "slot_name", slotName, "error", dropErr)}- if dropErr := database.PostgresqlPhysical.DropWalSlotForRemoval(ctx, logger, l.fieldEncryptor); dropErr != nil {+ if dropErr := sourceDatabase.DropWalSlotForRemoval(ctx, logger, l.fieldEncryptor); dropErr != nil {logger.Warn("physical slot cleanup: WAL streamer slot drop failed",- "slot_name", database.PostgresqlPhysical.ReplicationSlotName,+ "slot_name", walSlotName,"error", dropErr,)}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.goindex 44fa2d41..02560851 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.go@@ -15,12 +15,11 @@ import ("databasus-backend/internal/util/logger")-// Test_OnBeforeDatabaseRemove_DropsBothPerBackupAndStreamerSlots is the only-// coverage for the database-removal drop site — the sole place the long-lived-// streamer slot is removed. It also pins that the per-backup slot is keyed by the-// PostgresqlPhysical ID (not the parent Database ID): the two are distinct UUIDs,-// and computing the wrong one would silently orphan the slot forever, since the DB-// row is deleted right after and RunStartupCleanup only scans existing rows.+// The only coverage for the database-removal drop site — the sole place the long-lived streamer slot+// is removed. It also pins that the per-backup slot is keyed by the PostgresqlPhysical ID (not the+// parent Database ID): the two are distinct UUIDs, and computing the wrong one would silently orphan+// the slot forever, since the DB row is deleted right after and RunStartupCleanup only scans+// existing rows.func Test_OnBeforeDatabaseRemove_DropsBothPerBackupAndStreamerSlots(t *testing.T) {fixture := postgresql_executor.SetupPhysicalDBForBackup(t)@@ -68,11 +67,51 @@ func Test_OnBeforeDatabaseRemove_DropsBothPerBackupAndStreamerSlots(t *testing.T"WAL streamer slot must be dropped on DB removal")}-// Test_OnBeforeDatabaseRemove_WhenSourceUnreachable_DoesNotBlockRemoval pins the-// documented degraded path: an unreachable source must not fail the metadata-// delete (the listener logs + returns nil). This is the known G5 limitation — the-// slots stay orphaned on the unreachable source — captured so the behavior is-// intentional, not accidental.+// Removal is the only drop site with no second chance: the row goes away with it, and with it any+// record of which cluster to go looking on. A listener that dialled the source directly would never+// reach a bastioned one, and both slots would pin WAL on the customer's master forever.+func Test_OnBeforeDatabaseRemove_WhenTheSourceIsBehindABastion_DropsBothPerBackupAndStreamerSlots(+ t *testing.T,+) {+ fixture := postgresql_executor.SetupPhysicalDBForBackupBehindSshBastion(t)++ adminConn := postgresql_executor.OpenAdminConn(t, fixture)++ perBackupSlot := postgresql_executor.SlotName(fixture.DB.PostgresqlPhysical.ID)+ streamerSlot := fixture.DB.PostgresqlPhysical.ReplicationSlotName+ require.NotEmpty(t, streamerSlot, "streamer slot name should be populated by BeforeCreate")++ for _, slotName := range []string{perBackupSlot, streamerSlot} {+ _, err := adminConn.Exec(context.Background(),+ "SELECT pg_create_physical_replication_slot($1, true)", slotName)+ require.NoError(t, err, "pre-create slot %s", slotName)+ }++ // Defensive: if the listener fails to drop either slot, don't leak it into the+ // cluster (max_replication_slots is finite).+ t.Cleanup(func() {+ _, _ = adminConn.Exec(context.Background(),+ `SELECT pg_drop_replication_slot(slot_name)+ FROM pg_replication_slots WHERE slot_name = ANY($1)`,+ []string{perBackupSlot, streamerSlot})+ })++ listener := postgresql_executor.NewPhysicalSlotCleanupListener(+ databases.GetDatabaseService(),+ encryption.GetFieldEncryptor(),+ logger.GetLogger(),+ )++ require.NoError(t, listener.OnBeforeDatabaseRemove(fixture.DB.ID))++ assert.False(t, postgresql_executor.SlotExists(t, adminConn, perBackupSlot),+ "per-backup slot must be dropped through the tunnel on DB removal")+ assert.False(t, postgresql_executor.SlotExists(t, adminConn, streamerSlot),+ "WAL streamer slot must be dropped through the tunnel on DB removal")+}++// The slots stay orphaned on a source we cannot reach — accepted so a dead source can never block+// the metadata delete.func Test_OnBeforeDatabaseRemove_WhenSourceUnreachable_DoesNotBlockRemoval(t *testing.T) {fixture := postgresql_executor.SetupPhysicalDBForBackup(t)@@ -89,10 +128,9 @@ func Test_OnBeforeDatabaseRemove_WhenSourceUnreachable_DoesNotBlockRemoval(t *te"unreachable source must be logged + skipped, never block the metadata delete")}-// Test_DropWalSlot_WhenStreamerSlotActive_RefusesAndKeepsSlot pins the safety-// guard the removal listener relies on: DropWalSlot must refuse to drop a slot a-// consumer (our pg_receivewal) still holds, rather than terminate the session —-// dropping an active slot would crash the live streamer.+// The safety guard the removal listener relies on: DropWalSlot must refuse to drop a slot a consumer+// (our pg_receivewal) still holds, rather than terminate the session — dropping an active slot would+// crash the live streamer.func Test_DropWalSlot_WhenStreamerSlotActive_RefusesAndKeepsSlot(t *testing.T) {fixture := postgresql_executor.SetupPhysicalDBForBackup(t)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.goindex d0e3da0c..07531399 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.go@@ -36,6 +36,8 @@ import ("databasus-backend/internal/storage""databasus-backend/internal/util/encryption""databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/testing/bastion"+ "databasus-backend/internal/util/testing/containers""databasus-backend/internal/util/walmath")@@ -170,6 +172,33 @@ func SetupPhysicalDBForScheduledBackupVersion(})}+func SetupPhysicalDBFixtureWithTunnel(+ t *testing.T,+ spec databases.PhysicalTestDatabaseSpec,+) *PhysicalDBFixture {+ t.Helper()++ return wirePhysicalDBFixture(t, func(workspaceID uuid.UUID, notifier *notifiers.Notifier) *databases.Database {+ return databases.CreateTestPhysicalPostgresDatabaseWithTunnel(spec, workspaceID, notifier)+ })+}++// The source publishes no port, so every connection a test on this fixture makes has to go through+// the bastion — a direct route would keep it green after the tunnel stopped being used.+func SetupPhysicalDBForBackupBehindSshBastion(t *testing.T) *PhysicalDBFixture {+ t.Helper()++ topology := containers.StartPhysicalPostgresBehindSshBastion(t, "postgres:17")++ return SetupPhysicalDBFixtureWithTunnel(t, databases.PhysicalTestDatabaseSpec{+ Host: topology.Database.Host,+ Port: topology.Database.Port,+ VersionTag: "17",+ BackupType: postgresql_physical.BackupTypeFullIncrementalAndWalStream,+ SshTunnel: bastion.GetTunnelConfig(topology),+ })+}+// wirePhysicalDBFixture provisions the scaffolding every physical fixture needs —// workspace, storage, notifier, the source DB (via createDB), populated data, and// the persisted system_identifier — returning it with backups still disabled and@@ -205,7 +234,18 @@ func wirePhysicalDBFixture(encryptor := encryption.GetFieldEncryptor()log := logger.GetLogger()- require.NoError(t, db.PostgresqlPhysical.PopulateDbData(log, encryptor))+ // Through the tunnel, exactly as the database service does it, so a bastioned fixture reaches its+ // source and the discovered identity is carried back onto the row that gets persisted below.+ tunneledDatabase, err := postgresql_physical.OpenTunnel(t.Context(), postgresql_physical.OpenTunnelSpec{+ Database: db.PostgresqlPhysical,+ Logger: log,+ Encryptor: encryptor,+ })+ require.NoError(t, err)+ t.Cleanup(tunneledDatabase.Close)++ require.NoError(t, tunneledDatabase.GetDatabaseThroughTunnel().PopulateDbData(log, encryptor))+ tunneledDatabase.CopyDiscoveredMetadataToOriginal()// CreateTestPhysicalPostgresDatabase saved the row before PopulateDbData ran,// so the captured system_identifier lives only on the in-memory object. The@@ -287,12 +327,25 @@ func setupPhysicalFixture(return fixture}-// OpenAdminConn returns an inspection connection to the source PG with-// automatic close on test cleanup.+// Through the production opener rather than a hand-rolled dial: a bastioned source publishes no+// port, so a test that reached it any other way would stay green after the tunnel stopped being+// used. With no tunnel configured OpenTunnel hands back the original, so direct fixtures are+// unaffected.func OpenAdminConn(t *testing.T, fixture *PhysicalDBFixture) *pgx.Conn {t.Helper()- conn, err := fixture.DB.PostgresqlPhysical.OpenInspectionConn(context.Background(), encryption.GetFieldEncryptor())+ encryptor := encryption.GetFieldEncryptor()++ tunneledDatabase, err := postgresql_physical.OpenTunnel(t.Context(), postgresql_physical.OpenTunnelSpec{+ Database: fixture.DB.PostgresqlPhysical,+ Logger: logger.GetLogger(),+ Encryptor: encryptor,+ })+ require.NoError(t, err)+ t.Cleanup(tunneledDatabase.Close)++ conn, err := tunneledDatabase.GetDatabaseThroughTunnel().+ OpenInspectionConn(context.Background(), encryptor)require.NoError(t, err)t.Cleanup(func() { _ = conn.Close(context.Background()) })diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.goindex bd5e0bc9..4fbfd843 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go@@ -29,9 +29,16 @@ const (receivewalRespawnMaxBackoff = 30 * time.Minute- // A receiver that streamed at least this long before exiting counts as a- // transient blip (network drop, slot resend) and resets the crash-loop- // counter; a shorter run counts toward escalation.+ // While the bastion is down the backoff must keep growing, or the loop hammers it at the floor+ // interval — but not up to the ceiling above, which would leave half an hour of silence on an+ // already healed transport, WAL piling up on the source and a staleness alert firing after the+ // fact. Half a minute is neither hammering nor a wait anyone notices.+ receivewalBastionDownMaxBackoff = 30 * time.Second++ // A receiver that streamed at least this long before exiting counts as a transient blip (network+ // drop, slot resend) and resets the crash-loop counter; a shorter run counts toward escalation.+ // A run whose bastion was already gone when it exited is not weighed against this at all — see+ // recordExitAndDecideRetry.receivewalMinHealthyUptime = 15 * time.Second// This many back-to-back sub-uptime exits escalate to a fatal supervisor@@ -45,6 +52,10 @@ const (// server retains — only a rebuild clears that.receivewalMaxResumeMismatches = 2+ // Sits between two receiver spawns, so it has to answer fast; a bastion that cannot say hello in+ // this long is unreachable enough for the decision at hand.+ bastionProbeTimeout = 3 * time.Second+pausePollInterval = 1 * time.Second)@@ -75,6 +86,52 @@ func (e *resumeMismatchEscalator) reset() {e.mismatchCount = 0}+type rapidFailureEscalator struct {+ rapidFailureCount int+}++// All three hang on the same "was that run healthy" judgement, so they come out of one call;+// deriving them separately lets them drift.+type retryableExitDecision struct {+ isEscalationRequired bool+ isBackoffResettable bool+ maxRespawnBackoff time.Duration+}++// A run whose bastion was already gone when it exited says nothing about the source, so it is no+// evidence of a crash loop: counting it would let a restarted sshd mark the streamer FAILED in half+// a minute, firing a chain-broken alert and leaving nobody consuming the slot until a later+// supervisor tick reclaims it. It does not reset the backoff either, or the loop would hammer the+// bastion for as long as it stays down.+func (e *rapidFailureEscalator) recordExitAndDecideRetry(+ ranFor time.Duration,+ isBastionReachable bool,+) retryableExitDecision {+ if !isBastionReachable {+ return retryableExitDecision{maxRespawnBackoff: receivewalBastionDownMaxBackoff}+ }++ if ranFor >= receivewalMinHealthyUptime {+ e.rapidFailureCount = 0++ return retryableExitDecision{+ isBackoffResettable: true,+ maxRespawnBackoff: receivewalRespawnMaxBackoff,+ }+ }++ e.rapidFailureCount++++ return retryableExitDecision{+ isEscalationRequired: e.rapidFailureCount >= receivewalMaxRapidFailures,+ maxRespawnBackoff: receivewalRespawnMaxBackoff,+ }+}++func (e *rapidFailureEscalator) reset() {+ e.rapidFailureCount = 0+}+type WalStreamSpec struct {DatabaseID uuid.UUIDSourceDB *postgresql_physical.PostgresqlPhysicalDatabase@@ -115,6 +172,11 @@ type WalStreamSpec struct {// warnings, a wedged receiver); nil disables notification.OnChainAtRisk func(report ChainRiskReport)+ // Separates "the bastion went away" from "the receiver is crash-looping". Without it a restarted+ // sshd looks like five rapid failures and tears the streamer down. Nil means no bastion, so+ // every failure is the source's own.+ IsBastionReachable func(ctx context.Context) bool+Logger *slog.Logger}@@ -246,9 +308,11 @@ func (s *WalStreamSupervisor) Run(ctx context.Context) error {func (s *WalStreamSupervisor) runReceivewalSupervision(ctx context.Context, logger *slog.Logger) error {pgBin := tools.GetPostgresqlExecutable(s.spec.SourceDB.Version, tools.PostgresqlExecutablePgReceivewal)respawnBackoff := receivewalRespawnBackoff- rapidFailures := 0- var mismatchEscalator resumeMismatchEscalator+ var (+ mismatchEscalator resumeMismatchEscalator+ failureEscalator rapidFailureEscalator+ )for {if ctx.Err() != nil {@@ -271,6 +335,18 @@ func (s *WalStreamSupervisor) runReceivewalSupervision(ctx context.Context, loggreceiverRun := s.spawnAndSupervise(ctx, logger, pgBin)+ // One probe per iteration, shared by both dispositions that judge the source: asking twice+ // lets a bastion that comes back in between answer "gone" to the demotion and "here" to the+ // crash-loop counter, which is how a transport blip still ends up counted as a rapid failure.+ // The dispositions that never read the answer do not pay for the round trip, and default to+ // the same answer a database with no bastion in front of it gets.+ isBastionReachable := true+ if receiverRun.Exit == receiverFatal || receiverRun.Exit == receiverRetryable {+ isBastionReachable = s.isBastionReachable(ctx)+ }++ receiverRun = demoteFatalExitWhenBastionUnreachable(logger, receiverRun, isBastionReachable)+switch receiverRun.Exit {case receiverCtxCancelled:return nil@@ -282,8 +358,8 @@ func (s *WalStreamSupervisor) runReceivewalSupervision(ctx context.Context, logg// Our own SIGTERM (back pressure or slot stall): respawn promptly; the// top-of-loop backlog/pause gates already throttle the cause.respawnBackoff = receivewalRespawnBackoff- rapidFailures = 0+ failureEscalator.reset()mismatchEscalator.reset()continue@@ -304,28 +380,62 @@ func (s *WalStreamSupervisor) runReceivewalSupervision(ctx context.Context, loggmismatchEscalator.reset()- // receiverRetryable: a run that streamed for a healthy span is a transient- // blip (network) — reset the crash-loop counter; a string of sub-uptime- // exits is a crash loop a local respawn cannot fix, so escalate.- if receiverRun.RanFor >= receivewalMinHealthyUptime {- rapidFailures = 0- respawnBackoff = receivewalRespawnBackoff- } else {- rapidFailures+++ if !isBastionReachable {+ logger.Warn("wal receiver exited while the bastion was unreachable, waiting for the transport")}- if rapidFailures >= receivewalMaxRapidFailures {+ decision := failureEscalator.recordExitAndDecideRetry(receiverRun.RanFor, isBastionReachable)+ if decision.isEscalationRequired {return fmt.Errorf(- "pg_receivewal crash-looped: %d rapid failures, escalating for reassignment", rapidFailures,+ "pg_receivewal crash-looped: %d rapid failures, escalating for reassignment",+ receivewalMaxRapidFailures,)}+ if decision.isBackoffResettable {+ respawnBackoff = receivewalRespawnBackoff+ }+if !sleepCtx(ctx, respawnBackoff) {return nil}- respawnBackoff = min(respawnBackoff*2, receivewalRespawnMaxBackoff)+ respawnBackoff = min(respawnBackoff*2, decision.maxRespawnBackoff)+ }+}++// A fatal verdict is read off the receiver's stderr, and a receiver whose transport was already gone+// never got far enough to say anything about the source. The needles that classify a run as fatal+// are broad ("could not write", "permission denied"), so a run dying with the bastion can match one+// on the way down and hand the streamer back as FAILED over a blip the forwarder heals on its own.+// While the bastion is unreachable that verdict is not evidence; once it is back, the next one is+// read off trustworthy output and escalates if the cause was real.+func demoteFatalExitWhenBastionUnreachable(+ logger *slog.Logger,+ receiverRun receiverRunResult,+ isBastionReachable bool,+) receiverRunResult {+ if receiverRun.Exit != receiverFatal || isBastionReachable {+ return receiverRun}++ logger.Warn("wal receiver reported a non-retryable error while the bastion was unreachable, retrying",+ "error", receiverRun.FatalErr)++ receiverRun.Exit = receiverRetryable++ return receiverRun+}++func (s *WalStreamSupervisor) isBastionReachable(ctx context.Context) bool {+ if s.spec.IsBastionReachable == nil {+ return true+ }++ probeCtx, cancel := context.WithTimeout(ctx, bastionProbeTimeout)+ defer cancel()++ return s.spec.IsBastionReachable(probeCtx)}func (s *WalStreamSupervisor) waitWhilePaused(ctx context.Context) bool {diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.goindex 8853c4e7..9c8cc43b 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.go@@ -2,6 +2,7 @@ package usecases_physical_postgresqlimport ("context"+ "errors""fmt""os""path/filepath"@@ -13,6 +14,7 @@ import ("github.com/google/uuid""github.com/jackc/pgx/v5"+ "github.com/stretchr/testify/assert""github.com/stretchr/testify/require"backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"@@ -589,6 +591,122 @@ func Test_RecordMismatchAndDecideEscalation_AfterRebuild_StartsCountingFromScrat"a rebuild is expensive, so the next one needs its own pair of mismatches")}+const instantReceiverExit = 100 * time.Millisecond++func fatalReceiverRun() receiverRunResult {+ return receiverRunResult{+ Exit: receiverFatal,+ RanFor: instantReceiverExit,+ FatalErr: errors.New("pg_receivewal fatal error: could not write 8192 bytes to WAL file"),+ }+}++// Escalating on a verdict read off a receiver whose transport was already gone hands the streamer+// back as FAILED and fires a chain-broken alert for a blip the forwarder heals by itself.+func Test_DemoteFatalExitWhenBastionUnreachable_WhenTheBastionIsUnreachable_TurnsTheExitRetryable(+ t *testing.T,+) {+ demotedRun := demoteFatalExitWhenBastionUnreachable(logger.GetLogger(), fatalReceiverRun(), false)++ assert.Equal(t, receiverRetryable, demotedRun.Exit)+}++// The mirror: a fatal cause a respawn can never fix must still hand the streamer back for reclaim.+func Test_DemoteFatalExitWhenBastionUnreachable_WhenTheBastionIsReachable_LeavesTheExitFatal(+ t *testing.T,+) {+ fatalRun := fatalReceiverRun()+ judgedRun := demoteFatalExitWhenBastionUnreachable(logger.GetLogger(), fatalRun, true)++ assert.Equal(t, receiverFatal, judgedRun.Exit)+ assert.Equal(t, fatalRun.FatalErr, judgedRun.FatalErr)+}++func Test_DemoteFatalExitWhenBastionUnreachable_WhenTheExitIsNotFatal_LeavesTheExitUnchanged(+ t *testing.T,+) {+ for _, exit := range []receiverExit{receiverCtxCancelled, receiverRetryable, receiverInternalRestart} {+ judgedRun := demoteFatalExitWhenBastionUnreachable(+ logger.GetLogger(), receiverRunResult{Exit: exit}, false)++ assert.Equal(t, exit, judgedRun.Exit)+ }+}++// A restarted sshd refuses connections instantly, so every spawn dies well under the healthy-uptime+// bar. Counting those would escalate to streamer-FAILED in about half a minute and fire a+// chain-broken alert for a transport blip the forwarder heals on its own.+func Test_RecordExitAndDecideRetry_WhenTheBastionIsUnreachable_DoesNotEscalate(t *testing.T) {+ var failureEscalator rapidFailureEscalator++ for range receivewalMaxRapidFailures * 2 {+ require.False(t,+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, false).isEscalationRequired)+ }+}++// The mirror of the case above: without it the reachability check would silently swallow a real+// crash loop and the streamer would never be handed back for reclaim.+func Test_RecordExitAndDecideRetry_WhenTheBastionIsReachable_EscalatesAfterTheRapidFailureLimit(+ t *testing.T,+) {+ var failureEscalator rapidFailureEscalator++ for range receivewalMaxRapidFailures - 1 {+ require.False(t,+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, true).isEscalationRequired)+ }++ require.True(t,+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, true).isEscalationRequired)+}++func Test_RecordExitAndDecideRetry_WhenAHealthyRunFollowsRapidFailures_ClearsTheCount(t *testing.T) {+ var failureEscalator rapidFailureEscalator++ for range receivewalMaxRapidFailures - 1 {+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, true)+ }++ require.False(t,+ failureEscalator.recordExitAndDecideRetry(receivewalMinHealthyUptime, true).isEscalationRequired)+ require.False(t,+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, true).isEscalationRequired)+}++// A run that only looked healthy because it spent its whole life waiting on a dead bastion must not+// reset the backoff, or the loop hammers the bastion while it is down.+func Test_RecordExitAndDecideRetry_WhenTheBastionIsUnreachable_DoesNotResetTheBackoff(t *testing.T) {+ var failureEscalator rapidFailureEscalator++ require.False(t,+ failureEscalator.recordExitAndDecideRetry(receivewalMinHealthyUptime, false).isBackoffResettable)+ require.True(t,+ failureEscalator.recordExitAndDecideRetry(receivewalMinHealthyUptime, true).isBackoffResettable)+ require.False(t,+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, true).isBackoffResettable)+}++// Growing without a low ceiling would leave half an hour of silence on a transport that healed+// minutes ago: WAL piling up on the source and a staleness alert fired after the fact.+func Test_RecordExitAndDecideRetry_WhenTheBastionIsUnreachable_CapsTheRespawnBackoff(t *testing.T) {+ var failureEscalator rapidFailureEscalator++ require.Equal(t, receivewalBastionDownMaxBackoff,+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, false).maxRespawnBackoff)+ require.Less(t, receivewalBastionDownMaxBackoff, receivewalRespawnMaxBackoff,+ "a cap that is not lower than the ordinary ceiling caps nothing")+}++func Test_RecordExitAndDecideRetry_WhenTheBastionIsReachable_KeepsTheOrdinaryBackoffCeiling(t *testing.T) {+ var failureEscalator rapidFailureEscalator++ require.Equal(t, receivewalRespawnMaxBackoff,+ failureEscalator.recordExitAndDecideRetry(instantReceiverExit, true).maxRespawnBackoff)+ require.Equal(t, receivewalRespawnMaxBackoff,+ failureEscalator.recordExitAndDecideRetry(receivewalMinHealthyUptime, true).maxRespawnBackoff)+}+func Test_WalStream_WhenSourceIsIdle_KeepsReceiverAliveAndDoesNotRebuildSlot(t *testing.T) {if testing.Short() {t.Skip("streamer integration test runs pg_receivewal; skipped in -short")diff --git a/backend/internal/features/databases/controller_test.go b/backend/internal/features/databases/controller_test.goindex e4e167a3..6f6e4e0a 100644--- a/backend/internal/features/databases/controller_test.go+++ b/backend/internal/features/databases/controller_test.go@@ -37,6 +37,7 @@ import (workspaces_testing "databasus-backend/internal/features/workspaces/testing""databasus-backend/internal/util/encryption"test_utils "databasus-backend/internal/util/testing"+ "databasus-backend/internal/util/testing/bastion""databasus-backend/internal/util/testing/containers""databasus-backend/internal/util/tools""databasus-backend/internal/util/walmath"@@ -946,6 +947,10 @@ func assertSshTunnelSecretsAreHidden(t *testing.T, sshTunnel sshtunnel.Config) {}func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {+ // Started once and shared by the physical case's create and update: system_identifier is+ // immutable, so pointing the update at a second cluster is refused as a cluster swap.+ physicalSource := containers.StartPhysicalPostgres(t, "postgres:17")+testCases := []struct {name stringdatabaseType DatabaseType@@ -994,6 +999,46 @@ func Test_DatabaseSensitiveDataLifecycle_AllTypes(t *testing.T) {assertSshTunnelSecretsAreHidden(t, database.PostgresqlLogical.SshTunnel)},},+ {+ name: "PostgreSQL Physical Database",+ databaseType: DatabaseTypePostgresPhysical,+ createDatabase: func(_ *testing.T, workspaceID uuid.UUID) *Database {+ physicalConfig := getTestPhysicalConfigForSource(physicalSource)+ physicalConfig.SshTunnel = storedSshTunnelConfig()+ return &Database{+ WorkspaceID: &workspaceID,+ Name: "Test PostgreSQL Physical Database",+ Type: DatabaseTypePostgresPhysical,+ PostgresqlPhysical: physicalConfig,+ }+ },+ updateDatabase: func(_ *testing.T, workspaceID, databaseID uuid.UUID) *Database {+ physicalConfig := getTestPhysicalConfigForSource(physicalSource)+ physicalConfig.Password = ""+ physicalConfig.SshTunnel = submittedSshTunnelConfigWithoutSecrets()+ return &Database{+ ID: databaseID,+ WorkspaceID: &workspaceID,+ Name: "Updated PostgreSQL Physical Database",+ Type: DatabaseTypePostgresPhysical,+ PostgresqlPhysical: physicalConfig,+ }+ },+ verifySensitiveData: func(t *testing.T, database *Database) {+ assert.True(t, strings.HasPrefix(database.PostgresqlPhysical.Password, "enc:"),+ "Password should be encrypted in database")++ encryptor := encryption.GetFieldEncryptor()+ decrypted, err := encryptor.Decrypt(database.PostgresqlPhysical.Password)+ assert.NoError(t, err)+ assert.Equal(t, "testpassword", decrypted)+ assertSshTunnelUpdateMovedTheHostAndKeptTheSecrets(t, database.PostgresqlPhysical.SshTunnel)+ },+ verifyHiddenData: func(t *testing.T, database *Database) {+ assert.Equal(t, "", database.PostgresqlPhysical.Password)+ assertSshTunnelSecretsAreHidden(t, database.PostgresqlPhysical.SshTunnel)+ },+ },{name: "MariaDB Database",databaseType: DatabaseTypeMariadb,@@ -1472,6 +1517,12 @@ func getTestMysqlConfig(t *testing.T) *mysql.MysqlDatabase {return GetTestMysqlConfig(endpoint.Host, endpoint.Port)}+func getTestPhysicalConfigForSource(source containers.Endpoint) *postgresql_physical.PostgresqlPhysicalDatabase {+ return GetTestPhysicalPostgresConfigWithType(+ source.Host, source.Port, "17", postgresql_physical.BackupTypeFullOnly,+ )+}+func getTestMongodbConfig(t *testing.T) *mongodb.MongodbDatabase {endpoint := containers.StartMongodb(t, "mongo:7.0")@@ -1804,3 +1855,87 @@ func Test_CreateMongodbDatabase_WhenSrvAndSshTunnelAreEnabled_ReturnsBadRequest(assert.Equal(t, http.StatusBadRequest, response.Code)assert.Contains(t, response.Body.String(), "SRV")}++// The source cluster publishes no port, so a green result is proof the request went through the+// bastion — this endpoint is the one physical-only path that had no tunnel around it.+func Test_CreateReplicationOnlyUser_WhenTheDatabaseIsBehindABastion_ReachesTheClusterThroughTheTunnel(+ t *testing.T,+) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Bastioned Workspace", owner, router)+ defer workspaces_testing.RemoveTestWorkspace(workspace, router)++ topology := containers.StartPhysicalPostgresBehindSshBastion(t, "postgres:17")++ physicalConfig := GetTestPhysicalPostgresConfigWithType(+ topology.Database.Host, topology.Database.Port, "17", postgresql_physical.BackupTypeFullOnly,+ )+ physicalConfig.SshTunnel = bastion.GetTunnelConfig(topology)++ request := Database{+ Name: "Bastioned Physical DB",+ WorkspaceID: &workspace.ID,+ Type: DatabaseTypePostgresPhysical,+ PostgresqlPhysical: physicalConfig,+ }++ var response CreateReadOnlyUserResponse+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ "/api/v1/databases/create-replication-only-user",+ "Bearer "+owner.Token,+ request,+ http.StatusOK,+ &response,+ )++ assert.NotEmpty(t, response.Username)+ assert.NotEmpty(t, response.Password)+}++// Creating a physical database runs the replication-protocol probe, which is the one connection that+// does not go through pgx and so needed its own hostaddr handling. The cluster publishes no port, so+// reaching it at all proves the probe went through the bastion.+func Test_CreateDatabase_WhenThePhysicalClusterIsBehindABastion_PassesTheReplicationConnectionTest(+ t *testing.T,+) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Bastioned Create", owner, router)+ defer workspaces_testing.RemoveTestWorkspace(workspace, router)++ topology := containers.StartPhysicalPostgresBehindSshBastion(t, "postgres:17")++ physicalConfig := GetTestPhysicalPostgresConfigWithType(+ topology.Database.Host, topology.Database.Port, "17", postgresql_physical.BackupTypeFullOnly,+ )+ physicalConfig.SshTunnel = bastion.GetTunnelConfig(topology)++ request := Database{+ Name: "Bastioned Physical Create",+ WorkspaceID: &workspace.ID,+ Type: DatabaseTypePostgresPhysical,+ PostgresqlPhysical: physicalConfig,+ }++ var response Database+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ "/api/v1/databases/create",+ "Bearer "+owner.Token,+ request,+ http.StatusCreated,+ &response,+ )+ defer RemoveTestDatabase(&response)++ require.NotNil(t, response.PostgresqlPhysical)+ assert.NotEmpty(t, response.PostgresqlPhysical.Version,+ "the version discovered through the tunnel must be carried back onto the stored row")+ assert.NotNil(t, response.PostgresqlPhysical.SystemIdentifier,+ "the cluster identity must be carried back too, or the manifest records a zero identifier")+ assert.NotNil(t, response.PostgresqlPhysical.WalSegmentSizeBytes)+}diff --git a/backend/internal/features/databases/databases/postgresql/physical/connection.go b/backend/internal/features/databases/databases/postgresql/physical/connection.gonew file mode 100644index 00000000..93843cd8--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/physical/connection.go@@ -0,0 +1,99 @@+package postgresql_physical++import (+ "context"+ "fmt"+ "log/slog"+ "regexp"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"++ postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared"+ "databasus-backend/internal/util/encryption"+ "databasus-backend/internal/util/tools"+)++// The `postgres` database always exists, and the physical model has no per-DB selection.+func openConn(+ ctx context.Context,+ p *PostgresqlPhysicalDatabase,+ encryptor encryption.FieldEncryptor,+) (*pgx.Conn, error) {+ password, err := postgresql_shared.DecryptFieldIfNeeded(p.Password, encryptor)+ if err != nil {+ return nil, fmt.Errorf("failed to decrypt password: %w", err)+ }++ files, err := postgresql_shared.WriteCredentialFilesToTempDir(p.CredentialSpec(), password, encryptor)+ if err != nil {+ return nil, err+ }+ defer files.Remove()++ connConfig, err := postgresql_shared.BuildConnConfig(p.CredentialSpec(), password, "postgres", files)+ if err != nil {+ return nil, err+ }++ return pgx.ConnectConfig(ctx, connConfig)+}++// This is what exercises the "host replication" pg_hba path and the REPLICATION privilege at connect+// time; an ordinary "host all" rule does NOT cover it, so a logical (replication=database) probe+// would wrongly accept a cluster that real backups cannot stream. It uses the low-level pgconn+// because no ordinary SQL is allowed on a physical replication connection.+func openPhysicalReplicationConn(+ ctx context.Context,+ p *PostgresqlPhysicalDatabase,+ encryptor encryption.FieldEncryptor,+) (*pgconn.PgConn, error) {+ password, err := postgresql_shared.DecryptFieldIfNeeded(p.Password, encryptor)+ if err != nil {+ return nil, fmt.Errorf("failed to decrypt password: %w", err)+ }++ files, err := postgresql_shared.WriteCredentialFilesToTempDir(p.CredentialSpec(), password, encryptor)+ if err != nil {+ return nil, err+ }+ defer files.Remove()++ connConfig, err := postgresql_shared.BuildPhysicalReplicationConnConfig(+ p.CredentialSpec(), password, "postgres", files,+ )+ if err != nil {+ return nil, err+ }++ return pgconn.ConnectConfig(ctx, connConfig)+}++func closeConnQuietly(ctx context.Context, conn *pgx.Conn, logger *slog.Logger) {+ if err := conn.Close(ctx); err != nil {+ logger.Warn("failed to close connection", "error", err)+ }+}++var versionRegexp = regexp.MustCompile(`PostgreSQL (\d+)`)++func detectVersion(ctx context.Context, conn *pgx.Conn) (tools.PostgresqlVersion, error) {+ var rawServerVersion string+ if err := conn.QueryRow(ctx, "SELECT version()").Scan(&rawServerVersion); err != nil {+ return "", fmt.Errorf("failed to query version(): %w", err)+ }++ matches := versionRegexp.FindStringSubmatch(rawServerVersion)+ if len(matches) < 2 {+ return "", fmt.Errorf("could not parse version from: %s", rawServerVersion)+ }++ switch matches[1] {+ case "17":+ return tools.PostgresqlVersion17, nil+ case "18":+ return tools.PostgresqlVersion18, nil+ default:+ return "", fmt.Errorf("physical backup requires PostgreSQL 17 or 18, detected %s", matches[1])+ }+}diff --git a/backend/internal/features/databases/databases/postgresql/physical/credentials.go b/backend/internal/features/databases/databases/postgresql/physical/credentials.goindex e0d2f142..a81c23a7 100644--- a/backend/internal/features/databases/databases/postgresql/physical/credentials.go+++ b/backend/internal/features/databases/databases/postgresql/physical/credentials.go@@ -4,12 +4,17 @@ import (postgresql_shared "databasus-backend/internal/features/databases/databases/postgresql/shared")-// CredentialSpec maps this database into the strategy-agnostic credential inputs-// shared by every libpq path: the pgx inspection / replication connections here-// and pg_basebackup in the backup usecase.+// Every libpq path goes through here: the pgx inspection and replication connections, pg_basebackup+// and pg_receivewal.func (p *PostgresqlPhysicalDatabase) 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,diff --git a/backend/internal/features/databases/databases/postgresql/physical/model.go b/backend/internal/features/databases/databases/postgresql/physical/model.goindex eeedb182..58f8b10a 100644--- a/backend/internal/features/databases/databases/postgresql/physical/model.go+++ b/backend/internal/features/databases/databases/postgresql/physical/model.go@@ -5,7 +5,6 @@ import ("errors""fmt""log/slog"- "regexp""strconv""strings""time"@@ -16,6 +15,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/tools")@@ -39,6 +39,13 @@ type PostgresqlPhysicalDatabase 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 cluster 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:"-"`+ReplicationSlotName string `json:"-" gorm:"column:replication_slot_name;type:text;not null"`SystemIdentifier *string `json:"systemIdentifier" gorm:"column:system_identifier;type:text"`@@ -80,6 +87,10 @@ func (p *PostgresqlPhysicalDatabase) Validate() error {return err}+ if err := p.SshTunnel.Validate(); err != nil {+ return err+ }+switch p.BackupType {case BackupTypeFullOnly, BackupTypeFullAndIncremental, BackupTypeFullIncrementalAndWalStream:case "":@@ -129,6 +140,7 @@ func (p *PostgresqlPhysicalDatabase) Update(incoming *PostgresqlPhysicalDatabasep.SslClientCert = incoming.SslClientCertp.SslRootCert = incoming.SslRootCertp.BackupType = incoming.BackupType+ p.SshTunnel.Update(&incoming.SshTunnel)if incoming.Password != "" {p.Password = incoming.Password@@ -148,13 +160,15 @@ func (p *PostgresqlPhysicalDatabase) HideSensitiveData() {p.Password = ""p.SslClientKey = ""+ p.SshTunnel.HideSensitiveData()}// 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.+// read back from whichever cluster the copy is pointed at. LocalTunnelEndpoint belongs to the+// operation that opened the tunnel, not to the configuration.func (p *PostgresqlPhysicalDatabase) CopyForNewDatabase() *PostgresqlPhysicalDatabase {if p == nil {return nil@@ -166,6 +180,7 @@ func (p *PostgresqlPhysicalDatabase) CopyForNewDatabase() *PostgresqlPhysicalDatcopiedDatabase.ReplicationSlotName = ""copiedDatabase.SystemIdentifier = nilcopiedDatabase.WalSegmentSizeBytes = nil+ copiedDatabase.LocalTunnelEndpoint = nilreturn &copiedDatabase}@@ -191,7 +206,7 @@ func (p *PostgresqlPhysicalDatabase) EncryptSensitiveFields(*field = encrypted}- return nil+ return p.SshTunnel.EncryptSensitiveFields(encryptor)}func (p *PostgresqlPhysicalDatabase) PopulateDbData(@@ -1064,81 +1079,3 @@ func classifyReplicationConnectError(err error, username string) error {return &postgresql_shared.ConnectionTestError{Code: postgresql_shared.ConnErrConnectionFailed}}}--// openConn opens a regular pgx connection to the `postgres` database (always-// exists; physical model has no per-DB selection), carrying the source's client-// certificates the same way pg_basebackup does via the shared credential files.-func openConn(- ctx context.Context,- p *PostgresqlPhysicalDatabase,- encryptor encryption.FieldEncryptor,-) (*pgx.Conn, error) {- password, err := postgresql_shared.DecryptFieldIfNeeded(p.Password, encryptor)- if err != nil {- return nil, fmt.Errorf("failed to decrypt password: %w", err)- }-- files, err := postgresql_shared.WriteCredentialFilesToTempDir(p.CredentialSpec(), password, encryptor)- if err != nil {- return nil, err- }- defer files.Remove()-- return pgx.Connect(ctx, postgresql_shared.BuildConnString(p.CredentialSpec(), password, "postgres", files))-}--// openPhysicalReplicationConn opens a PHYSICAL replication connection (replication=true) — the same-// mode pg_basebackup / pg_receivewal use. This is what exercises the "host replication" pg_hba path-// and the REPLICATION privilege at connect time; an ordinary "host all" rule does NOT cover it, so a-// logical (replication=database) probe would wrongly accept a cluster that real backups cannot stream.-// Uses the low-level pgconn because no ordinary SQL is allowed on a physical replication connection.-func openPhysicalReplicationConn(- ctx context.Context,- p *PostgresqlPhysicalDatabase,- encryptor encryption.FieldEncryptor,-) (*pgconn.PgConn, error) {- password, err := postgresql_shared.DecryptFieldIfNeeded(p.Password, encryptor)- if err != nil {- return nil, fmt.Errorf("failed to decrypt password: %w", err)- }-- files, err := postgresql_shared.WriteCredentialFilesToTempDir(p.CredentialSpec(), password, encryptor)- if err != nil {- return nil, err- }- defer files.Remove()-- return pgconn.Connect(- ctx,- postgresql_shared.BuildPhysicalReplicationConnString(p.CredentialSpec(), password, "postgres", files),- )-}--func closeConnQuietly(ctx context.Context, conn *pgx.Conn, logger *slog.Logger) {- if err := conn.Close(ctx); err != nil {- logger.Warn("failed to close connection", "error", err)- }-}--var versionRegexp = regexp.MustCompile(`PostgreSQL (\d+)`)--func detectVersion(ctx context.Context, conn *pgx.Conn) (tools.PostgresqlVersion, error) {- var versionStr string- if err := conn.QueryRow(ctx, "SELECT version()").Scan(&versionStr); err != nil {- return "", fmt.Errorf("failed to query version(): %w", err)- }-- matches := versionRegexp.FindStringSubmatch(versionStr)- if len(matches) < 2 {- return "", fmt.Errorf("could not parse version from: %s", versionStr)- }-- switch matches[1] {- case "17":- return tools.PostgresqlVersion17, nil- case "18":- return tools.PostgresqlVersion18, nil- default:- return "", fmt.Errorf("physical backup requires PostgreSQL 17 or 18, detected %s", matches[1])- }-}diff --git a/backend/internal/features/databases/databases/postgresql/physical/tunnel.go b/backend/internal/features/databases/databases/postgresql/physical/tunnel.gonew file mode 100644index 00000000..43853c2c--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/physical/tunnel.go@@ -0,0 +1,100 @@+package postgresql_physical++import (+ "context"+ "log/slog"++ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/encryption"+)++type OpenTunnelSpec struct {+ Database *PostgresqlPhysicalDatabase+ Logger *slog.Logger+ Encryptor encryption.FieldEncryptor+}++// The tunnel belongs to the operation, not to the model: a base backup runs for hours and a WAL+// streamer for weeks, both over connections that outlive any single method down there.+type TunneledDatabase struct {+ original *PostgresqlPhysicalDatabase+ databaseThroughTunnel *PostgresqlPhysicalDatabase+ 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()++ // The struct copy is what keeps ID, DatabaseID and ReplicationSlotName intact, and both slot+ // families are named from those. Reaching for CopyForNewDatabase here would blank them and mint+ // a fresh slot on the source cluster on every reconnect.+ 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() *PostgresqlPhysicalDatabase {+ if t == nil {+ return nil+ }++ return t.databaseThroughTunnel+}++// PopulateDbData fills all three from the cluster, into the model it was handed — which is the+// copy. Carrying back only Version would persist a row with a NULL system_identifier, and+// SystemIdentifierUint64 would then write 0 into every backup manifest.+func (t *TunneledDatabase) CopyDiscoveredMetadataToOriginal() {+ if t == nil || t.original == nil || t.databaseThroughTunnel == nil {+ return+ }++ t.original.Version = t.databaseThroughTunnel.Version+ t.original.SystemIdentifier = t.databaseThroughTunnel.SystemIdentifier+ t.original.WalSegmentSizeBytes = t.databaseThroughTunnel.WalSegmentSizeBytes+}++// No forwarder means no bastion between us and the cluster, so nothing about the transport can be+// at fault and the caller's failure is the source's own.+func (t *TunneledDatabase) IsBastionReachable(ctx context.Context) bool {+ if t == nil || t.forwarder == nil {+ return true+ }++ return t.forwarder.IsBastionReachable(ctx)+}++func (t *TunneledDatabase) Close() {+ if t == nil || t.forwarder == nil {+ return+ }++ t.forwarder.Close()+}diff --git a/backend/internal/features/databases/databases/postgresql/physical/tunnel_test.go b/backend/internal/features/databases/databases/postgresql/physical/tunnel_test.gonew file mode 100644index 00000000..313518e6--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/physical/tunnel_test.go@@ -0,0 +1,176 @@+package postgresql_physical++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "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 unreachableBastionTimeout = 2 * time.Second++func enabledTunnelDatabase() *PostgresqlPhysicalDatabase {+ parentDatabaseID := uuid.New()++ return &PostgresqlPhysicalDatabase{+ ID: uuid.New(),+ DatabaseID: &parentDatabaseID,+ Version: tools.PostgresqlVersion17,+ BackupType: BackupTypeFullIncrementalAndWalStream,+ Host: "cluster.internal",+ Port: 5432,+ Username: "testuser",+ Password: "testpassword",+ ReplicationSlotName: "databasus_slot_deadbeef",+ SshTunnel: sshtunnel.Config{+ IsEnabled: true,+ Host: "bastion.example.com",+ Port: 22,+ Username: "tunneluser",+ Password: "tunnelpassword",+ },+ }+}++func bastionedTunnelDatabase(t *testing.T) *PostgresqlPhysicalDatabase {+ 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, "cluster.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)+ assert.Equal(t, "127.0.0.1", databaseThroughTunnel.CredentialSpec().HostAddr)+}++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)+}++// Both slot families are named from these: the per-backup slot from ID, the streamer slot from the+// stored name, and the receiver's application_name from DatabaseID. A copy that blanked them would+// mint a fresh slot on the source cluster every time the tunnel is reopened.+func Test_OpenTunnel_WhenTunneled_KeepsTheSlotIdentityOnTheCopy(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, database.ID, databaseThroughTunnel.ID)+ require.NotNil(t, databaseThroughTunnel.DatabaseID)+ assert.Equal(t, *database.DatabaseID, *databaseThroughTunnel.DatabaseID)+ assert.Equal(t, database.ReplicationSlotName, databaseThroughTunnel.ReplicationSlotName)+ assert.Equal(t, database.ParentDatabaseID(), databaseThroughTunnel.ParentDatabaseID())+}++// PopulateDbData writes all three into the model it was handed, which is the copy. Carrying back+// only Version would persist a NULL system_identifier and put 0 into every backup manifest.+func Test_CopyDiscoveredMetadataToOriginal_AfterPopulateDbData_CarriesVersionAndClusterIdentity(t *testing.T) {+ database := bastionedTunnelDatabase(t)+ database.Version = ""++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ discoveredSystemIdentifier := "7150000000000000000"+ discoveredWalSegmentSizeBytes := int64(16 * 1024 * 1024)++ databaseThroughTunnel := tunneledDatabase.GetDatabaseThroughTunnel()+ databaseThroughTunnel.Version = tools.PostgresqlVersion18+ databaseThroughTunnel.SystemIdentifier = &discoveredSystemIdentifier+ databaseThroughTunnel.WalSegmentSizeBytes = &discoveredWalSegmentSizeBytes++ tunneledDatabase.CopyDiscoveredMetadataToOriginal()++ assert.Equal(t, tools.PostgresqlVersion18, database.Version)+ require.NotNil(t, database.SystemIdentifier)+ assert.Equal(t, discoveredSystemIdentifier, *database.SystemIdentifier)+ require.NotNil(t, database.WalSegmentSizeBytes)+ assert.Equal(t, discoveredWalSegmentSizeBytes, *database.WalSegmentSizeBytes)+}++func Test_IsBastionReachable_WhenTheTunnelIsDisabled_ReportsReachable(t *testing.T) {+ database := enabledTunnelDatabase()+ database.SshTunnel.IsEnabled = false++ tunneledDatabase, err := OpenTunnel(t.Context(), OpenTunnelSpec{Database: database})+ require.NoError(t, err)++ defer tunneledDatabase.Close()++ assert.True(t, tunneledDatabase.IsBastionReachable(t.Context()),+ "with no bastion in the path a receiver failure is the source's own")+}diff --git a/backend/internal/features/databases/databases/postgresql/shared/credentials.go b/backend/internal/features/databases/databases/postgresql/shared/credentials.goindex 3beaf563..0a62d075 100644--- a/backend/internal/features/databases/databases/postgresql/shared/credentials.go+++ b/backend/internal/features/databases/databases/postgresql/shared/credentials.go@@ -8,6 +8,7 @@ import ("github.com/google/uuid""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn""databasus-backend/internal/util/encryption""databasus-backend/internal/util/tools"@@ -78,7 +79,7 @@ func (f *CredentialTempFiles) Remove() {_ = os.RemoveAll(f.Dir)}-func BuildConnString(+func buildConnString(spec CredentialSpec,password, dbName string,files *CredentialTempFiles,@@ -98,18 +99,17 @@ func BuildConnString(return appendSslFilePaths(connStr, files)}-// BuildPhysicalReplicationConnString builds a libpq conninfo for a PHYSICAL replication connection-// (replication=true) — the mode pg_basebackup / pg_receivewal use, and the one pg_hba matches via-// "host replication" rules rather than ordinary "host all" rules. It omits the pgx-only query-exec-// params so the string is consumable by the low-level pgconn.Connect used for the connectivity probe.-func BuildPhysicalReplicationConnString(+// replication=true is the mode pg_basebackup / pg_receivewal use, and the one pg_hba matches via+// "host replication" rules rather than ordinary "host all" rules. The pgx-only query-exec params are+// omitted so the string stays consumable by the low-level pgconn used for the connectivity probe.+func buildPhysicalReplicationConnString(spec CredentialSpec,password, dbName string,files *CredentialTempFiles,) string {connStr := fmt.Sprintf("host=%s port=%d user=%s password='%s' dbname=%s sslmode=%s replication=true",- spec.Host,+ getConnectHost(spec),spec.Port,spec.Username,escapeConnStringValue(password),@@ -127,26 +127,49 @@ func BuildConnConfig(password, dbName string,files *CredentialTempFiles,) (*pgx.ConnConfig, error) {- connConfig, err := pgx.ParseConfig(BuildConnString(spec, password, dbName, files))+ 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)}+ restoreServerNameForTunneledHost(&connConfig.Config, spec)++ return connConfig, nil+}++// pgconn has no hostaddr either, and unlike the pgx path there is no ParseConfig step in the caller,+// so the ServerName restoration has to happen here or verify-full would match the tunnel's loopback.+func BuildPhysicalReplicationConnConfig(+ spec CredentialSpec,+ password, dbName string,+ files *CredentialTempFiles,+) (*pgconn.Config, error) {+ connConfig, err := pgconn.ParseConfig(buildPhysicalReplicationConnString(spec, password, dbName, files))+ if err != nil {+ return nil, fmt.Errorf("failed to parse the PostgreSQL replication connection string: %w", err)+ }++ restoreServerNameForTunneledHost(connConfig, spec)++ return connConfig, nil+}++// pgx builds one fallback config per sslmode it may retry with, so skipping those would silently+// verify against the tunnel address on the retry.+func restoreServerNameForTunneledHost(config *pgconn.Config, spec CredentialSpec) {if spec.HostAddr == "" {- return connConfig, nil+ return}- if connConfig.TLSConfig != nil {- connConfig.TLSConfig.ServerName = spec.Host+ if config.TLSConfig != nil {+ config.TLSConfig.ServerName = spec.Host}- for _, fallback := range connConfig.Fallbacks {+ for _, fallback := range config.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 againstdiff --git a/backend/internal/features/databases/model.go b/backend/internal/features/databases/model.goindex 023ddcdc..4377fa51 100644--- a/backend/internal/features/databases/model.go+++ b/backend/internal/features/databases/model.go@@ -268,6 +268,10 @@ func (d *Database) ClearSshTunnelConfig() {d.PostgresqlLogical.SshTunnel = sshtunnel.Config{}}+ if d.PostgresqlPhysical != nil {+ d.PostgresqlPhysical.SshTunnel = sshtunnel.Config{}+ }+if d.Mysql != nil {d.Mysql.SshTunnel = sshtunnel.Config{}}diff --git a/backend/internal/features/databases/model_test.go b/backend/internal/features/databases/model_test.goindex 55d7fb29..6ee0c555 100644--- a/backend/internal/features/databases/model_test.go+++ b/backend/internal/features/databases/model_test.go@@ -141,6 +141,7 @@ func Test_PopulateVersion_WhenTheDatabaseCarriesAStaleEngineConfig_DispatchesOnTfunc Test_HideSensitiveData_ForEveryTunnelCapableType_ClearsTheTunnelSecrets(t *testing.T) {for _, databaseType := range []DatabaseType{DatabaseTypePostgresLogical,+ DatabaseTypePostgresPhysical,DatabaseTypeMysql,DatabaseTypeMariadb,DatabaseTypeMongodb,@@ -163,6 +164,7 @@ func Test_HideSensitiveData_ForEveryTunnelCapableType_ClearsTheTunnelSecrets(t *func Test_ClearSshTunnelConfig_ForEveryTunnelCapableType_RemovesTheWholeBlock(t *testing.T) {for _, databaseType := range []DatabaseType{DatabaseTypePostgresLogical,+ DatabaseTypePostgresPhysical,DatabaseTypeMysql,DatabaseTypeMariadb,DatabaseTypeMongodb,@@ -183,6 +185,8 @@ func getSshTunnelConfig(t *testing.T, database *Database) sshtunnel.Config {switch database.Type {case DatabaseTypePostgresLogical:return database.PostgresqlLogical.SshTunnel+ case DatabaseTypePostgresPhysical:+ return database.PostgresqlPhysical.SshTunnelcase DatabaseTypeMysql:return database.Mysql.SshTunnelcase DatabaseTypeMariadb:@@ -273,6 +277,8 @@ func filledSourceDatabase(databaseType DatabaseType) *Database {SslClientCert: "clientcert",SslClientKey: "enc:clientkey",SslRootCert: "rootcert",+ SshTunnel: filledSshTunnel(),+ LocalTunnelEndpoint: &sshtunnel.Endpoint{Host: "127.0.0.1", Port: 41000},ReplicationSlotName: "databasus_slot_deadbeef",SystemIdentifier: &systemIdentifier,WalSegmentSizeBytes: &walSegmentSizeBytes,@@ -444,11 +450,24 @@ func Test_CopyForNewDatabase_WhenTheSourceIsPostgresqlPhysical_DoesNotInheritSersourceEngineWithoutIdentity.ReplicationSlotName = ""sourceEngineWithoutIdentity.SystemIdentifier = nilsourceEngineWithoutIdentity.WalSegmentSizeBytes = nil+ sourceEngineWithoutIdentity.LocalTunnelEndpoint = nilassert.Equal(t, sourceEngineWithoutIdentity, *copiedEngine)assert.Equal(t, "databasus_slot_deadbeef", sourceDatabase.PostgresqlPhysical.ReplicationSlotName)}+func Test_CopyForNewDatabase_WhenTheSourceIsPostgresqlPhysical_DropsTheLocalTunnelEndpoint(t *testing.T) {+ sourceDatabase := filledSourceDatabase(DatabaseTypePostgresPhysical)+ require.NotNil(t, sourceDatabase.PostgresqlPhysical.LocalTunnelEndpoint)++ copiedEngine := sourceDatabase.CopyForNewDatabase().PostgresqlPhysical+ require.NotNil(t, copiedEngine)++ assert.Nil(t, copiedEngine.LocalTunnelEndpoint)+ assert.Equal(t, filledSshTunnel(), copiedEngine.SshTunnel,+ "a clone behind the same bastion still goes through it")+}+func Test_CopyForNewDatabase_DropsIdentityAndBackupHistory(t *testing.T) {sourceDatabase := filledSourceDatabase(DatabaseTypeMysql)diff --git a/backend/internal/features/databases/service.go b/backend/internal/features/databases/service.goindex 045383bb..ed96f5b6 100644--- a/backend/internal/features/databases/service.go+++ b/backend/internal/features/databases/service.go@@ -894,9 +894,21 @@ func (s *DatabaseService) CreateReplicationOnlyUser(ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()- username, password, err := usingDatabase.PostgresqlPhysical.CreateReplicationOnlyUser(- 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 "", "", err+ }++ defer tunneledDatabase.Close()++ username, password, err := tunneledDatabase.GetDatabaseThroughTunnel().+ PostgresqlPhysical.CreateReplicationOnlyUser(ctx, logger, s.fieldEncryptor)if err != nil {return "", "", err}diff --git a/backend/internal/features/databases/testing.go b/backend/internal/features/databases/testing.goindex 44afd99d..8e557413 100644--- a/backend/internal/features/databases/testing.go+++ b/backend/internal/features/databases/testing.go@@ -17,6 +17,7 @@ import (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""databasus-backend/internal/util/tools")@@ -317,6 +318,44 @@ func CreateTestPhysicalPostgresDatabaseWithType(return database}+// Host and Port address a bastioned cluster from inside the bastion's network, so they are+// unreachable from the host running the test: only the tunnel gets there.+type PhysicalTestDatabaseSpec struct {+ Host string+ Port int+ VersionTag string+ BackupType postgresql_physical.BackupType+ SshTunnel sshtunnel.Config+}++func CreateTestPhysicalPostgresDatabaseWithTunnel(+ spec PhysicalTestDatabaseSpec,+ workspaceID uuid.UUID,+ notifier *notifiers.Notifier,+) *Database {+ physicalConfig := GetTestPhysicalPostgresConfigWithType(+ spec.Host, spec.Port, spec.VersionTag, spec.BackupType,+ )+ physicalConfig.SshTunnel = spec.SshTunnel++ database := &Database{+ WorkspaceID: &workspaceID,+ Name: "test-physical-pg-bastioned " + uuid.New().String(),+ Type: DatabaseTypePostgresPhysical,+ PostgresqlPhysical: physicalConfig,+ Notifiers: []notifiers.Notifier{+ *notifier,+ },+ }++ database, err := databaseRepository.Save(database)+ if err != nil {+ panic(err)+ }++ return database+}+// CreateTestPhysicalPostgresDatabaseNoSummary persists a physical DB row at host:port pointed at a// summarize_wal=off cluster, so incremental pre-checks reach the SUMMARIZER_OFF branch// deterministically (ALTER SYSTEM cannot override a command-line GUC on the standard fixture).diff --git a/backend/internal/features/databases/tunneled_database.go b/backend/internal/features/databases/tunneled_database.goindex 381497fc..faa6d849 100644--- a/backend/internal/features/databases/tunneled_database.go+++ b/backend/internal/features/databases/tunneled_database.go@@ -8,6 +8,7 @@ import ("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/util/encryption")@@ -45,6 +46,8 @@ func OpenTunnel(ctx context.Context, spec OpenTunnelSpec) (*TunneledDatabase, erswitch spec.Database.Type {case DatabaseTypePostgresLogical:err = tunneledDatabase.openPostgresqlLogicalTunnel(ctx, spec)+ case DatabaseTypePostgresPhysical:+ err = tunneledDatabase.openPostgresqlPhysicalTunnel(ctx, spec)case DatabaseTypeMysql:err = tunneledDatabase.openMysqlTunnel(ctx, spec)case DatabaseTypeMariadb:@@ -109,6 +112,26 @@ func (t *TunneledDatabase) openPostgresqlLogicalTunnel(ctx context.Context, specreturn nil}+func (t *TunneledDatabase) openPostgresqlPhysicalTunnel(ctx context.Context, spec OpenTunnelSpec) error {+ if spec.Database.PostgresqlPhysical == nil || !spec.Database.PostgresqlPhysical.SshTunnel.IsEnabled {+ return nil+ }++ tunneledEngine, err := postgresql_physical.OpenTunnel(ctx, postgresql_physical.OpenTunnelSpec{+ Database: spec.Database.PostgresqlPhysical,+ Logger: spec.Logger,+ Encryptor: spec.Encryptor,+ })+ if err != nil {+ return err+ }++ t.tunneledEngine = tunneledEngine+ t.databaseThroughTunnel.PostgresqlPhysical = 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 nildiff --git a/backend/internal/features/sshtunnel/keepalive.go b/backend/internal/features/sshtunnel/keepalive.goindex c61caaf4..395eb2fa 100644--- a/backend/internal/features/sshtunnel/keepalive.go+++ b/backend/internal/features/sshtunnel/keepalive.go@@ -28,7 +28,7 @@ func (f *Forwarder) runKeepalive() {continue}- if !isKeepaliveAnswered(client) {+ if !f.isKeepaliveAnsweredWithin(keepaliveTimeout, client) {f.logger.Warn("ssh tunnel keepalive went unanswered, reconnecting on next use")f.discardClient(client)}@@ -36,10 +36,13 @@ func (f *Forwarder) runKeepalive() {}}+// The budget is a parameter because the reachability probe answers a caller with a far shorter+// deadline than the keepalive loop's.+//// 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 {+func (f *Forwarder) isKeepaliveAnsweredWithin(budget time.Duration, client *ssh.Client) bool {keepaliveAnswer := make(chan error, 1)go func() {@@ -47,10 +50,15 @@ func isKeepaliveAnswered(client *ssh.Client) bool {keepaliveAnswer <- err}()+ timer := time.NewTimer(budget)+ defer timer.Stop()+select {case err := <-keepaliveAnswer:return err == nil- case <-time.After(keepaliveTimeout):+ case <-timer.C:+ return false+ case <-f.done:return false}}diff --git a/backend/internal/features/sshtunnel/reachability.go b/backend/internal/features/sshtunnel/reachability.gonew file mode 100644index 00000000..8bfeea6c--- /dev/null+++ b/backend/internal/features/sshtunnel/reachability.go@@ -0,0 +1,38 @@+package sshtunnel++import (+ "context"+ "time"+)++// Asking must not change anything: a cached session is probed in place, and with no session this+// dials TCP only — no handshake, no authentication, nothing written back to the client cache. The+// caller is a supervision loop deciding whether a failed run was the bastion's fault, so it needs an+// answer inside its own deadline rather than the transport's 30s dial budget.+func (f *Forwarder) IsBastionReachable(ctx context.Context) bool {+ f.clientMutex.Lock()+ client := f.client+ f.clientMutex.Unlock()++ if client != nil {+ return f.isKeepaliveAnsweredWithin(budgetUntil(ctx), client)+ }++ bastionConn, err := f.dialBastionConn(ctx, f.bastionAddress)+ if err != nil {+ return false+ }++ _ = bastionConn.Close()++ return true+}++func budgetUntil(ctx context.Context) time.Duration {+ deadline, hasDeadline := ctx.Deadline()+ if !hasDeadline {+ return bastionDialTimeout+ }++ return max(time.Until(deadline), 0)+}diff --git a/backend/internal/features/sshtunnel/reachability_test.go b/backend/internal/features/sshtunnel/reachability_test.gonew file mode 100644index 00000000..d384dd05--- /dev/null+++ b/backend/internal/features/sshtunnel/reachability_test.go@@ -0,0 +1,195 @@+package sshtunnel++import (+ "context"+ "fmt"+ "net"+ "sync/atomic"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/util/testing/containers"+)++// The caller is a supervision loop between two receiver spawns, so an answer that took the+// transport's own 30s dial budget would be useless — it has to come back inside the deadline it+// was given.+func Test_IsBastionReachable_WhenTheBastionIsGone_ReturnsFalseWithinTheCallersDeadline(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))+ assertTargetReachableThroughTunnel(t, forwarder)++ forwarder.clientMutex.Lock()+ cachedClient := forwarder.client+ forwarder.clientMutex.Unlock()++ forwarder.discardClient(cachedClient)++ forwarder.dialBastionConn = func(ctx context.Context, _ string) (net.Conn, error) {+ <-ctx.Done()++ return nil, ctx.Err()+ }++ probeBudget := 500 * time.Millisecond++ ctx, cancel := context.WithTimeout(t.Context(), probeBudget)+ defer cancel()++ probeStartedAt := time.Now()+ isReachable := forwarder.IsBastionReachable(ctx)++ assert.False(t, isReachable)+ assert.Less(t, time.Since(probeStartedAt), bastionDialTimeout/2,+ "the probe outlived the caller's deadline")+}++// Asking a question must not authenticate: getOrDialBastion would have installed a live session as+// a side effect, so a probe built on it would silently reconnect on every call.+func Test_IsBastionReachable_WhenNoClientIsCached_DoesNotCacheTheDialedClient(t *testing.T) {+ bastion := startTestBastion(t)++ forwarder := openTestForwarder(t, bastionConfig(bastion))++ forwarder.clientMutex.Lock()+ cachedClient := forwarder.client+ forwarder.clientMutex.Unlock()++ forwarder.discardClient(cachedClient)++ assert.True(t, forwarder.IsBastionReachable(t.Context()))++ forwarder.clientMutex.Lock()+ defer forwarder.clientMutex.Unlock()++ assert.Nil(t, forwarder.client, "the probe installed a session nobody asked for")+}++// The cached-session branch cannot dial, so this is where the caller's deadline reaches it. A probe+// that fell back to the keepalive loop's own 15s budget would block a supervision loop that asked+// for three seconds.+func Test_BudgetUntil_WithACallerDeadline_ReportsTheRemainingTimeRatherThanTheDialTimeout(t *testing.T) {+ callerBudget := 3 * time.Second++ ctx, cancel := context.WithTimeout(t.Context(), callerBudget)+ defer cancel()++ assert.InDelta(t, callerBudget, budgetUntil(ctx), float64(200*time.Millisecond))+}++func Test_BudgetUntil_WithoutACallerDeadline_FallsBackToTheDialTimeout(t *testing.T) {+ assert.Equal(t, bastionDialTimeout, budgetUntil(context.Background()))+}++func Test_BudgetUntil_WithAnExpiredDeadline_ReportsZeroRatherThanANegativeBudget(t *testing.T) {+ ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(-time.Minute))+ defer cancel()++ assert.Equal(t, time.Duration(0), budgetUntil(ctx))+}++// startStallableBastionProxy fronts the real bastion with a pipe the test can stop feeding. Halting+// it mid-session is the failure keepalive exists for: the TCP connection stays open with no FIN, so+// a request written into it is never answered and never fails either.+func startStallableBastionProxy(t *testing.T, bastion containers.Endpoint) (containers.Endpoint, *atomic.Bool) {+ t.Helper()++ var listenConfig net.ListenConfig++ proxy, err := listenConfig.Listen(t.Context(), "tcp", "127.0.0.1:0")+ require.NoError(t, err)+ t.Cleanup(func() { _ = proxy.Close() })++ isStalled := &atomic.Bool{}++ go func() {+ for {+ clientConn, acceptErr := proxy.Accept()+ if acceptErr != nil {+ return+ }++ go pipeUntilStalled(t.Context(), clientConn, bastion, isStalled)+ }+ }()++ proxyAddr, isTCPAddr := proxy.Addr().(*net.TCPAddr)+ require.True(t, isTCPAddr)++ return containers.Endpoint{Host: "127.0.0.1", Port: proxyAddr.Port}, isStalled+}++func pipeUntilStalled(+ ctx context.Context,+ clientConn net.Conn,+ bastion containers.Endpoint,+ isStalled *atomic.Bool,+) {+ defer func() { _ = clientConn.Close() }()++ bastionConn, err := net.DialTimeout("tcp",+ fmt.Sprintf("%s:%d", bastion.Host, bastion.Port), 10*time.Second)+ if err != nil {+ return+ }+ defer func() { _ = bastionConn.Close() }()++ copyUntilStalled := func(dst, src net.Conn) {+ buffer := make([]byte, 32*1024)+ for {+ readCount, readErr := src.Read(buffer)+ if isStalled.Load() {+ // Neither answering nor hanging up is the whole point; unwinding at test end keeps+ // that from outliving the test.+ <-ctx.Done()++ return+ }++ if readCount > 0 {+ if _, writeErr := dst.Write(buffer[:readCount]); writeErr != nil {+ return+ }+ }++ if readErr != nil {+ return+ }+ }+ }++ go copyUntilStalled(bastionConn, clientConn)+ copyUntilStalled(clientConn, bastionConn)+}++// The cached-session branch cannot dial, so this is the only place the caller's deadline reaches it.+// With the keepalive loop's own 15s budget hard-coded here instead, a supervision loop asking for one+// second would block for fifteen between two receiver spawns.+func Test_IsBastionReachable_WhenTheCachedSessionHangs_ReturnsFalseWithinTheCallersDeadline(t *testing.T) {+ bastion := startTestBastion(t)+ proxy, isStalled := startStallableBastionProxy(t, bastion)++ forwarder := openTestForwarder(t, bastionConfig(proxy))++ forwarder.clientMutex.Lock()+ hasCachedClient := forwarder.client != nil+ forwarder.clientMutex.Unlock()+ require.True(t, hasCachedClient, "the probe must take the cached-session branch")++ isStalled.Store(true)++ probeBudget := time.Second++ ctx, cancel := context.WithTimeout(t.Context(), probeBudget)+ defer cancel()++ probeStartedAt := time.Now()++ assert.False(t, forwarder.IsBastionReachable(ctx))+ assert.Less(t, time.Since(probeStartedAt), keepaliveTimeout/2,+ "the probe waited out the keepalive loop's budget instead of the caller's")+}diff --git a/backend/internal/features/tests/logical/mariadb/sshtunnel_test.go b/backend/internal/features/tests/logical/mariadb/sshtunnel_test.goindex 9fdce231..689b6add 100644--- a/backend/internal/features/tests/logical/mariadb/sshtunnel_test.go+++ b/backend/internal/features/tests/logical/mariadb/sshtunnel_test.go@@ -23,6 +23,7 @@ import (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/bastion""databasus-backend/internal/util/testing/containers""databasus-backend/internal/util/tools")@@ -40,7 +41,7 @@ func bastionedMariadbConfig(Password: containers.MariadbRootPassword,Database: &databaseName,Version: tools.MariadbVersion114,- SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ SshTunnel: bastion.GetTunnelConfig(topology),}}diff --git a/backend/internal/features/tests/logical/mongodb/sshtunnel_test.go b/backend/internal/features/tests/logical/mongodb/sshtunnel_test.goindex 514265ad..ffaf68bb 100644--- a/backend/internal/features/tests/logical/mongodb/sshtunnel_test.go+++ b/backend/internal/features/tests/logical/mongodb/sshtunnel_test.go@@ -21,6 +21,7 @@ import (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/bastion""databasus-backend/internal/util/testing/containers""databasus-backend/internal/util/tools")@@ -40,7 +41,7 @@ func bastionedMongodbConfig(AuthDatabase: containers.MongodbAuthDatabase,CpuCount: 1,Version: tools.MongodbVersion7,- SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ SshTunnel: bastion.GetTunnelConfig(topology),}}diff --git a/backend/internal/features/tests/logical/mysql/sshtunnel_test.go b/backend/internal/features/tests/logical/mysql/sshtunnel_test.goindex 66451a6e..ea11dd5e 100644--- a/backend/internal/features/tests/logical/mysql/sshtunnel_test.go+++ b/backend/internal/features/tests/logical/mysql/sshtunnel_test.go@@ -23,6 +23,7 @@ import (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/bastion""databasus-backend/internal/util/testing/containers""databasus-backend/internal/util/tools")@@ -40,7 +41,7 @@ func bastionedMysqlConfig(Password: containers.MysqlRootPassword,Database: &databaseName,Version: tools.MysqlVersion84,- SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ SshTunnel: bastion.GetTunnelConfig(topology),}}diff --git a/backend/internal/features/tests/logical/postgresql/sshtunnel_test.go b/backend/internal/features/tests/logical/postgresql/sshtunnel_test.goindex 1c187841..4e09976f 100644--- a/backend/internal/features/tests/logical/postgresql/sshtunnel_test.go+++ b/backend/internal/features/tests/logical/postgresql/sshtunnel_test.go@@ -23,6 +23,7 @@ import (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/bastion""databasus-backend/internal/util/testing/containers")@@ -38,7 +39,7 @@ func bastionedPostgresConfig(Password: containers.PostgresPassword,Database: &databaseName,CpuCount: 1,- SshTunnel: logicaltesting.BuildBastionTunnelConfig(topology),+ SshTunnel: bastion.GetTunnelConfig(topology),}}diff --git a/backend/internal/features/tests/logical/shared/sshtunnel.go b/backend/internal/features/tests/logical/shared/sshtunnel.goindex 2182092c..f6a9d76f 100644--- a/backend/internal/features/tests/logical/shared/sshtunnel.go+++ b/backend/internal/features/tests/logical/shared/sshtunnel.go@@ -7,19 +7,10 @@ import ("databasus-backend/internal/features/sshtunnel""databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/testing/bastion""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.@@ -27,7 +18,7 @@ func OpenForwardedEndpoint(t *testing.T, topology containers.BastionedDatabase)t.Helper()forwarder, err := sshtunnel.Open(t.Context(), sshtunnel.OpenSpec{- Config: BuildBastionTunnelConfig(topology),+ Config: bastion.GetTunnelConfig(topology),Target: sshtunnel.Endpoint{Host: topology.Database.Host, Port: topology.Database.Port},Logger: logger.GetLogger(),})diff --git a/backend/internal/features/tests/physical/postgresql/pg17/backup_restore_test.go b/backend/internal/features/tests/physical/postgresql/pg17/backup_restore_test.goindex a42974a7..a9265023 100644--- a/backend/internal/features/tests/physical/postgresql/pg17/backup_restore_test.go+++ b/backend/internal/features/tests/physical/postgresql/pg17/backup_restore_test.go@@ -50,3 +50,11 @@ func Test_PhysicalWalSlot_AppearsWhenBackupingStarts_RemovedWhenDatabaseDeleted(func Test_PhysicalWalSlot_WhenDatabaseDeletedWithStreamedWal_SlotRemovedSoNoWalStuck(t *testing.T) {physicaltesting.RunWalSlotWhenDatabaseDeletedWithStreamedWalSlotRemovedSoNoWalStuck(t, pgVersion, pgImage)}++func Test_PhysicalRestore_OverSshTunnel_RecoversToTarget(t *testing.T) {+ physicaltesting.RunOverSshTunnelRecoversToTarget(t, pgVersion, pgImage)+}++func Test_PhysicalWalStream_WhenTheBastionDiesMidStream_KeepsTheSlotAndResumes(t *testing.T) {+ physicaltesting.RunWhenBastionDiesMidStreamKeepsTheSlotAndResumes(t, pgVersion, pgImage)+}diff --git a/backend/internal/features/tests/physical/postgresql/shared/bodies.go b/backend/internal/features/tests/physical/postgresql/shared/bodies.goindex 9e75e821..e14f14d8 100644--- a/backend/internal/features/tests/physical/postgresql/shared/bodies.go+++ b/backend/internal/features/tests/physical/postgresql/shared/bodies.go@@ -357,3 +357,80 @@ func RunWalSlotWhenDatabaseDeletedWithStreamedWalSlotRemovedSoNoWalStuck(t *testrequireDatabaseSlotsGone(t, adminConn, fixture, 60*time.Second)}++// The source publishes no port, so nothing on this path can silently fall back to a direct route.+func RunOverSshTunnelRecoversToTarget(t *testing.T, version, image string) {+ if testing.Short() {+ t.Skip("streams WAL through an SSH bastion and runs a real PITR recovery; skipped in -short")+ }++ router, fixture, topology := setupBastionedFixture(+ t, version, image, postgresql_physical.BackupTypeFullIncrementalAndWalStream)+ target := prepareRestoreTarget(t, image)++ sourceConn := openSourceTestDBConnThroughBastion(t, topology)++ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Minute)+ defer cancel()++ targetTime, survivingPhases := seedChainAndStreamPastTarget(t, ctx, router, sourceConn, fixture)++ bundle := downloadRestoreBundleViaAPI(t, router, fixture, &targetTime)+ reconstructCluster(t, target, router, image, bundle, &targetTime)+ startRestoredCluster(t, target, image)++ restoredPhases := queryRestoredMarkerRows(t, target)+ assert.ElementsMatch(t, survivingPhases, restoredPhases,+ "a chain built entirely through the bastion must restore the same rows as a direct one")+}++// SSH failures are classified apart from receiver crashes, and this is why. Killing the bastion+// makes every pg_receivewal spawn fail instantly, which unclassified reads as five rapid failures:+// the streamer would be marked FAILED and a chain-broken alert sent, leaving nobody consuming the+// slot until a later supervisor tick reclaims it — for a blip the forwarder heals on its own.+func RunWhenBastionDiesMidStreamKeepsTheSlotAndResumes(t *testing.T, version, image string) {+ if testing.Short() {+ t.Skip("stops and restarts a bastion container under a live WAL stream; skipped in -short")+ }++ router, fixture, topology := setupBastionedFixture(+ t, version, image, postgresql_physical.BackupTypeFullIncrementalAndWalStream)++ slotName := fixture.DB.PostgresqlPhysical.ReplicationSlotName+ require.NotEmpty(t, slotName)++ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Minute)+ defer cancel()++ enablePhysicalBackupsViaAPI(t, router, fixture, true)+ waitForChainBackups(t, router, fixture, 0, 5*time.Minute)++ adminConn := postgresql_executor.OpenAdminConn(t, fixture)+ waitForSlotPresent(t, adminConn, slotName, 60*time.Second)++ fullBackupsBeforeOutage := len(waitForChainBackups(t, router, fixture, 0, time.Minute))++ stopBastion(t, topology)++ // Comfortably longer than the five rapid failures plus their 2/4/8/16s backoff would need to+ // escalate, so a regression has every chance to tear the streamer down before we look.+ time.Sleep(75 * time.Second)++ requireStreamerNotFailed(t, fixture)++ startBastion(t, topology)++ resumedConn := postgresql_executor.OpenAdminConn(t, fixture)+ require.True(t, postgresql_executor.SlotExists(t, resumedConn, slotName),+ "the slot must survive the outage: rebuilding it opens a WAL gap and costs a fresh full backup")++ segmentsBeforeResume := getCommittedWalSegmentCount(t, fixture)++ _, err := postgresql_executor.GenerateWalActivity(ctx, resumedConn, 64*1024*1024)+ require.NoError(t, err)++ waitForCommittedWalSegmentsAbove(t, fixture, segmentsBeforeResume, 3*time.Minute)++ assert.Len(t, waitForChainBackups(t, router, fixture, 0, time.Minute), fullBackupsBeforeOutage,+ "a transport blip must not request an out-of-cadence full backup")+}diff --git a/backend/internal/features/tests/physical/postgresql/shared/helpers.go b/backend/internal/features/tests/physical/postgresql/shared/helpers.goindex 2573a17c..3de86a30 100644--- a/backend/internal/features/tests/physical/postgresql/shared/helpers.go+++ b/backend/internal/features/tests/physical/postgresql/shared/helpers.go@@ -49,6 +49,10 @@ const (restoredPgUser = "testuser"restoredPgPassword = "testpassword"restoredPgDatabase = "testdb"++ // Replaying a PITR chain is disk-bound and runs while the test holds several containers, so this+ // is sized for a loaded machine rather than for the few seconds it takes when idle.+ recoveryCompletionTimeout = 3 * time.Minute)// setupReplicationOnlyFixture boots a throwaway replication-capable source for one PostgreSQL major,@@ -935,6 +939,29 @@ func startRestoredCluster(t *testing.T, target containers.RestoreTarget, image starget.ExecBestEffort("postgres","pg_ctl", "-D", clusterDir, "-m", "immediate", "stop")})++ waitForRecoveryToFinish(t, target)+}++// pg_ctl -w returns as soon as the cluster accepts connections, which during recovery means+// read-only and mid-replay: a query issued then sees whichever prefix of the WAL has been applied so+// far. Recovery with a target promotes when it reaches it, so leaving recovery is the real signal+// that the restored data is complete.+func waitForRecoveryToFinish(t *testing.T, target containers.RestoreTarget) {+ t.Helper()++ deadline := time.Now().UTC().Add(recoveryCompletionTimeout)+ for time.Now().UTC().Before(deadline) {+ recoveryState := target.ExecBestEffort("postgres",+ "psql", "-U", restoredPgUser, "-d", restoredPgDatabase, "-tAc", "SELECT pg_is_in_recovery()")+ if strings.TrimSpace(string(recoveryState)) == "f" {+ return+ }++ time.Sleep(500 * time.Millisecond)+ }++ t.Fatalf("the restored cluster was still replaying WAL after %s", recoveryCompletionTimeout)}func queryRestoredMarkerRows(t *testing.T, target containers.RestoreTarget) []string {diff --git a/backend/internal/features/tests/physical/postgresql/shared/sshtunnel.go b/backend/internal/features/tests/physical/postgresql/shared/sshtunnel.gonew file mode 100644index 00000000..b41ea199--- /dev/null+++ b/backend/internal/features/tests/physical/postgresql/shared/sshtunnel.go@@ -0,0 +1,167 @@+package physicaltesting++import (+ "context"+ "net"+ "strconv"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/jackc/pgx/v5"+ "github.com/stretchr/testify/require"++ physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+ physical_repositories "databasus-backend/internal/features/backups/backups/core/physical/repositories"+ postgresql_executor "databasus-backend/internal/features/backups/backups/usecases/physical/postgresql"+ "databasus-backend/internal/features/databases"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"+ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/testing/bastion"+ "databasus-backend/internal/util/testing/containers"+ "databasus-backend/internal/util/walmath"+)++// The source cluster publishes no port, so every connection the backend makes has to go through the+// bastion. A direct route would keep these tests green after the tunnel stopped being used.+func setupBastionedFixture(+ t *testing.T,+ version string,+ image string,+ backupType postgresql_physical.BackupType,+) (*gin.Engine, *postgresql_executor.PhysicalDBFixture, containers.BastionedDatabase) {+ t.Helper()++ topology := containers.StartPhysicalPostgresBehindSshBastion(t, image)++ router := newPhysicalTestRouter()+ fixture := postgresql_executor.SetupPhysicalDBFixtureWithTunnel(t, databases.PhysicalTestDatabaseSpec{+ Host: topology.Database.Host,+ Port: topology.Database.Port,+ VersionTag: version,+ BackupType: backupType,+ SshTunnel: bastion.GetTunnelConfig(topology),+ })++ return router, fixture, topology+}++// The test has no other route to the bastioned cluster, so it reaches it the same way the backend+// does. The forwarder is the test's own on purpose: stopping the bastion has to break both it and+// the backend's, and reopening this one must not repair the backend's.+//+// It lands on the seeded test database rather than `postgres`, because that is where the marker rows+// the restore is asserted against live.+func openSourceTestDBConnThroughBastion(+ t *testing.T,+ topology containers.BastionedDatabase,+) *pgx.Conn {+ t.Helper()++ localEndpoint := openForwardedEndpoint(t, topology)++ return openConnAt(t, localEndpoint.Host, localEndpoint.Port)+}++func openForwardedEndpoint(t *testing.T, topology containers.BastionedDatabase) sshtunnel.Endpoint {+ t.Helper()++ forwarder, err := sshtunnel.Open(t.Context(), sshtunnel.OpenSpec{+ Config: bastion.GetTunnelConfig(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()+}++func stopBastion(t *testing.T, topology containers.BastionedDatabase) {+ t.Helper()++ stopTimeout := 10 * time.Second+ require.NoError(t, topology.BastionContainer.Stop(context.Background(), &stopTimeout))+}++func startBastion(t *testing.T, topology containers.BastionedDatabase) {+ t.Helper()++ require.NoError(t, topology.BastionContainer.Start(context.Background()))+ waitForBastionAccepting(t, topology.Bastion, 90*time.Second)+}++// Dialling rather than checking the container state: a running container whose sshd has not finished+// binding still refuses connections. The address is the one from before the outage on purpose — the+// backend's forwarder has been retrying it all along, and if the restart moved it the premise of the+// test is gone rather than merely slow.+func waitForBastionAccepting(t *testing.T, bastion containers.Endpoint, timeout time.Duration) {+ t.Helper()++ address := net.JoinHostPort(bastion.Host, strconv.Itoa(bastion.Port))+ dialer := net.Dialer{Timeout: time.Second}++ deadline := time.Now().UTC().Add(timeout)+ for time.Now().UTC().Before(deadline) {+ conn, err := dialer.DialContext(context.Background(), "tcp", address)+ if err == nil {+ _ = conn.Close()++ return+ }++ time.Sleep(500 * time.Millisecond)+ }++ t.Fatalf("the bastion never accepted connections at %s again within %s", address, timeout)+}++// A FAILED row is how the supervisor hands a streamer back for reclaim, so it is exactly what an+// unclassified transport outage would leave behind.+func requireStreamerNotFailed(t *testing.T, fixture *postgresql_executor.PhysicalDBFixture) {+ t.Helper()++ streamer, err := physical_repositories.GetWalStreamerRepository().FindByDatabaseID(fixture.DB.ID)+ require.NoError(t, err)+ require.NotNil(t, streamer, "the supervisor must still own the streamer")+ require.NotEqual(t, physical_enums.PhysicalWalStreamerStatusFailed, streamer.Status)+}++func getCommittedWalSegmentCount(t *testing.T, fixture *postgresql_executor.PhysicalDBFixture) int {+ t.Helper()++ segments, err := physical_repositories.GetWalSegmentRepository().FindByChainSpan(+ fixture.DB.ID, 1, walmath.LSN(0), walmath.LSN(^uint64(0)),+ )+ require.NoError(t, err)++ committedCount := 0+ for _, segment := range segments {+ if segment.FileName != nil {+ committedCount+++ }+ }++ return committedCount+}++func waitForCommittedWalSegmentsAbove(+ t *testing.T,+ fixture *postgresql_executor.PhysicalDBFixture,+ previousCount int,+ timeout time.Duration,+) {+ t.Helper()++ deadline := time.Now().UTC().Add(timeout)+ for time.Now().UTC().Before(deadline) {+ if getCommittedWalSegmentCount(t, fixture) > previousCount {+ return+ }++ time.Sleep(500 * time.Millisecond)+ }++ t.Fatalf("no WAL segment was archived within %s after the bastion came back", timeout)+}diff --git a/backend/internal/util/testing/bastion/bastion.go b/backend/internal/util/testing/bastion/bastion.gonew file mode 100644index 00000000..ed485d25--- /dev/null+++ b/backend/internal/util/testing/bastion/bastion.go@@ -0,0 +1,21 @@+// Package bastion builds the SSH tunnel configuration that reaches a bastioned test topology.+//+// It sits apart from containers because containers must not import features: sshtunnel's own tests+// live in package sshtunnel and import containers, so the reverse edge would be an import cycle.+// Putting it in sshtunnel instead would pull testcontainers into the production build graph.+package bastion++import (+ "databasus-backend/internal/features/sshtunnel"+ "databasus-backend/internal/util/testing/containers"+)++func GetTunnelConfig(bastionedDatabase containers.BastionedDatabase) sshtunnel.Config {+ return sshtunnel.Config{+ IsEnabled: true,+ Host: bastionedDatabase.Bastion.Host,+ Port: bastionedDatabase.Bastion.Port,+ Username: containers.SshBastionUsername,+ Password: containers.SshBastionPassword,+ }+}diff --git a/backend/internal/util/testing/containers/postgres_physical.go b/backend/internal/util/testing/containers/postgres_physical.goindex 4cec8f0e..57890754 100644--- a/backend/internal/util/testing/containers/postgres_physical.go+++ b/backend/internal/util/testing/containers/postgres_physical.go@@ -130,11 +130,46 @@ func physicalPostgresCmd(opts physicalPostgresOptions) []string {func StartPhysicalPostgres(t *testing.T, image string, opts ...PhysicalPostgresOption) Endpoint {t.Helper()+ return start(t, physicalPostgresRequest(image, resolvePhysicalPostgresOptions(opts)), postgresPort)+}++// The database publishes no ports and the bastion does, so a tunnel is the only way in — a direct+// route would keep the tunnel tests green after the tunnel stopped being used.+func StartPhysicalPostgresBehindSshBastion(+ t *testing.T,+ image string,+ opts ...PhysicalPostgresOption,+) BastionedDatabase {+ t.Helper()++ networkName := StartNetwork(t)+ bastion := StartSshBastionContainerOnNetwork(t, networkName)++ req := physicalPostgresRequest(image, resolvePhysicalPostgresOptions(opts))+ // postgresReady 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)++ placement := NetworkPlacement{NetworkName: networkName, Alias: bastionedPhysicalPostgresAlias}+ startUnpublished(t, req, placement)++ return BastionedDatabase{+ Bastion: bastion.Endpoint,+ BastionContainer: bastion.Container,+ Database: Endpoint{Host: placement.Alias, Port: getPortNumber(postgresPort)},+ }+}++func resolvePhysicalPostgresOptions(opts []PhysicalPostgresOption) physicalPostgresOptions {options := physicalPostgresOptions{summarizeWal: true}for _, apply := range opts {apply(&options)}+ return options+}++func physicalPostgresRequest(image string, options physicalPostgresOptions) testcontainers.ContainerRequest {var files []testcontainers.ContainerFileif !options.omitReplicationHbaEntry {files = append(files, allowReplicationInitScript())@@ -143,7 +178,7 @@ func StartPhysicalPostgres(t *testing.T, image string, opts ...PhysicalPostgresOfiles = append(files, createTablespaceInitScript())}- req := testcontainers.ContainerRequest{+ return testcontainers.ContainerRequest{Image: image,ExposedPorts: []string{postgresPort},Env: postgresEnv(),@@ -152,8 +187,6 @@ func StartPhysicalPostgres(t *testing.T, image string, opts ...PhysicalPostgresOTmpfs: map[string]string{postgresDataDir(image): physicalDataDirTmpfsOptions},WaitingFor: postgresReady(),}-- return start(t, req, postgresPort)}// StartPhysicalPrimaryWithStandby boots a replication-capable primary and a streaming standby that@@ -200,25 +233,9 @@ func startPhysicalPrimaryOnNetwork() Endpoint {t.Helper()- var files []testcontainers.ContainerFile- if !options.omitReplicationHbaEntry {- files = append(files, allowReplicationInitScript())- }- if options.withTablespace {- files = append(files, createTablespaceInitScript())- }-- req := testcontainers.ContainerRequest{- Image: image,- ExposedPorts: []string{postgresPort},- Env: postgresEnv(),- Cmd: physicalPostgresCmd(options),- Files: files,- Tmpfs: map[string]string{postgresDataDir(image): physicalDataDirTmpfsOptions},- Networks: []string{networkName},- NetworkAliases: map[string][]string{networkName: {physicalPrimaryAlias}},- WaitingFor: postgresReady(),- }+ req := physicalPostgresRequest(image, options)+ req.Networks = []string{networkName}+ req.NetworkAliases = map[string][]string{networkName: {physicalPrimaryAlias}}return start(t, req, postgresPort)}diff --git a/backend/internal/util/testing/containers/ssh_bastion.go b/backend/internal/util/testing/containers/ssh_bastion.goindex 424187e8..390492ca 100644--- a/backend/internal/util/testing/containers/ssh_bastion.go+++ b/backend/internal/util/testing/containers/ssh_bastion.go@@ -1,11 +1,17 @@package containersimport (+ "context"+ "net"+ "net/netip""path/filepath""runtime"+ "strconv""testing""time"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/api/types/network""github.com/testcontainers/testcontainers-go""github.com/testcontainers/testcontainers-go/wait")@@ -28,14 +34,16 @@ func StartSshBastion(t *testing.T) Endpoint {}// 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 {+// bastion in turn reach containers that publish nothing. The container comes back too, so a test can+// stop and restart the bastion under a running tunnel.+func StartSshBastionContainerOnNetwork(t *testing.T, networkName string) ContainerHandle {t.Helper()req := sshBastionRequest(t)req.Networks = []string{networkName}+ pinBastionHostPort(t, &req)- return start(t, req, sshBastionPort)+ return startContainer(t, req, sshBastionPort)}// Resolved from this file rather than the working directory: callers live in other packages, and@@ -52,10 +60,12 @@ func GetSshBastionTestdataDir(t *testing.T) string {return filepath.Join(filepath.Dir(thisFile), "testdata", "ssh_bastion")}-// Database is the in-network address, reachable only through Bastion.+// Database is the in-network address, reachable only through Bastion. BastionContainer is what lets+// a test kill the transport mid-stream and bring it back.type BastionedDatabase struct {- Bastion Endpoint- Database Endpoint+ Bastion Endpoint+ BastionContainer testcontainers.Container+ Database Endpoint}// One alias per engine so a run that boots several topologies stays readable in docker inspect.@@ -64,6 +74,8 @@ const (bastionedMysqlAlias = "mysql-behind-bastion"bastionedMariadbAlias = "mariadb-behind-bastion"bastionedMongodbAlias = "mongodb-behind-bastion"++ bastionedPhysicalPostgresAlias = "physical-postgres-behind-bastion")// The database publishes no ports and the bastion does, so a tunnel is the only way in. Tests@@ -74,8 +86,11 @@ func StartPostgresBehindSshBastion(t *testing.T, image string) BastionedDatabasenetworkName := StartNetwork(t)+ bastion := StartSshBastionContainerOnNetwork(t, networkName)+return BastionedDatabase{- Bastion: StartSshBastionOnNetwork(t, networkName),+ Bastion: bastion.Endpoint,+ BastionContainer: bastion.Container,Database: StartPostgresOnNetwork(t, OnNetworkSpec{Image: image,Placement: NetworkPlacement{@@ -91,8 +106,11 @@ func StartMysqlBehindSshBastion(t *testing.T, image string) BastionedDatabase {networkName := StartNetwork(t)+ bastion := StartSshBastionContainerOnNetwork(t, networkName)+return BastionedDatabase{- Bastion: StartSshBastionOnNetwork(t, networkName),+ Bastion: bastion.Endpoint,+ BastionContainer: bastion.Container,Database: StartMysqlOnNetwork(t, OnNetworkSpec{Image: image,Placement: NetworkPlacement{@@ -108,8 +126,11 @@ func StartMariadbBehindSshBastion(t *testing.T, image string) BastionedDatabasenetworkName := StartNetwork(t)+ bastion := StartSshBastionContainerOnNetwork(t, networkName)+return BastionedDatabase{- Bastion: StartSshBastionOnNetwork(t, networkName),+ Bastion: bastion.Endpoint,+ BastionContainer: bastion.Container,Database: StartMariadbOnNetwork(t, OnNetworkSpec{Image: image,Placement: NetworkPlacement{@@ -125,8 +146,11 @@ func StartMongodbBehindSshBastion(t *testing.T, image string) BastionedDatabasenetworkName := StartNetwork(t)+ bastion := StartSshBastionContainerOnNetwork(t, networkName)+return BastionedDatabase{- Bastion: StartSshBastionOnNetwork(t, networkName),+ Bastion: bastion.Endpoint,+ BastionContainer: bastion.Container,Database: StartMongodbOnNetwork(t, OnNetworkSpec{Image: image,Placement: NetworkPlacement{@@ -137,6 +161,42 @@ func StartMongodbBehindSshBastion(t *testing.T, image string) BastionedDatabase}}+// Docker re-picks an ephemeral host port on every `start`, so a bastion published dynamically moves+// out from under a tunnel the moment a test restarts it. Pinning the binding is what a real bastion+// has anyway, and it is the only way a forwarder can find its way back after an outage.+func pinBastionHostPort(t *testing.T, req *testcontainers.ContainerRequest) {+ t.Helper()++ var listenConfig net.ListenConfig++ listener, err := listenConfig.Listen(context.Background(), "tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to reserve a host port for the ssh bastion: %v", err)+ }++ reservedPort, isTCPAddr := listener.Addr().(*net.TCPAddr)+ if !isTCPAddr {+ t.Fatalf("failed to read the reserved ssh bastion port from %s", listener.Addr())+ }++ if err := listener.Close(); err != nil {+ t.Fatalf("failed to release the reserved ssh bastion port: %v", err)+ }++ bastionPort, err := network.ParsePort(sshBastionPort)+ if err != nil {+ t.Fatalf("failed to parse the ssh bastion port %q: %v", sshBastionPort, err)+ }++ req.HostConfigModifier = func(hostConfig *container.HostConfig) {+ hostConfig.PortBindings = network.PortMap{+ bastionPort: []network.PortBinding{+ {HostIP: netip.MustParseAddr("127.0.0.1"), HostPort: strconv.Itoa(reservedPort.Port)},+ },+ }+ }+}+func sshBastionRequest(t *testing.T) testcontainers.ContainerRequest {return testcontainers.ContainerRequest{FromDockerfile: testcontainers.FromDockerfile{diff --git a/backend/migrations/20260813053858_add_ssh_tunnel_to_physical_databases.sql b/backend/migrations/20260813053858_add_ssh_tunnel_to_physical_databases.sqlnew file mode 100644index 00000000..437871f5--- /dev/null+++ b/backend/migrations/20260813053858_add_ssh_tunnel_to_physical_databases.sql@@ -0,0 +1,47 @@+-- +goose Up+-- +goose StatementBegin+ALTER TABLE postgresql_physical_databases+ ADD COLUMN IF NOT EXISTS ssh_is_enabled BOOLEAN NOT NULL DEFAULT FALSE;++ALTER TABLE postgresql_physical_databases+ ADD COLUMN IF NOT EXISTS ssh_host TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_physical_databases+ ADD COLUMN IF NOT EXISTS ssh_port INTEGER NOT NULL DEFAULT 22;++ALTER TABLE postgresql_physical_databases+ ADD COLUMN IF NOT EXISTS ssh_username TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_physical_databases+ ADD COLUMN IF NOT EXISTS ssh_password TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_physical_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key TEXT NOT NULL DEFAULT '';++ALTER TABLE postgresql_physical_databases+ ADD COLUMN IF NOT EXISTS ssh_private_key_passphrase TEXT NOT NULL DEFAULT '';+-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin+ALTER TABLE postgresql_physical_databases+ DROP COLUMN IF EXISTS ssh_private_key_passphrase;++ALTER TABLE postgresql_physical_databases+ DROP COLUMN IF EXISTS ssh_private_key;++ALTER TABLE postgresql_physical_databases+ DROP COLUMN IF EXISTS ssh_password;++ALTER TABLE postgresql_physical_databases+ DROP COLUMN IF EXISTS ssh_username;++ALTER TABLE postgresql_physical_databases+ DROP COLUMN IF EXISTS ssh_port;++ALTER TABLE postgresql_physical_databases+ DROP COLUMN IF EXISTS ssh_host;++ALTER TABLE postgresql_physical_databases+ DROP COLUMN IF EXISTS ssh_is_enabled;+-- +goose StatementEnddiff --git a/frontend/src/entity/databases/model/postgresql/physical/PostgresqlPhysicalDatabase.ts b/frontend/src/entity/databases/model/postgresql/physical/PostgresqlPhysicalDatabase.tsindex 853ac587..86c86d5e 100644--- a/frontend/src/entity/databases/model/postgresql/physical/PostgresqlPhysicalDatabase.ts+++ b/frontend/src/entity/databases/model/postgresql/physical/PostgresqlPhysicalDatabase.ts@@ -1,3 +1,4 @@+import type { SshTunnelConfig } from '../../sshtunnel/SshTunnelConfig';import type { PostgresSslMode } from '../PostgresSslMode';import type { PostgresqlVersion } from '../PostgresqlVersion';import type { PhysicalDatabaseBackupType } from './PhysicalDatabaseBackupType';@@ -23,6 +24,9 @@ export interface PostgresqlPhysicalDatabase {sslClientKey?: string;sslRootCert?: string;+ // When enabled, host and port above address the cluster as the bastion sees it.+ sshTunnel?: SshTunnelConfig;+// server-managed identity, read-only - set by the backend on first connect and// immutable afterwards (a changed value means the cluster was swapped)systemIdentifier?: string;diff --git a/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsxindex 51fc6795..a776cfb1 100644--- a/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsx@@ -10,6 +10,8 @@ import {PostgresSslMode,type PostgresqlPhysicalDatabase,databaseApi,+ hasStoredSshTunnelSecrets,+ isSshTunnelReadyToTest,physicalConnectionErrorContent,} from '../../../../entity/databases';import { ConnectionStringParser } from '../../../../entity/databases/model/postgresql/ConnectionStringParser';@@ -17,6 +19,7 @@ import { ApiError } from '../../../../shared/api';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';import { ClipboardPasteModalComponent } from '../../../../shared/ui';+import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {database: Database;@@ -448,6 +451,8 @@ export const EditPostgreSqlPhysicalSpecificDataComponent = ({if (!editingDatabase.postgresqlPhysical?.username) isAllFieldsFilled = false;if (!editingDatabase.id && !editingDatabase.postgresqlPhysical?.password)isAllFieldsFilled = false;+ if (!isSshTunnelReadyToTest(editingDatabase.postgresqlPhysical?.sshTunnel, hasStoredSshSecrets))+ isAllFieldsFilled = false;return (<>@@ -590,6 +595,20 @@ export const EditPostgreSqlPhysicalSpecificDataComponent = ({/></div>+ <EditSshTunnelComponent+ sshTunnel={editingDatabase.postgresqlPhysical?.sshTunnel}+ hasStoredSecrets={hasStoredSshSecrets}+ onChange={(sshTunnel) => {+ if (!editingDatabase.postgresqlPhysical) return;++ setEditingDatabase({+ ...editingDatabase,+ postgresqlPhysical: { ...editingDatabase.postgresqlPhysical, sshTunnel },+ });+ setIsConnectionTested(false);+ }}+ />+<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">SSL mode</div><Select@@ -650,6 +669,11 @@ export const EditPostgreSqlPhysicalSpecificDataComponent = ({);};+ const hasStoredSshSecrets = hasStoredSshTunnelSecrets(+ database.postgresqlPhysical?.sshTunnel,+ database.id,+ );+return (<div>{renderForm()}diff --git a/frontend/src/features/databases/ui/show/ShowPostgreSqlPhysicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/show/ShowPostgreSqlPhysicalSpecificDataComponent.tsxindex e4cd3a88..6a134b91 100644--- a/frontend/src/features/databases/ui/show/ShowPostgreSqlPhysicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/show/ShowPostgreSqlPhysicalSpecificDataComponent.tsx@@ -4,6 +4,7 @@ import {PostgresSslMode,PostgresqlVersion,} from '../../../../entity/databases';+import { ShowSshTunnelComponent } from './ShowSshTunnelComponent';interface Props {database: Database;@@ -85,6 +86,8 @@ export const ShowPostgreSqlPhysicalSpecificDataComponent = ({ database }: Props)<div>*************</div></div>)}++ <ShowSshTunnelComponent sshTunnel={database.postgresqlPhysical?.sshTunnel} /></div>);};