Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: route gh-ost through SSH tunnel (#20304)
rebelice9c2054f90c37
diff --git a/backend/component/ghost/config.go b/backend/component/ghost/config.goindex 81cba79da8..366588ac91 100644--- a/backend/component/ghost/config.go+++ b/backend/component/ghost/config.go@@ -3,12 +3,15 @@ package ghostimport ("context""log/slog"+ "net""os""strconv""strings"ghostbase "github.com/github/gh-ost/go/base"ghostsql "github.com/github/gh-ost/go/sql"+ gomysql "github.com/go-sql-driver/mysql"+ "github.com/google/uuid""github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"@@ -18,6 +21,15 @@ import ("github.com/bytebase/bytebase/backend/store")+type sshDialer interface {+ DialContext(context.Context, string, string) (net.Conn, error)+ Close() error+}++var getSSHDialer = func(dataSource *storepb.DataSource) (sshDialer, error) {+ return util.GetSSHClient(dataSource)+}+var defaultConfig = struct {attemptInstantDDL boolallowedRunningOnMaster bool@@ -204,10 +216,10 @@ func GetUserFlags(flags map[string]string) (*UserFlags, error) {}// NewMigrationContext is the context for gh-ost migration.-func NewMigrationContext(ctx context.Context, taskID int64, database *store.DatabaseMessage, dataSource *storepb.DataSource, tableName string, tmpTableNameSuffix string, statement string, noop bool, flags map[string]string, serverIDOffset uint) (*ghostbase.MigrationContext, error) {+func NewMigrationContext(ctx context.Context, taskID int64, database *store.DatabaseMessage, dataSource *storepb.DataSource, tableName string, tmpTableNameSuffix string, statement string, noop bool, flags map[string]string, serverIDOffset uint) (*ghostbase.MigrationContext, func(), error) { // NOSONAR(go:S107) This existing internal API wires gh-ost configuration fields explicitly.resolvedDataSource, err := util.ResolveTLSMaterial(dataSource)if err != nil {- return nil, err+ return nil, nil, err}if resolvedDataSource != nil {dataSource = resolvedDataSource@@ -215,7 +227,7 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.Datapassword, err := secretcomp.ReplaceExternalSecret(ctx, dataSource.GetPassword(), dataSource.GetExternalSecret())if err != nil {- return nil, err+ return nil, nil, err}migrationContext := ghostbase.NewMigrationContext()@@ -225,7 +237,7 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.Dataif dataSource.GetPort() != "" {dsPort, err := strconv.Atoi(dataSource.GetPort())if err != nil {- return nil, errors.Wrap(err, "failed to convert port from string to int")+ return nil, nil, errors.Wrap(err, "failed to convert port from string to int")}port = dsPort}@@ -235,12 +247,12 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.DatatlsCleanup, err := writeTLSMaterialTempFiles(dataSource, migrationContext)if err != nil {- return nil, err+ return nil, nil, err}defer tlsCleanup()if err := migrationContext.SetupTLS(); err != nil {- return nil, errors.Wrapf(err, "failed to set up tls")+ return nil, nil, errors.Wrapf(err, "failed to set up tls")}}migrationContext.InspectorConnectionConfig.Key.Port = port@@ -259,7 +271,7 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.DatamigrationContext.ReplicaServerId = serverIDOffset + uint(taskID)// set defaultsif err := migrationContext.SetConnectionConfig(""); err != nil {- return nil, err+ return nil, nil, err}migrationContext.AttemptInstantDDL = defaultConfig.attemptInstantDDLmigrationContext.AllowedRunningOnMaster = defaultConfig.allowedRunningOnMaster@@ -270,20 +282,20 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.DatamigrationContext.ThrottleHTTPTimeoutMillis = defaultConfig.throttleHTTPTimeoutMillisif migrationContext.AlterStatement == "" {- return nil, errors.Errorf("alterStatement must be provided and must not be empty")+ return nil, nil, errors.Errorf("alterStatement must be provided and must not be empty")}parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()if migrationContext.DatabaseName == "" {if !parser.HasExplicitSchema() {- return nil, errors.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")+ return nil, nil, errors.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")}migrationContext.DatabaseName = parser.GetExplicitSchema()}if migrationContext.OriginalTableName == "" {if !parser.HasExplicitTable() {- return nil, errors.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")+ return nil, nil, errors.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")}migrationContext.OriginalTableName = parser.GetExplicitTable()}@@ -313,22 +325,22 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.DatamigrationContext.SetDefaultNumRetries(defaultConfig.defaultNumRetries)migrationContext.ApplyCredentials()if err := migrationContext.SetCutOverLockTimeoutSeconds(defaultConfig.cutoverLockTimeoutSeconds); err != nil {- return nil, err+ return nil, nil, err}if err := migrationContext.SetExponentialBackoffMaxInterval(defaultConfig.exponentialBackoffMaxInterval); err != nil {- return nil, err+ return nil, nil, err}userFlags, err := GetUserFlags(flags)if err != nil {- return nil, errors.Wrapf(err, "failed to get user flags")+ return nil, nil, errors.Wrapf(err, "failed to get user flags")}if v := userFlags.attemptInstantDDL; v != nil {migrationContext.AttemptInstantDDL = *v}if v := userFlags.maxLoad; v != nil {if err := migrationContext.ReadMaxLoad(*v); err != nil {- return nil, errors.Wrapf(err, "failed to parse max load %q", *v)+ return nil, nil, errors.Wrapf(err, "failed to parse max load %q", *v)}}if v := userFlags.chunkSize; v != nil {@@ -342,12 +354,12 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.Data}if v := userFlags.cutoverLockTimeoutSeconds; v != nil {if err := migrationContext.SetCutOverLockTimeoutSeconds(*v); err != nil {- return nil, errors.Wrapf(err, "failed to set cutover lock timeout %d", *v)+ return nil, nil, errors.Wrapf(err, "failed to set cutover lock timeout %d", *v)}}if v := userFlags.exponentialBackoffMaxInterval; v != nil {if err := migrationContext.SetExponentialBackoffMaxInterval(*v); err != nil {- return nil, errors.Wrapf(err, "failed to set exponential backoff max interval %d", *v)+ return nil, nil, errors.Wrapf(err, "failed to set exponential backoff max interval %d", *v)}}if v := userFlags.maxLagMillis; v != nil {@@ -370,7 +382,7 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.Data}if v := userFlags.throttleControlReplicas; v != nil {if err := migrationContext.ReadThrottleControlReplicaKeys(*v); err != nil {- return nil, errors.Wrapf(err, "failed to set throttleControlReplicas")+ return nil, nil, errors.Wrapf(err, "failed to set throttleControlReplicas")}}if v := userFlags.assumeMasterHost; v != nil && *v {@@ -385,9 +397,50 @@ func NewMigrationContext(ctx context.Context, taskID int64, database *store.DatamigrationContext.ForceTmpTableName = tableName + tmpTableNameSuffixif migrationContext.SwitchToRowBinlogFormat && migrationContext.AssumeRBR {- return nil, errors.Errorf("switchToRBR and assumeRBR are mutually exclusive")+ return nil, nil, errors.Errorf("switchToRBR and assumeRBR are mutually exclusive")+ }+ cleanup, err := setupSSHNetwork(dataSource, migrationContext)+ if err != nil {+ return nil, nil, err+ }+ return migrationContext, cleanup, nil+}++func setupSSHNetwork(dataSource *storepb.DataSource, migrationContext *ghostbase.MigrationContext) (func(), error) {+ if dataSource.GetSshHost() == "" {+ return noopCleanup, nil}- return migrationContext, nil++ sshClient, err := getSSHDialer(dataSource)+ if err != nil {+ return nil, err+ }++ network := "mysql-tcp-" + uuid.NewString()[:8]+ gomysql.RegisterDialContext(network, func(ctx context.Context, addr string) (net.Conn, error) {+ if sshClient == nil {+ return nil, errors.New("ssh client is not initialized")+ }+ return sshClient.DialContext(ctx, "tcp", addr)+ })+ migrationContext.InspectorConnectionConfig.Network = network+ migrationContext.InspectorConnectionConfig.Dialer = func(ctx context.Context, network, address string) (net.Conn, error) {+ if sshClient == nil {+ return nil, errors.New("ssh client is not initialized")+ }+ return sshClient.DialContext(ctx, network, address)+ }++ return func() {+ gomysql.DeregisterDialContext(network)+ if sshClient != nil {+ _ = sshClient.Close()+ }+ }, nil+}++func noopCleanup() {+ // No resource is allocated when SSH tunneling is disabled.}func writeTLSMaterialTempFiles(dataSource *storepb.DataSource, migrationContext *ghostbase.MigrationContext) (func(), error) {diff --git a/backend/component/ghost/config_test.go b/backend/component/ghost/config_test.goindex b27b3039f1..a2edc29102 100644--- a/backend/component/ghost/config_test.go+++ b/backend/component/ghost/config_test.go@@ -6,9 +6,14 @@ import ("crypto/rsa""crypto/x509""crypto/x509/pkix"+ "database/sql""encoding/pem"+ "errors"+ "fmt""math/big"+ "net""path/filepath"+ "strings""testing""time"@@ -35,8 +40,9 @@ func TestNewMigrationContextWritesTLSMaterialToTempFiles(t *testing.T) {AuthenticationType: storepb.DataSource_PASSWORD,}- migrationContext, err := NewMigrationContext(ctx, 1, database, dataSource, "t", "_suffix", "ALTER TABLE t ADD COLUMN c INT", false, nil, 0)+ migrationContext, cleanup, err := NewMigrationContext(ctx, 1, database, dataSource, "t", "_suffix", "ALTER TABLE t ADD COLUMN c INT", false, nil, 0)require.NoError(t, err)+ t.Cleanup(cleanup)require.True(t, migrationContext.UseTLS)require.True(t, migrationContext.TLSAllowInsecure)require.True(t, filepath.IsAbs(migrationContext.TLSCACertificate))@@ -66,11 +72,75 @@ func TestNewMigrationContextRespectsVerifyTlsCertificate(t *testing.T) {SslKey: keyPEM,}- migrationContext, err := NewMigrationContext(ctx, 1, database, dataSource, "t", "_suffix", "ALTER TABLE t ADD COLUMN c INT", false, nil, 0)+ migrationContext, cleanup, err := NewMigrationContext(ctx, 1, database, dataSource, "t", "_suffix", "ALTER TABLE t ADD COLUMN c INT", false, nil, 0)require.NoError(t, err)+ t.Cleanup(cleanup)require.False(t, migrationContext.TLSAllowInsecure)}+func TestNewMigrationContextUsesSSHNetworkDialersAndCleanup(t *testing.T) {+ originalGetSSHDialer := getSSHDialer+ fakeDialer := &fakeSSHDialer{}+ getSSHDialer = func(_ *storepb.DataSource) (sshDialer, error) {+ return fakeDialer, nil+ }+ t.Cleanup(func() {+ getSSHDialer = originalGetSSHDialer+ })++ ctx := context.Background()+ database := &store.DatabaseMessage{DatabaseName: "ghostdb"}+ dataSource := &storepb.DataSource{+ Host: "172.29.0.10",+ Port: "3306",+ Username: "root",+ Password: "root",+ SshHost: "127.0.0.1",+ SshPort: "2222",+ SshUser: "bb",+ AuthenticationType: storepb.DataSource_PASSWORD,+ }++ migrationContext, cleanup, err := NewMigrationContext(ctx, 1, database, dataSource, "t", "_suffix", "ALTER TABLE t ADD COLUMN c INT", false, nil, 0)+ require.NoError(t, err)+ cleanedUp := false+ t.Cleanup(func() {+ if !cleanedUp {+ cleanup()+ }+ })+ require.True(t, strings.HasPrefix(migrationContext.InspectorConnectionConfig.Network, "mysql-tcp-"))+ require.NotNil(t, migrationContext.InspectorConnectionConfig.Dialer)++ sqlCtx := context.WithValue(ctx, dialContextKey{}, "sql")+ db, err := sql.Open("mysql", fmt.Sprintf("%s@%s(%s)/%s", dataSource.GetUsername(), migrationContext.InspectorConnectionConfig.Network, dataSource.GetHost()+":"+dataSource.GetPort(), database.DatabaseName))+ require.NoError(t, err)+ t.Cleanup(func() {+ _ = db.Close()+ })+ require.ErrorIs(t, db.PingContext(sqlCtx), errFakeDial)+ require.Len(t, fakeDialer.calls, 1)+ require.Equal(t, "sql", fakeDialer.calls[0].contextValue)+ require.Equal(t, "tcp", fakeDialer.calls[0].network)+ require.Equal(t, dataSource.GetHost()+":"+dataSource.GetPort(), fakeDialer.calls[0].address)++ binlogCtx := context.WithValue(ctx, dialContextKey{}, "binlog")+ _, err = migrationContext.InspectorConnectionConfig.Dialer(binlogCtx, "tcp", dataSource.GetHost()+":"+dataSource.GetPort())+ require.ErrorIs(t, err, errFakeDial)+ require.Len(t, fakeDialer.calls, 2)+ require.Equal(t, "binlog", fakeDialer.calls[1].contextValue)++ cleanup()+ cleanedUp = true+ require.Equal(t, 1, fakeDialer.closeCount)++ dbAfterCleanup, err := sql.Open("mysql", fmt.Sprintf("%s@%s(%s)/%s", dataSource.GetUsername(), migrationContext.InspectorConnectionConfig.Network, dataSource.GetHost()+":"+dataSource.GetPort(), database.DatabaseName))+ require.NoError(t, err)+ defer dbAfterCleanup.Close()+ require.Error(t, dbAfterCleanup.PingContext(ctx))+ require.Len(t, fakeDialer.calls, 2)+}+func generateSelfSignedPEM(t *testing.T) (string, string) {t.Helper()@@ -101,3 +171,32 @@ func generateSelfSignedPEM(t *testing.T) (string, string) {return string(certPEM), string(keyPEM)}++type dialContextKey struct{}++var errFakeDial = errors.New("fake dial")++type fakeSSHDialer struct {+ calls []fakeSSHDialCall+ closeCount int+}++type fakeSSHDialCall struct {+ contextValue any+ network string+ address string+}++func (d *fakeSSHDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {+ d.calls = append(d.calls, fakeSSHDialCall{+ contextValue: ctx.Value(dialContextKey{}),+ network: network,+ address: address,+ })+ return nil, errFakeDial+}++func (d *fakeSSHDialer) Close() error {+ d.closeCount+++ return nil+}diff --git a/backend/runner/plancheck/ghost_sync_executor.go b/backend/runner/plancheck/ghost_sync_executor.goindex d8b7398def..06d2ba9663 100644--- a/backend/runner/plancheck/ghost_sync_executor.go+++ b/backend/runner/plancheck/ghost_sync_executor.go@@ -142,10 +142,11 @@ func (e *GhostSyncExecutor) RunForTarget(ctx context.Context, target *CheckTargeif err != nil {return nil, common.Wrapf(err, common.Internal, "failed to generate secure random number")}- migrationContext, err := ghost.NewMigrationContext(ctx, randomInt.Int64(), database, adminDataSource, tableName, fmt.Sprintf("_dryrun_%d", time.Now().Unix()), statement, true, target.GhostFlags, 20000000)+ migrationContext, cleanup, err := ghost.NewMigrationContext(ctx, randomInt.Int64(), database, adminDataSource, tableName, fmt.Sprintf("_dryrun_%d", time.Now().Unix()), statement, true, target.GhostFlags, 20000000)if err != nil {return nil, common.Wrapf(err, common.Internal, "failed to create migration context")}+ defer cleanup()defer func() {// Use migrationContext.Uuid as the tls_config_key by convention.// We need to deregister it when gh-ost exits.diff --git a/backend/runner/taskrun/database_migrate_executor.go b/backend/runner/taskrun/database_migrate_executor.goindex 913105f9c5..a228b5dda9 100644--- a/backend/runner/taskrun/database_migrate_executor.go+++ b/backend/runner/taskrun/database_migrate_executor.go@@ -322,10 +322,11 @@ func executeGhostMigration(ctx context.Context, driverCtx context.Context, taskreturn common.Errorf(common.Internal, "admin data source not found for instance %s", instance.ResourceID)}- migrationContext, err := ghost.NewMigrationContext(ctx, task.ID, database, adminDataSource, tableName, fmt.Sprintf("_%d", time.Now().Unix()), cleanedStatement, false, flags, 10000000)+ migrationContext, cleanup, err := ghost.NewMigrationContext(ctx, task.ID, database, adminDataSource, tableName, fmt.Sprintf("_%d", time.Now().Unix()), cleanedStatement, false, flags, 10000000)if err != nil {return errors.Wrap(err, "failed to init migrationContext for gh-ost")}+ defer cleanup()defer func() {// Use migrationContext.Uuid as the tls_config_key by convention.// We need to deregister it when gh-ost exits.diff --git a/go.mod b/go.modindex 9b17e37329..31dfa66caf 100644--- a/go.mod+++ b/go.mod@@ -375,7 +375,7 @@ replace (// fix potential security issue(CVE-2020-26160) introduced by indirect dependency.github.com/dgrijalva/jwt-go => github.com/form3tech-oss/jwt-go v3.2.6-0.20210809144907-32ab6a8243d7+incompatible// Other fixes.- github.com/github/gh-ost => github.com/bytebase/gh-ost2 v1.1.7-0.20260509080506-4ca6df829327+ github.com/github/gh-ost => github.com/bytebase/gh-ost2 v1.1.7-0.20260512035759-ca2794d6ebeagithub.com/jackc/pgx/v5 => github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767diff --git a/go.sum b/go.sumindex 586fe908c3..82965140fb 100644--- a/go.sum+++ b/go.sum@@ -242,8 +242,8 @@ github.com/bytebase/antlr/v4 v4.0.0-20240827034948-8c385f108920 h1:IfmPt5o5R70NKgithub.com/bytebase/antlr/v4 v4.0.0-20240827034948-8c385f108920/go.mod h1:ykhjIPiv0IWpu3OGXCHdz2eUSe8UNGGD6baqjs8jSuU=github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20260424030223-eac0db373bca h1:bDgHzFb+pn23vrCdQ8+VYTu8dHKwV9KWgcAUvL6CT+s=github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20260424030223-eac0db373bca/go.mod h1:OwIkGuhFwOV7zicy7lmJl3MRqhkf2OmCSX8NMFEPm4A=-github.com/bytebase/gh-ost2 v1.1.7-0.20260509080506-4ca6df829327 h1:zfT0iH+eaP1kyYV3TSaTi/5YOUVY/kE1yZurtPdd/WE=-github.com/bytebase/gh-ost2 v1.1.7-0.20260509080506-4ca6df829327/go.mod h1:XVUEFLOcM31VxA/pvm1YMolnDWlzVyvsqZy9OZKVJ8k=+github.com/bytebase/gh-ost2 v1.1.7-0.20260512035759-ca2794d6ebea h1:jj2X8RJaIEjFG4OUZONdKaPRyXY1k5uXepEj6Y8FDgk=+github.com/bytebase/gh-ost2 v1.1.7-0.20260512035759-ca2794d6ebea/go.mod h1:XVUEFLOcM31VxA/pvm1YMolnDWlzVyvsqZy9OZKVJ8k=github.com/bytebase/go-mssqldb v0.0.0-20240801091126-3ff3ca07d898 h1:0ggqA9XL4yvtePPvRDRYMed3jtdNk4s0o8AMW8uJPSA=github.com/bytebase/go-mssqldb v0.0.0-20240801091126-3ff3ca07d898/go.mod h1:2KhUz4GSLcdJGXSJMXAf2BjmakcgoOkNyPpHdGAxRpY=github.com/bytebase/gomongo v0.0.0-20260510192859-8526a440b352 h1:3sC5pdvJ7bNAhRDQ2Qd1EkW2+CJNAQiL6yB94gzCH/c=