Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: support Google Cloud SQL with IAM for PG (#11700)
ecmadao255855b47984
diff --git a/backend/plugin/db/pg/dump.go b/backend/plugin/db/pg/dump.goindex 3d13538293..6a67a02294 100644--- a/backend/plugin/db/pg/dump.go+++ b/backend/plugin/db/pg/dump.go@@ -17,10 +17,17 @@ import ("github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")// Dump dumps the database.func (driver *Driver) Dump(ctx context.Context, out io.Writer, schemaOnly bool) (string, error) {+ // We don't support pg_dump for CloudSQL, because pg_dump not support IAM & instance name for authentication.+ // To dump schema for CloudSQL, you need to run the cloud-sql-proxy with IAM to get the host and port.+ // Learn more: https://linear.app/bytebase/issue/BYT-5401/support-iam-authentication-for-gcp-and-aws+ if driver.config.AuthenticationType == storepb.DataSourceOptions_GOOGLE_CLOUD_SQL_IAM {+ return "", nil+ }// pg_dump -d dbName --schema-only+// Find all dumpable databasesdiff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex 4cd01076df..267f100f46 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -14,6 +14,7 @@ import (// Import pg driver.// init() in pgx/v5/stdlib will register it's pgx driver.+ "cloud.google.com/go/cloudsqlconn""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/stdlib""github.com/pkg/errors"@@ -64,6 +65,68 @@ func newDriver(config db.DriverConfig) db.Driver {// Open opens a Postgres driver.func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, config db.ConnectionConfig) (db.Driver, error) {+ var connConfig *pgx.ConnConfig+ if config.AuthenticationType == storepb.DataSourceOptions_GOOGLE_CLOUD_SQL_IAM {+ cloudSQLConfig, err := getCloudSQLConnectionConfig(ctx, config)+ if err != nil {+ return nil, err+ }+ connConfig = cloudSQLConfig+ } else {+ pgConfig, err := getPGConnectionConfig(config)+ if err != nil {+ return nil, err+ }+ connConfig = pgConfig+ }++ if config.SSHConfig.Host != "" {+ sshClient, err := util.GetSSHClient(config.SSHConfig)+ if err != nil {+ return nil, err+ }+ driver.sshClient = sshClient++ connConfig.Config.DialFunc = func(_ context.Context, network, addr string) (net.Conn, error) {+ conn, err := sshClient.Dial(network, addr)+ if err != nil {+ return nil, err+ }+ return &noDeadlineConn{Conn: conn}, nil+ }+ }++ driver.databaseName = config.Database+ if config.Database == "" {+ databaseName, cfg, err := guessDSN(connConfig, config.Username)+ if err != nil {+ return nil, err+ }+ connConfig = cfg+ driver.databaseName = databaseName+ }+ driver.config = config++ driver.connectionString = stdlib.RegisterConnConfig(connConfig)+ db, err := sql.Open(driverName, driver.connectionString)+ if err != nil {+ return nil, err+ }+ driver.db = db+ if config.ConnectionContext.UseDatabaseOwner {+ owner, err := driver.GetCurrentDatabaseOwner(ctx)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get database owner")+ }+ if _, err := driver.db.ExecContext(ctx, fmt.Sprintf("SET ROLE \"%s\";", owner)); err != nil {+ return nil, errors.Wrapf(err, "failed to set role to database owner %q", owner)+ }+ }+ driver.connectionCtx = config.ConnectionContext+ return driver, nil+}++func getPGConnectionConfig(config db.ConnectionConfig) (*pgx.ConnConfig, error) {// Require username for Postgres, as the guessDSN 1st guess is to use the username as the connecting database// if database name is not explicitly specified.if config.Username == "" {@@ -102,54 +165,33 @@ func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Connif cfg != nil {connConfig.TLSConfig = cfg}-- if config.SSHConfig.Host != "" {- sshClient, err := util.GetSSHClient(config.SSHConfig)- if err != nil {- return nil, err- }- driver.sshClient = sshClient-- connConfig.Config.DialFunc = func(_ context.Context, network, addr string) (net.Conn, error) {- conn, err := sshClient.Dial(network, addr)- if err != nil {- return nil, err- }- return &noDeadlineConn{Conn: conn}, nil- }- }if config.ReadOnly {connConfig.RuntimeParams["default_transaction_read_only"] = "true"}- driver.databaseName = config.Database- if config.Database == "" {- databaseName, cfg, err := guessDSN(connConfig, config.Username)- if err != nil {- return nil, err- }- connConfig = cfg- driver.databaseName = databaseName+ return connConfig, nil+}++// getCloudSQLConnectionConfig returns config for Cloud SQL connector.+// refs:+// https://cloud.google.com/sql/docs/postgres/connect-connectors+// https://github.com/GoogleCloudPlatform/golang-samples/blob/main/cloudsql/postgres/database-sql/cloudsql.go+func getCloudSQLConnectionConfig(ctx context.Context, conf db.ConnectionConfig) (*pgx.ConnConfig, error) {+ d, err := cloudsqlconn.NewDialer(ctx, cloudsqlconn.WithIAMAuthN())+ if err != nil {+ return nil, err}- driver.config = config- driver.connectionString = stdlib.RegisterConnConfig(connConfig)- db, err := sql.Open(driverName, driver.connectionString)+ dsn := fmt.Sprintf("user=%s database=%s", conf.Username, conf.Database)+ config, err := pgx.ParseConfig(dsn)if err != nil {return nil, err}- driver.db = db- if config.ConnectionContext.UseDatabaseOwner {- owner, err := driver.GetCurrentDatabaseOwner(ctx)- if err != nil {- return nil, errors.Wrapf(err, "failed to get database owner")- }- if _, err := db.ExecContext(ctx, fmt.Sprintf("SET ROLE \"%s\";", owner)); err != nil {- return nil, errors.Wrapf(err, "failed to set role to database owner %q", owner)- }+ config.DialFunc = func(ctx context.Context, _, _ string) (net.Conn, error) {+ return d.Dial(ctx, conf.Host)}- driver.connectionCtx = config.ConnectionContext- return driver, nil++ return config, nil}type noDeadlineConn struct{ net.Conn }diff --git a/frontend/src/components/InstanceForm/DataSourceSection/CreateDataSourceExample.vue b/frontend/src/components/InstanceForm/DataSourceSection/CreateDataSourceExample.vueindex 4dddc0c2c8..6e9bc0f708 100644--- a/frontend/src/components/InstanceForm/DataSourceSection/CreateDataSourceExample.vue+++ b/frontend/src/components/InstanceForm/DataSourceSection/CreateDataSourceExample.vue@@ -104,6 +104,21 @@{{ $t("instance.sentence.create-user-example.postgresql.warn") }}</BBAttention><i18n-t+ v-if="+ authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ "+ tag="p"+ keypath="instance.sentence.google-cloud-sql.postgresql.template"+ >+ <template #user>+ <span class="font-semibold">+ {{ userName }}+ </span>+ </template>+ </i18n-t>+ <i18n-t+ v-elsetag="p"keypath="instance.sentence.create-user-example.postgresql.template">@@ -342,6 +357,12 @@ GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE`;case Engine.RISINGWAVE:case Engine.POSTGRES:+ if (+ props.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return `GRANT pg_write_all_data TO "${ADMIN_USER_NAME}@{project-id}.iam";`;+ }return `CREATE USER ${ADMIN_USER_NAME} WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER ${ADMIN_USER_NAME} WITH SUPERUSER;`;case Engine.REDSHIFT:return `CREATE USER ${ADMIN_USER_NAME} WITH PASSWORD 'YOUR_DB_PWD' CREATEUSER CREATEDB;`;@@ -487,6 +508,12 @@ GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE`;case Engine.RISINGWAVE:case Engine.POSTGRES:+ if (+ props.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return `GRANT pg_read_all_data TO "${READONLY_USER_NAME}@{project-id}.iam";`;+ }return `CREATE USER ${READONLY_USER_NAME} WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';ALTER USER ${READONLY_USER_NAME} WITH SUPERUSER;`;case Engine.MONGODB:diff --git a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vueindex b777711142..9cb7fe4b06 100644--- a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue+++ b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue@@ -1,7 +1,13 @@<template><!-- eslint-disable vue/no-mutating-props --><template v-if="basicInfo.engine !== Engine.SPANNER">- <div v-if="basicInfo.engine === Engine.MYSQL" class="mt-2">+ <div+ v-if="+ basicInfo.engine === Engine.MYSQL ||+ basicInfo.engine === Engine.POSTGRES+ "+ class="mt-2"+ ><NRadioGroupv-model:value="dataSource.authenticationType"class="textlabel"diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex a9f3a441cc..2aa1259a9d 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1320,6 +1320,9 @@"instance-name-tips": "The instance connection name should like project-id:region:instance-name.","mysql": {"template": "Create a service account named {user}, then add it in your Google Cloud SQL as IAM user {user}{'@'}'%'. Grant this user with the needed privileges."+ },+ "postgresql": {+ "template": "Create a service account named {user}, then add it in your Google Cloud SQL as IAM user {user}{'@'}project-id.iam. Grant the user with the needed privileges."}},"create-user-example": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex ca82442b5c..dc48f4f552 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1320,6 +1320,9 @@"instance-name-tips": "El nombre de la conexión de la instancia debería ser project-id:region:instance-name.","mysql": {"template": "Cree una cuenta de servicio llamada {user} y luego agréguela en su Google Cloud SQL como usuario de IAM {user}{'@'}'%'. Otorgue a este usuario los privilegios necesarios."+ },+ "postgresql": {+ "template": "Cree una cuenta de servicio llamada {user} y luego agréguela en su Google Cloud SQL como usuario de IAM {user}{'@'}project-id.iam. Otorgue al usuario los privilegios necesarios."}},"create-user-example": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 7a270e6823..d4e441e86b 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1320,6 +1320,9 @@"instance-name-tips": "インスタンス接続名は、project-id:region:instance-name のようになります。","mysql": {"template": "{user} という名前のサービス アカウントを作成し、それを IAM ユーザー {user}{'@'}'%' として Google Cloud SQL に追加します。このユーザーに必要な権限を付与します。"+ },+ "postgresql": {+ "template": "{user} という名前のサービス アカウントを作成し、それを IAM ユーザー {user}{'@'}project-id.iam として Google Cloud SQL に追加します。ユーザーに必要な権限を付与します。"}},"create-user-example": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 60b85f8a38..22a8091cc2 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1320,6 +1320,9 @@"instance-name-tips": "Tên kết nối phiên bản phải như project-id:region:instance-name.","mysql": {"template": "Tạo một tài khoản dịch vụ có tên {user}, sau đó thêm tài khoản đó vào Google Cloud SQL của bạn với tư cách là người dùng IAM {user}{'@'}'%'. Cấp cho người dùng này những đặc quyền cần thiết."+ },+ "postgresql": {+ "template": "Tạo một tài khoản dịch vụ có tên {user}, sau đó thêm tài khoản đó vào Google Cloud SQL của bạn với tư cách là người dùng IAM {user}{'@'}project-id.iam. Cấp cho người dùng những đặc quyền cần thiết."}},"create-user-example": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 3b3c854537..ef8e16ecf8 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1320,6 +1320,9 @@"instance-name-tips": "实例连接名称应为 project-id:region:instance-name。","mysql": {"template": "创建一个名为 {user} 的服务帐户,然后将其作为 IAM 用户 {user}{'@'}'%' 添加到您的 Google Cloud SQL 中。授予此用户所需的权限。"+ },+ "postgresql": {+ "template": "创建一个名为 {user} 的服务帐户,然后将其作为 IAM 用户 {user}{'@'}project-id.iam 添加到您的 Google Cloud SQL 中。授予用户所需的权限。"}},"create-user-example": {