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: instance roles (#13029)
Danny Xu71ac4b82088c
diff --git a/backend/api/v1/instance_role_service.go b/backend/api/v1/instance_role_service.goindex 45f8fde91d..63395a9d6e 100644--- a/backend/api/v1/instance_role_service.go+++ b/backend/api/v1/instance_role_service.go@@ -2,14 +2,8 @@ package v1import ("context"- "fmt"- "google.golang.org/grpc/codes"- "google.golang.org/grpc/status"-- "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/component/dbfactory"- "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/store"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -30,113 +24,11 @@ func NewInstanceRoleService(store *store.Store, dbFactory *dbfactory.DBFactory)}// GetInstanceRole gets an role.-func (s *InstanceRoleService) GetInstanceRole(ctx context.Context, request *v1pb.GetInstanceRoleRequest) (*v1pb.InstanceRole, error) {- instanceID, roleName, err := common.GetInstanceRoleID(request.Name)- if err != nil {- return nil, status.Errorf(codes.InvalidArgument, err.Error())- }-- instance, err := s.getInstanceMessage(ctx, instanceID)- if err != nil {- return nil, err- }-- role, err := func() (*db.DatabaseRoleMessage, error) {- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, nil /* database */, db.ConnectionContext{})- if err != nil {- return nil, err- }- defer driver.Close(ctx)-- role, err := driver.FindRole(ctx, roleName)- if err != nil {- return nil, err- }-- return role, nil- }()- if err != nil {- if common.ErrorCode(err) == common.NotFound {- return nil, status.Errorf(codes.NotFound, "role %s not found", request.Name)- }- return nil, status.Errorf(codes.Internal, err.Error())- }-- return convertToInstanceRole(role, instance), nil+func (*InstanceRoleService) GetInstanceRole(_ context.Context, _ *v1pb.GetInstanceRoleRequest) (*v1pb.InstanceRole, error) {+ return &v1pb.InstanceRole{}, nil}// ListInstanceRoles lists all roles in an instance.-func (s *InstanceRoleService) ListInstanceRoles(ctx context.Context, request *v1pb.ListInstanceRolesRequest) (*v1pb.ListInstanceRolesResponse, error) {- instanceID, err := common.GetInstanceID(request.Parent)- if err != nil {- return nil, status.Errorf(codes.InvalidArgument, err.Error())- }-- instance, err := s.getInstanceMessage(ctx, instanceID)- if err != nil {- return nil, err- }-- if !request.Refresh {- instanceUsers, err := s.store.ListInstanceUsers(ctx, &store.FindInstanceUserMessage{InstanceUID: instance.UID})- if err != nil {- return nil, err- }- response := &v1pb.ListInstanceRolesResponse{}- for _, u := range instanceUsers {- response.Roles = append(response.Roles, &v1pb.InstanceRole{- Name: fmt.Sprintf("instances/%s/roles/%s", instance.ResourceID, u.Name),- RoleName: u.Name,- Attribute: &u.Grant,- })- }- return response, nil- }-- roleList, err := func() ([]*db.DatabaseRoleMessage, error) {- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, nil /* database */, db.ConnectionContext{})- if err != nil {- return nil, err- }- defer driver.Close(ctx)-- roleList, err := driver.ListRole(ctx)- if err != nil {- return nil, err- }-- return roleList, nil- }()- if err != nil {- return nil, status.Errorf(codes.Internal, err.Error())- }-- response := &v1pb.ListInstanceRolesResponse{}- for _, role := range roleList {- response.Roles = append(response.Roles, convertToInstanceRole(role, instance))- }- return response, nil-}--func (s *InstanceRoleService) getInstanceMessage(ctx context.Context, instanceID string) (*store.InstanceMessage, error) {- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{- ResourceID: &instanceID,- })- if err != nil {- return nil, status.Errorf(codes.Internal, err.Error())- }- if instance == nil {- return nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)- }- return instance, nil-}--func convertToInstanceRole(role *db.DatabaseRoleMessage, instance *store.InstanceMessage) *v1pb.InstanceRole {- return &v1pb.InstanceRole{- Name: fmt.Sprintf("instances/%s/roles/%s", instance.ResourceID, role.Name),- RoleName: role.Name,- ConnectionLimit: &role.ConnectionLimit,- ValidUntil: role.ValidUntil,- Attribute: role.Attribute,- }+func (*InstanceRoleService) ListInstanceRoles(_ context.Context, _ *v1pb.ListInstanceRolesRequest) (*v1pb.ListInstanceRolesResponse, error) {+ return &v1pb.ListInstanceRolesResponse{}, nil}diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.goindex 70d019fd52..e92e0e12e0 100644--- a/backend/api/v1/instance_service.go+++ b/backend/api/v1/instance_service.go@@ -1049,9 +1049,21 @@ func convertToInstance(instance *store.InstanceMessage) (*v1pb.Instance, error)Environment: fmt.Sprintf("environments/%s", instance.EnvironmentID),Activation: instance.Activation,Options: convertToInstanceOptions(instance.Options),+ Roles: convertToInstanceRoles(instance.Metadata.Roles),}, nil}+func convertToInstanceRoles(roles []*storepb.InstanceRole) []*v1pb.InstanceRole {+ var v1Roles []*v1pb.InstanceRole+ for _, role := range roles {+ v1Roles = append(v1Roles, &v1pb.InstanceRole{+ RoleName: role.Name,+ Attribute: role.Attribute,+ })+ }+ return v1Roles+}+func (s *InstanceService) convertToInstanceMessage(instanceID string, instance *v1pb.Instance) (*store.InstanceMessage, error) {datasources, err := s.convertToDataSourceMessages(instance.DataSources)if err != nil {@@ -1087,6 +1099,7 @@ func convertToInstanceResource(instanceMessage *store.InstanceMessage) (*v1pb.InDataSources: instance.DataSources,Activation: instance.Activation,Environment: instance.Environment,+ Roles: instance.Roles,}, nil}diff --git a/backend/plugin/db/clickhouse/role.go b/backend/plugin/db/clickhouse/role.goindex 5dd530922d..ab91c170cc 100644--- a/backend/plugin/db/clickhouse/role.go+++ b/backend/plugin/db/clickhouse/role.go@@ -2,42 +2,12 @@ package clickhouseimport ("context"- "fmt"- "strings"- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"storepb "github.com/bytebase/bytebase/proto/generated-go/store")-// CreateRole creates the role.-func (*Driver) CreateRole(_ context.Context, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("create role for ClickHouse is not implemented yet")-}--// UpdateRole updates the role.-func (*Driver) UpdateRole(_ context.Context, _ string, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("update role for ClickHouse is not implemented yet")-}--// FindRole finds the role by name.-func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("find role for ClickHouse is not implemented yet")-}--// ListRole lists the role.-func (*Driver) ListRole(_ context.Context) ([]*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("list role for ClickHouse is not implemented yet")-}--// DeleteRole deletes the role by name.-func (*Driver) DeleteRole(_ context.Context, _ string) error {- return errors.Errorf("delete role for ClickHouse is not implemented yet")-}--func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {// host_ip isn't used for user identifier.query := `SELECT@@ -51,7 +21,7 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instance}defer roleRows.Close()- var instanceRoles []*storepb.InstanceRoleMetadata+ var instanceRoles []*storepb.InstanceRolefor roleRows.Next() {var user stringif err := roleRows.Scan(@@ -59,40 +29,9 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instance); err != nil {return nil, err}-- if err := func() error {- // Uses single quote instead of backtick to escape because this is a string- // instead of table (which should use backtick instead). MySQL actually works- // in both ways. On the other hand, some other MySQL compatible engines might not (OceanBase in this case).- grantQuery := fmt.Sprintf("SHOW GRANTS FOR `%s`", user)- grantRows, err := driver.db.QueryContext(ctx,- grantQuery,- )- if err != nil {- return util.FormatErrorWithQuery(err, grantQuery)- }- defer grantRows.Close()-- grantList := []string{}- for grantRows.Next() {- var grant string- if err := grantRows.Scan(&grant); err != nil {- return err- }- grantList = append(grantList, grant)- }- if err := grantRows.Err(); err != nil {- return util.FormatErrorWithQuery(err, grantQuery)- }-- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: user,- Grant: strings.Join(grantList, "\n"),- })- return nil- }(); err != nil {- return nil, err- }+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: user,+ })}if err := roleRows.Err(); err != nil {return nil, util.FormatErrorWithQuery(err, query)diff --git a/backend/plugin/db/clickhouse/sync.go b/backend/plugin/db/clickhouse/sync.goindex 7ef17b727d..2beed6105a 100644--- a/backend/plugin/db/clickhouse/sync.go+++ b/backend/plugin/db/clickhouse/sync.go@@ -53,9 +53,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: instanceRoles,- Databases: databases,+ Version: version,+ Databases: databases,+ Metadata: &storepb.InstanceMetadata{+ Roles: instanceRoles,+ },}, nil}diff --git a/backend/plugin/db/databricks/role.go b/backend/plugin/db/databricks/role.goindex ce04425f7d..b6a2f2dce0 100644--- a/backend/plugin/db/databricks/role.go+++ b/backend/plugin/db/databricks/role.go@@ -1,28 +1 @@package databricks--import (- "context"-- "github.com/bytebase/bytebase/backend/plugin/db"-)--func (*Driver) CreateRole(_ context.Context, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, nil-}--func (*Driver) DeleteRole(_ context.Context, _ string) error {- return nil-}--func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, error) {- return nil, nil-}--func (*Driver) UpdateRole(_ context.Context, _ string, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, nil-}--// TODO(tommy): maybe implement this when Permissions API is implemented.-func (*Driver) ListRole(_ context.Context) ([]*db.DatabaseRoleMessage, error) {- return nil, nil-}diff --git a/backend/plugin/db/dm/role.go b/backend/plugin/db/dm/role.goindex 7e3125ab39..a5bf44f6c1 100644--- a/backend/plugin/db/dm/role.go+++ b/backend/plugin/db/dm/role.go@@ -1,34 +1 @@package dm--import (- "context"-- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/db"-)--// CreateRole creates the role.-func (*Driver) CreateRole(_ context.Context, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("create role for DM is not implemented yet")-}--// UpdateRole updates the role.-func (*Driver) UpdateRole(_ context.Context, _ string, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("update role for DM is not implemented yet")-}--// FindRole finds the role by name.-func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("find role for DM is not implemented yet")-}--// ListRole lists the role.-func (*Driver) ListRole(_ context.Context) ([]*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("list role for DM is not implemented yet")-}--// DeleteRole deletes the role by name.-func (*Driver) DeleteRole(_ context.Context, _ string) error {- return errors.Errorf("delete role for DM is not implemented yet")-}diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex 12ac3aafe3..9658ee8dea 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -35,8 +35,7 @@ type User struct {// InstanceMetadata is the metadata for an instance.type InstanceMetadata struct {- Version string- InstanceRoles []*storepb.InstanceRoleMetadata+ Version string// Simplified database metadata.Databases []*storepb.DatabaseSchemaMetadataMetadata *storepb.InstanceMetadata@@ -300,18 +299,6 @@ type Driver interface {// CheckSlowQueryLogEnabled checks if the slow query log is enabled.CheckSlowQueryLogEnabled(ctx context.Context) error- // Role- // CreateRole creates the role.- CreateRole(ctx context.Context, upsert *DatabaseRoleUpsertMessage) (*DatabaseRoleMessage, error)- // UpdateRole updates the role.- UpdateRole(ctx context.Context, roleName string, upsert *DatabaseRoleUpsertMessage) (*DatabaseRoleMessage, error)- // FindRole finds the role by name.- FindRole(ctx context.Context, roleName string) (*DatabaseRoleMessage, error)- // ListRole lists the role.- ListRole(ctx context.Context) ([]*DatabaseRoleMessage, error)- // DeleteRole deletes the role by name.- DeleteRole(ctx context.Context, roleName string) error-// Dump dumps the schema of database.Dump(ctx context.Context, out io.Writer) (string, error)}diff --git a/backend/plugin/db/dynamodb/role.go b/backend/plugin/db/dynamodb/role.goindex 1fbdbaaf2f..eeacc1963d 100644--- a/backend/plugin/db/dynamodb/role.go+++ b/backend/plugin/db/dynamodb/role.go@@ -1,34 +1 @@package dynamodb--import (- "context"-- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/db"-)--// CreateRole creates the role.-func (*Driver) CreateRole(_ context.Context, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("create role for dynamodb is not implemented yet")-}--// UpdateRole updates the role.-func (*Driver) UpdateRole(_ context.Context, _ string, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("update role for dynamodb is not implemented yet")-}--// FindRole finds the role by name.-func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("find role for dynamodb is not implemented yet")-}--// ListRole lists the role.-func (*Driver) ListRole(_ context.Context) ([]*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("list role for dynamodb is not implemented yet")-}--// DeleteRole deletes the role by name.-func (*Driver) DeleteRole(_ context.Context, _ string) error {- return errors.Errorf("delete role for dynamodb is not implemented yet")-}diff --git a/backend/plugin/db/elasticsearch/role.go b/backend/plugin/db/elasticsearch/role.goindex e4092ef372..61fbb4ae24 100644--- a/backend/plugin/db/elasticsearch/role.go+++ b/backend/plugin/db/elasticsearch/role.go@@ -3,105 +3,20 @@ package elasticsearchimport ("context""encoding/json"- "errors"+ "fmt""net/http"+ "strings""github.com/elastic/go-elasticsearch/v8/esapi"- "github.com/bytebase/bytebase/backend/plugin/db"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")-func (d *Driver) ListRole(ctx context.Context) ([]*db.DatabaseRoleMessage, error) {- resp, err := esapi.SecurityGetRoleRequest{}.Do(ctx, d.typedClient)- if err != nil {- return nil, err- }-- bytes, err := readBytesAndClose(resp)- if err != nil {- return nil, err- }-- dbRoleMessages := []*db.DatabaseRoleMessage{}-- roles := map[string]any{}- if err := json.Unmarshal(bytes, &roles); err != nil {- return nil, err- }-- for roleName, roleInfo := range roles {- roleInfoStr, ok := roleInfo.(string)- if !ok {- return nil, errors.New("type assertion fails: roleInfo")- }- dbRoleMessages = append(dbRoleMessages, &db.DatabaseRoleMessage{- Name: roleName,- Attribute: &roleInfoStr,- })- }-- return dbRoleMessages, nil-}--func (d *Driver) FindRole(ctx context.Context, name string) (*db.DatabaseRoleMessage, error) {- resp, err := esapi.SecurityGetRoleRequest{Name: []string{name}}.Do(ctx, d.typedClient)- if err != nil {- return nil, err- }-- bytes, err := readBytesAndClose(resp)- if err != nil {- return nil, err- }-- dbRoleMessage := &db.DatabaseRoleMessage{}-- roles := map[string]any{}- if err := json.Unmarshal(bytes, &roles); err != nil {- return nil, err- }-- for roleName, roleInfo := range roles {- roleInfoStr, ok := roleInfo.(string)- if !ok {- return nil, errors.New("type assertion fails: roleInfo")- }- dbRoleMessage.Name = roleName- dbRoleMessage.Attribute = &roleInfoStr- }-- return dbRoleMessage, nil-}--func (d *Driver) CreateRole(ctx context.Context, msg *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- resp, err := esapi.SecurityPutRoleRequest{Name: msg.Name}.Do(ctx, d.typedClient)- if err != nil || resp.StatusCode != 200 {- return nil, err- }- return nil, nil-}--func (d *Driver) DeleteRole(ctx context.Context, name string) error {- resp, err := esapi.SecurityDeleteRoleRequest{Name: name}.Do(ctx, d.typedClient)- if err != nil || resp.StatusCode != 200 {- return err- }- return nil-}--func (d *Driver) UpdateRole(ctx context.Context, _ string, msg *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- dbRoleMsg, err := d.CreateRole(ctx, msg)- if err != nil {- return nil, err- }- return dbRoleMsg, nil-}-type UserResult struct {Roles []string `json:"roles"`}-func (d *Driver) getUsersWithRoles() (map[string]UserResult, error) {+func (d *Driver) getInstanceRoles() ([]*storepb.InstanceRole, error) {resp, err := esapi.SecurityGetUserRequest{Pretty: true}.Do(context.Background(), d.typedClient)if err != nil {return nil, err@@ -117,7 +32,19 @@ func (d *Driver) getUsersWithRoles() (map[string]UserResult, error) {return nil, err}- return results, nil+ var instanceRoles []*storepb.InstanceRole+ for name, userResult := range results {+ privileges, err := d.getUserPrivileges(name)+ if err != nil {+ return nil, err+ }+ attribute := fmt.Sprintf("[%s]: %s", strings.Join(userResult.Roles, ", "), privileges)+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: name,+ Attribute: &attribute,+ })+ }+ return instanceRoles, nil}func (d *Driver) getUserPrivileges(usrName string) (string, error) {diff --git a/backend/plugin/db/elasticsearch/sync.go b/backend/plugin/db/elasticsearch/sync.goindex 98d13fff4a..1b447c8f62 100644--- a/backend/plugin/db/elasticsearch/sync.go+++ b/backend/plugin/db/elasticsearch/sync.go@@ -7,7 +7,6 @@ import ("strconv""strings"- "fmt""io""net/http""time"@@ -20,41 +19,31 @@ import ()func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error) {- var instanceMetadata db.InstanceMetadata-// version.version, err := d.getVerison()if err != nil {return nil, errors.Wrapf(err, "failed to fetch version from Elasticsearch server")}- // indices.- dbSchemaMetadata, err := d.SyncDBSchema(ctx)+ // databases.+ dbMetadata, err := d.SyncDBSchema(ctx)if err != nil {return nil, errors.Wrapf(err, "failed to fetch indices from Elasticsearch server")}// roles.- var instanceRoles []*storepb.InstanceRoleMetadata- usersWithRoles, err := d.getUsersWithRoles()+ instanceRoles, err := d.getInstanceRoles()if err != nil {return nil, err}- for userName, roles := range usersWithRoles {- privileges, err := d.getUserPrivileges(userName)- if err != nil {- return nil, err- }- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: userName,- Grant: fmt.Sprintf("[%s]: %s", strings.Join(roles.Roles, ", "), privileges),- })- }- instanceMetadata.InstanceRoles = instanceRoles- instanceMetadata.Databases = append(instanceMetadata.Databases, dbSchemaMetadata)- instanceMetadata.Version = version- return &instanceMetadata, nil+ return &db.InstanceMetadata{+ Version: version,+ Databases: []*storepb.DatabaseSchemaMetadata{dbMetadata},+ Metadata: &storepb.InstanceMetadata{+ Roles: instanceRoles,+ },+ }, nil}// SyncDBSchema implements db.Driver.diff --git a/backend/plugin/db/mongodb/role.go b/backend/plugin/db/mongodb/role.goindex 8648102951..2f9282accc 100644--- a/backend/plugin/db/mongodb/role.go+++ b/backend/plugin/db/mongodb/role.go@@ -2,7 +2,6 @@ package mongodbimport ("context"- "encoding/json""log/slog""github.com/pkg/errors"@@ -43,7 +42,7 @@ func (*Driver) DeleteRole(_ context.Context, _ string) error {}// getUserList returns the list of users.-func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {database := driver.client.Database(bytebaseDefaultDatabase)command := bson.D{{Key: "usersInfo",@@ -60,16 +59,10 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instance}return nil, errors.Wrap(err, "cannot run usersInfo command")}- var instanceRoles []*storepb.InstanceRoleMetadata+ var instanceRoles []*storepb.InstanceRolefor _, user := range commandResult.Users {- bs, err := json.Marshal(user)- if err != nil {- return nil, errors.Wrap(err, "cannot marshal user")- }-- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: user.ID,- Grant: string(bs),+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: user.ID,})}return instanceRoles, nildiff --git a/backend/plugin/db/mongodb/sync.go b/backend/plugin/db/mongodb/sync.goindex 06df16efd7..68ee23e6e9 100644--- a/backend/plugin/db/mongodb/sync.go+++ b/backend/plugin/db/mongodb/sync.go@@ -57,7 +57,7 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, eif err != nil {return nil, err}- users, err := driver.getInstanceRoles(ctx)+ instanceRoles, err := driver.getInstanceRoles(ctx)if err != nil {return nil, err}@@ -73,9 +73,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: users,- Databases: databases,+ Version: version,+ Databases: databases,+ Metadata: &storepb.InstanceMetadata{+ Roles: instanceRoles,+ },}, nil}diff --git a/backend/plugin/db/mysql/role.go b/backend/plugin/db/mysql/role.goindex 646218175b..2d2f051c92 100644--- a/backend/plugin/db/mysql/role.go+++ b/backend/plugin/db/mysql/role.go@@ -2,388 +2,18 @@ package mysqlimport ("context"- "database/sql""fmt""log/slog"- "regexp"- "strconv""strings""github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"- "github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/plugin/db/util"- "github.com/bytebase/bytebase/backend/plugin/parser/base"storepb "github.com/bytebase/bytebase/proto/generated-go/store")-// CreateRole creates the role.-func (driver *Driver) CreateRole(ctx context.Context, upsert *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- txn, err := driver.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer txn.Rollback()-- if err := createRoleImpl(ctx, txn, upsert); err != nil {- return nil, err- }-- roles, err := driver.findRoleImpl(ctx, &upsert.Name)- if err != nil {- return nil, err- }- if len(roles) == 0 {- return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", upsert.Name))- }-- if err := txn.Commit(); err != nil {- return nil, err- }-- return roles[0], nil-}--// UpdateRole updates the role.-func (driver *Driver) UpdateRole(ctx context.Context, roleName string, upsert *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- txn, err := driver.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer txn.Rollback()-- if err := alterRoleImpl(ctx, txn, roleName, upsert); err != nil {- return nil, err- }-- roles, err := driver.findRoleImpl(ctx, &upsert.Name)- if err != nil {- return nil, err- }- if len(roles) == 0 {- return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", upsert.Name))- }-- if err := txn.Commit(); err != nil {- return nil, err- }-- return roles[0], nil-}--// FindRole finds the role by name.-func (driver *Driver) FindRole(ctx context.Context, roleName string) (*db.DatabaseRoleMessage, error) {- roles, err := driver.findRoleImpl(ctx, &roleName)- if err != nil {- return nil, err- }- if len(roles) == 0 {- return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", roleName))- }-- return roles[0], nil-}--// ListRole lists the role.-func (driver *Driver) ListRole(ctx context.Context) ([]*db.DatabaseRoleMessage, error) {- roles, err := driver.findRoleImpl(ctx, nil)- if err != nil {- return nil, err- }-- return roles, nil-}--// DeleteRole deletes the role by name.-func (driver *Driver) DeleteRole(ctx context.Context, roleName string) error {- statement := fmt.Sprintf(`DROP USER IF EXISTS %s`, roleName)- if _, err := driver.db.ExecContext(ctx, statement); err != nil {- return util.FormatErrorWithQuery(err, statement)- }-- return nil-}--func (driver *Driver) findRoleImpl(ctx context.Context, name *string) ([]*db.DatabaseRoleMessage, error) {- if name != nil {- attribute, err := driver.findRoleGrant(ctx, *name)- if err != nil {- return nil, err- }-- user, host := parseNameAndHost(*name)- maxUserConnection, lifetime, err := driver.findConnectionLimitAndExpiration(ctx, user, host)- if err != nil {- return nil, err- }-- var lifetimeString *string- if lifetime != nil {- day := fmt.Sprintf("%d", *lifetime)- lifetimeString = &day- }- return []*db.DatabaseRoleMessage{- {- Name: *name,- Attribute: &attribute,- ConnectionLimit: maxUserConnection,- ValidUntil: lifetimeString,- },- }, nil- }-- query := `- SELECT- user,- host- FROM mysql.user- WHERE user NOT LIKE 'mysql.%'- `- roleRows, err := driver.db.QueryContext(ctx, query)-- if err != nil {- return nil, util.FormatErrorWithQuery(err, query)- }- defer roleRows.Close()-- var result []*db.DatabaseRoleMessage-- for roleRows.Next() {- var user string- var host string- if err := roleRows.Scan(- &user,- &host,- ); err != nil {- return nil, err- }-- name := fmt.Sprintf("'%s'@'%s'", user, host)- attribute, err := driver.findRoleGrant(ctx, name)- if err != nil {- return nil, err- }-- maxUserConnection, lifetime, err := driver.findConnectionLimitAndExpiration(ctx, user, host)- if err != nil {- return nil, err- }-- var lifetimeString *string- if lifetime != nil {- day := fmt.Sprintf("%d", *lifetime)- lifetimeString = &day- }-- result = append(result, &db.DatabaseRoleMessage{- Name: name,- Attribute: &attribute,- ConnectionLimit: maxUserConnection,- ValidUntil: lifetimeString,- })- }- if err := roleRows.Err(); err != nil {- return nil, err- }-- return result, nil-}--func (driver *Driver) findConnectionLimitAndExpiration(ctx context.Context, user string, host string) (int32, *int32, error) {- statement := fmt.Sprintf(`SELECT max_user_connections, password_lifetime FROM mysql.user WHERE user = '%s' AND host = '%s'`, user, host)- rows, err := driver.db.QueryContext(ctx, statement)- if err != nil {- return 0, nil, util.FormatErrorWithQuery(err, statement)- }- defer rows.Close()-- type result struct {- maxUserConnection int32- lifetime sql.NullInt32- }- var list []result-- for rows.Next() {- var row result- if err := rows.Scan(- &row.maxUserConnection,- &row.lifetime,- ); err != nil {- return 0, nil, util.FormatErrorWithQuery(err, statement)- }- list = append(list, row)- }- if err := rows.Err(); err != nil {- return 0, nil, err- }-- if len(list) == 0 {- return 0, nil, common.Errorf(common.NotFound, "role '%s'@'%s' not found", user, host)- }-- // never catch- if len(list) > 1 {- return 0, nil, common.Errorf(common.Internal, "role '%s'@'%s' is not unique", user, host)- }-- lifetime := (*int32)(nil)- if list[0].lifetime.Valid {- lifetime = &list[0].lifetime.Int32- }- return list[0].maxUserConnection, lifetime, nil-}--// parseNameAndHost parses the MySQL role name, there are two cases:-// 1. user@host: specify host-// 2. user: do not specify host, the host will be `%`-// user and host can be surrounded by quotes('), double-quotes("), black-quotes(`) or not.-func parseNameAndHost(in string) (string, string) {- reg := regexp.MustCompile("(.*)@(.*)")- list := reg.FindStringSubmatch(in)- trimFunc := func(r rune) bool {- return r == '`' || r == '"' || r == '\''- }- if len(list) != 3 {- // Case Two: do not specify host- return strings.TrimFunc(in, trimFunc), "%"- }- // Case One: specify host- return strings.TrimFunc(list[1], trimFunc), strings.TrimFunc(list[2], trimFunc)-}--func alterRoleImpl(ctx context.Context, txn *sql.Tx, roleName string, upsert *db.DatabaseRoleUpsertMessage) error {- if roleName != upsert.Name {- renameStatement := fmt.Sprintf(`RENAME USER %s to %s`, roleName, upsert.Name)- if _, err := txn.ExecContext(ctx, renameStatement); err != nil {- return util.FormatErrorWithQuery(err, renameStatement)- }- }-- content, err := convertToUserContent(upsert)- if err != nil {- return err- }-- if content != "" {- alterStatement := fmt.Sprintf(`ALTER USER IF EXISTS %s %s`, upsert.Name, content)- if _, err := txn.ExecContext(ctx, alterStatement); err != nil {- return util.FormatErrorWithQuery(err, alterStatement)- }- }-- if upsert.Attribute != nil {- revokeStatement := fmt.Sprintf(`REVOKE ALL PRIVILEGES, GRANT OPTION FROM %s`, upsert.Name)- if _, err := txn.ExecContext(ctx, revokeStatement); err != nil {- return util.FormatErrorWithQuery(err, revokeStatement)- }-- if len(*upsert.Attribute) > 0 {- list, err := splitGrantStatement(*upsert.Attribute)- if err != nil {- return err- }- for _, sql := range list {- if _, err := txn.ExecContext(ctx, sql.Text); err != nil {- return util.FormatErrorWithQuery(err, sql.Text)- }- }- }- }-- return nil-}--func createRoleImpl(ctx context.Context, txn *sql.Tx, upsert *db.DatabaseRoleUpsertMessage) error {- content, err := convertToUserContent(upsert)- if err != nil {- return err- }- statement := fmt.Sprintf(`CREATE USER IF NOT EXISTS %s %s`, upsert.Name, content)-- if _, err := txn.ExecContext(ctx, statement); err != nil {- return util.FormatErrorWithQuery(err, statement)- }-- if upsert.Attribute != nil && len(*upsert.Attribute) > 0 {- list, err := splitGrantStatement(*upsert.Attribute)- if err != nil {- return err- }- for _, sql := range list {- if _, err := txn.ExecContext(ctx, sql.Text); err != nil {- return util.FormatErrorWithQuery(err, sql.Text)- }- }- }-- return nil-}--func convertToUserContent(upsert *db.DatabaseRoleUpsertMessage) (string, error) {- var contentList []string- if upsert.Password != nil {- contentList = append(contentList, fmt.Sprintf(`IDENTIFIED BY '%s'`, *upsert.Password))- }- if upsert.ConnectionLimit != nil {- contentList = append(contentList, fmt.Sprintf(`WITH MAX_USER_CONNECTIONS %d`, *upsert.ConnectionLimit))- }- if upsert.ValidUntil != nil {- interval, err := strconv.Atoi(*upsert.ValidUntil)- if err != nil || interval < 0 {- return "", common.Wrapf(err, common.Invalid, "invalid MySQL expiration")- }- if interval == 0 {- contentList = append(contentList, "PASSWORD EXPIRE NEVER")- } else {- contentList = append(contentList, fmt.Sprintf("PASSWORD EXPIRE INTERVAL %d DAY", interval))- }- }- return strings.Join(contentList, " "), nil-}--func splitGrantStatement(stmts string) ([]base.SingleSQL, error) {- singleSQLs, err := base.SplitMultiSQL(storepb.Engine_MYSQL, stmts)- if err != nil {- return nil, common.Wrapf(err, common.Invalid, "failed to split grant statement")- }-- grantReg := regexp.MustCompile("(?i)^GRANT ")- for _, singleSQL := range singleSQLs {- if len(grantReg.FindString(singleSQL.Text)) == 0 {- return nil, common.Wrapf(err, common.Invalid, "\"%s\" is not the GRANT statement", singleSQL.Text)- }- }-- return singleSQLs, nil-}--func (driver *Driver) findRoleGrant(ctx context.Context, name string) (string, error) {- grantQuery := fmt.Sprintf("SHOW GRANTS FOR %s", name)- grantRows, err := driver.db.QueryContext(ctx, grantQuery)- if err != nil {- return "", util.FormatErrorWithQuery(err, grantQuery)- }- defer grantRows.Close()-- grantList := []string{}- for grantRows.Next() {- var grant string- if err := grantRows.Scan(&grant); err != nil {- return "", err- }- grantList = append(grantList, grant)- }- if err := grantRows.Err(); err != nil {- return "", util.FormatErrorWithQuery(err, grantQuery)- }-- return strings.Join(grantList, ";\n"), nil-}--func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {- var instanceRoles []*storepb.InstanceRoleMetadata+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {+ var instanceRoles []*storepb.InstanceRolevar users []stringvar err errorusers, err = driver.getUsersFromMySQLUser(ctx)@@ -404,9 +34,10 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instanceif err != nil {return nil, errors.Wrapf(err, "failed to get grants for %s", name)}- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: name,- Grant: strings.Join(grantList, "\n"),+ attribute := strings.Join(grantList, "\n")+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: name,+ Attribute: &attribute,})}return instanceRoles, nildiff --git a/backend/plugin/db/mysql/sync.go b/backend/plugin/db/mysql/sync.goindex 43704f6d75..ef16a9089a 100644--- a/backend/plugin/db/mysql/sync.go+++ b/backend/plugin/db/mysql/sync.go@@ -78,7 +78,7 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}}- users, err := driver.getInstanceRoles(ctx)+ instanceRoles, err := driver.getInstanceRoles(ctx)if err != nil {return nil, err}@@ -115,11 +115,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: users,- Databases: databases,+ Version: version,+ Databases: databases,Metadata: &storepb.InstanceMetadata{MysqlLowerCaseTableNames: int32(lowerCaseTableNames),+ Roles: instanceRoles,},}, nil}diff --git a/backend/plugin/db/oracle/role.go b/backend/plugin/db/oracle/role.goindex 3f6518d292..5a6ef42d25 100644--- a/backend/plugin/db/oracle/role.go+++ b/backend/plugin/db/oracle/role.go@@ -1,34 +1 @@package oracle--import (- "context"-- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/db"-)--// CreateRole creates the role.-func (*Driver) CreateRole(_ context.Context, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("create role for Oracle is not implemented yet")-}--// UpdateRole updates the role.-func (*Driver) UpdateRole(_ context.Context, _ string, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("update role for Oracle is not implemented yet")-}--// FindRole finds the role by name.-func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("find role for Oracle is not implemented yet")-}--// ListRole lists the role.-func (*Driver) ListRole(_ context.Context) ([]*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("list role for Oracle is not implemented yet")-}--// DeleteRole deletes the role by name.-func (*Driver) DeleteRole(_ context.Context, _ string) error {- return errors.Errorf("delete role for Oracle is not implemented yet")-}diff --git a/backend/plugin/db/pg/role.go b/backend/plugin/db/pg/role.goindex 5e4df79ab4..4a854a3223 100644--- a/backend/plugin/db/pg/role.go+++ b/backend/plugin/db/pg/role.go@@ -6,341 +6,18 @@ import ("fmt""strings"- "github.com/bytebase/bytebase/backend/common"- "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")-// RoleAttribute is the attribute string for role.-type RoleAttribute string--const (- // SUPERUSER is the role attribute for rolsuper.- SUPERUSER RoleAttribute = "SUPERUSER"- // NOSUPERUSER is the role attribute for rolsuper.- NOSUPERUSER RoleAttribute = "NOSUPERUSER"- // LOGIN is the role attribute for rolcanlogin.- LOGIN RoleAttribute = "LOGIN"- // NOLOGIN is the role attribute for rolcanlogin.- NOLOGIN RoleAttribute = "NOLOGIN"- // INHERIT is the role attribute for rolinherit.- INHERIT RoleAttribute = "INHERIT"- // NOINHERIT is the role attribute for rolinherit.- NOINHERIT RoleAttribute = "NOINHERIT"- // CREATEDB is the role attribute for rolcreatedb.- CREATEDB RoleAttribute = "CREATEDB"- // NOCREATEDB is the role attribute for rolcreatedb.- NOCREATEDB RoleAttribute = "NOCREATEDB"- // CREATEROLE is the role attribute for rolcreaterole.- CREATEROLE RoleAttribute = "CREATEROLE"- // NOCREATEROLE is the role attribute for rolcreaterole.- NOCREATEROLE RoleAttribute = "NOCREATEROLE"- // REPLICATION is the role attribute for rolreplication.- REPLICATION RoleAttribute = "REPLICATION"- // NOREPLICATION is the role attribute for rolreplication.- NOREPLICATION RoleAttribute = "NOREPLICATION"- // BYPASSRLS is the role attribute for rolbypassrls.- BYPASSRLS RoleAttribute = "BYPASSRLS"- // NOBYPASSRLS is the role attribute for rolbypassrls.- NOBYPASSRLS RoleAttribute = "NOBYPASSRLS"-)--// ToString returns the string value for role attribute.-func (a RoleAttribute) ToString() string {- return string(a)-}--type roleFind struct {- Name *string-}--// CreateRole will create the PG role.-func (driver *Driver) CreateRole(ctx context.Context, upsert *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- txn, err := driver.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer txn.Rollback()-- if err := createRoleImpl(ctx, txn, upsert); err != nil {- return nil, err- }-- roles, err := findRoleImpl(ctx, txn, &roleFind{- Name: &upsert.Name,- })- if err != nil {- return nil, err- }- if len(roles) == 0 {- return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", upsert.Name))- }-- if err := txn.Commit(); err != nil {- return nil, err- }-- return roles[0], nil-}--// UpdateRole will alter the PG role.-func (driver *Driver) UpdateRole(ctx context.Context, roleName string, upsert *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- txn, err := driver.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer txn.Rollback()-- if err := alterRoleImpl(ctx, txn, roleName, upsert); err != nil {- return nil, err- }-- roles, err := findRoleImpl(ctx, txn, &roleFind{- Name: &upsert.Name,- })- if err != nil {- return nil, err- }- if len(roles) == 0 {- return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", upsert.Name))- }-- if err := txn.Commit(); err != nil {- return nil, err- }-- return roles[0], nil-}--// FindRole will find the PG role by name.-func (driver *Driver) FindRole(ctx context.Context, roleName string) (*db.DatabaseRoleMessage, error) {- txn, err := driver.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer txn.Rollback()-- roles, err := findRoleImpl(ctx, txn, &roleFind{- Name: &roleName,- })- if err != nil {- return nil, err- }- if len(roles) == 0 {- return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", roleName))- }-- if err := txn.Commit(); err != nil {- return nil, err- }-- return roles[0], nil-}--// ListRole lists the role.-func (driver *Driver) ListRole(ctx context.Context) ([]*db.DatabaseRoleMessage, error) {- txn, err := driver.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer txn.Rollback()-- roles, err := findRoleImpl(ctx, txn, &roleFind{})- if err != nil {- return nil, err- }-- if err := txn.Commit(); err != nil {- return nil, err- }-- return roles, nil-}--// DeleteRole will drop the PG role by name.-func (driver *Driver) DeleteRole(ctx context.Context, roleName string) error {- statement := fmt.Sprintf(`DROP ROLE IF EXISTS "%s"`, roleName)- if _, err := driver.db.ExecContext(ctx, statement); err != nil {- return util.FormatErrorWithQuery(err, statement)- }-- return nil-}--func findRoleImpl(ctx context.Context, txn *sql.Tx, find *roleFind) ([]*db.DatabaseRoleMessage, error) {- where := []string{}- if v := find.Name; v != nil {- where = append(where, fmt.Sprintf("r.rolname = '%s'", *v))- }- if len(where) == 0 {- where = append(where, "r.rolname !~ '^pg_'")- }-- statement := fmt.Sprintf(`- SELECT- r.rolname,- r.rolsuper,- r.rolinherit,- r.rolcreaterole,- r.rolcreatedb,- r.rolcanlogin,- r.rolreplication,- r.rolbypassrls,- r.rolvaliduntil,- r.rolconnlimit- FROM pg_catalog.pg_roles r- WHERE %s;- `, strings.Join(where, " AND "))-- rows, err := txn.QueryContext(ctx, statement)- if err != nil {- return nil, util.FormatErrorWithQuery(err, statement)- }- defer rows.Close()-- var roleList []*db.DatabaseRoleMessage-- for rows.Next() {- var name string- var super, inherit, createRole, createDB, canLogin, replication, bypassRLS bool- var validUntil sql.NullString- var connectionLimit int32- if err := rows.Scan(- &name,- &super,- &inherit,- &createRole,- &createDB,- &canLogin,- &replication,- &bypassRLS,- &validUntil,- &connectionLimit,- ); err != nil {- return nil, util.FormatErrorWithQuery(err, statement)- }-- var attributes []string- if super {- attributes = append(attributes, SUPERUSER.ToString())- } else {- attributes = append(attributes, NOSUPERUSER.ToString())- }- if inherit {- attributes = append(attributes, INHERIT.ToString())- } else {- attributes = append(attributes, NOINHERIT.ToString())- }- if createRole {- attributes = append(attributes, CREATEROLE.ToString())- } else {- attributes = append(attributes, NOCREATEROLE.ToString())- }- if createDB {- attributes = append(attributes, CREATEDB.ToString())- } else {- attributes = append(attributes, NOCREATEDB.ToString())- }- if canLogin {- attributes = append(attributes, LOGIN.ToString())- } else {- attributes = append(attributes, NOLOGIN.ToString())- }- if replication {- attributes = append(attributes, REPLICATION.ToString())- } else {- attributes = append(attributes, NOREPLICATION.ToString())- }- if bypassRLS {- attributes = append(attributes, BYPASSRLS.ToString())- } else {- attributes = append(attributes, NOBYPASSRLS.ToString())- }-- attribute := strings.Join(attributes, " ")- role := &db.DatabaseRoleMessage{- Name: name,- ConnectionLimit: connectionLimit,- Attribute: &attribute,- }-- if validUntil.Valid {- role.ValidUntil = &validUntil.String- }-- roleList = append(roleList, role)- }-- if err := rows.Err(); err != nil {- return nil, err- }- return roleList, nil-}--func createRoleImpl(ctx context.Context, txn *sql.Tx, upsert *db.DatabaseRoleUpsertMessage) error {- statement := fmt.Sprintf(`CREATE ROLE "%s" %s;`, upsert.Name, convertToAttributeStatement(upsert))- if _, err := txn.ExecContext(ctx, statement); err != nil {- return util.FormatErrorWithQuery(err, statement)- }-- return nil-}--func alterRoleImpl(ctx context.Context, txn *sql.Tx, roleName string, upsert *db.DatabaseRoleUpsertMessage) error {- if roleName != upsert.Name {- renameStatement := fmt.Sprintf(`ALTER ROLE "%s" RENAME TO "%s";`, roleName, upsert.Name)- if _, err := txn.ExecContext(ctx, renameStatement); err != nil {- return util.FormatErrorWithQuery(err, renameStatement)- }- }-- attributeStatement := convertToAttributeStatement(upsert)- if attributeStatement == "" {- return nil- }-- statement := fmt.Sprintf(`ALTER ROLE "%s" %s;`, upsert.Name, attributeStatement)- if _, err := txn.ExecContext(ctx, statement); err != nil {- return util.FormatErrorWithQuery(err, statement)- }-- return nil-}--func convertToAttributeStatement(r *db.DatabaseRoleUpsertMessage) string {- attributeList := []string{}-- if r.Attribute != nil {- attributeList = append(attributeList, *r.Attribute)- }-- if v := r.Password; v != nil {- attributeList = append(attributeList, fmt.Sprintf("ENCRYPTED PASSWORD '%s'", *v))- }- if v := r.ValidUntil; v != nil {- attributeList = append(attributeList, fmt.Sprintf("VALID UNTIL '%s'", *v))- }- if v := r.ConnectionLimit; v != nil {- attributeList = append(attributeList, fmt.Sprintf("CONNECTION LIMIT %d", *v))- }-- attribute := ""- if len(attributeList) > 0 {- attribute = fmt.Sprintf("WITH %s", strings.Join(attributeList, " "))- }-- return attribute-}--func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {query := `SELECT r.rolname, r.rolsuper, r.rolinherit, r.rolcreaterole, r.rolcreatedb, r.rolcanlogin, r.rolreplication, r.rolvaliduntil, r.rolbypassrlsFROM pg_catalog.pg_roles rWHERE r.rolname !~ '^pg_';`- var instanceRoles []*storepb.InstanceRoleMetadata+ var instanceRoles []*storepb.InstanceRolerows, err := driver.db.QueryContext(ctx, query)if err != nil {return nil, util.FormatErrorWithQuery(err, query)@@ -392,10 +69,10 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instanceif bypassRLS {attributes = append(attributes, "Bypass RLS+")}-- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: role,- Grant: strings.Join(attributes, ", "),+ attribute := strings.Join(attributes, " ")+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: role,+ Attribute: &attribute,})}if err := rows.Err(); err != nil {diff --git a/backend/plugin/db/pg/sync.go b/backend/plugin/db/pg/sync.goindex b832f69015..db7fb03c04 100644--- a/backend/plugin/db/pg/sync.go+++ b/backend/plugin/db/pg/sync.go@@ -52,9 +52,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: instanceRoles,- Databases: filteredDatabases,+ Version: version,+ Databases: filteredDatabases,+ Metadata: &storepb.InstanceMetadata{+ Roles: instanceRoles,+ },}, nil}diff --git a/backend/plugin/db/redshift/role.go b/backend/plugin/db/redshift/role.goindex aac4ece2cf..1d942cfbe6 100644--- a/backend/plugin/db/redshift/role.go+++ b/backend/plugin/db/redshift/role.go@@ -2,33 +2,88 @@ package redshiftimport ("context"+ "database/sql"+ "fmt"+ "strings"- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/db"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")-// CreateRole creates the role.-func (*Driver) CreateRole(_ context.Context, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("create role for Redshift is not implemented yet")-}--// UpdateRole updates the role.-func (*Driver) UpdateRole(_ context.Context, _ string, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("update role for Redshift is not implemented yet")-}--// FindRole finds the role by name.-func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("find role for Redshift is not implemented yet")-}--// ListRole lists the role.-func (*Driver) ListRole(_ context.Context) ([]*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("list role for Redshift is not implemented yet")-}+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {+ // Reference: https://sourcegraph.com/github.com/postgres/postgres@REL_14_0/-/blob/src/bin/psql/describe.c?L3792+ query := `+ SELECT+ u.usename AS rolename,+ u.usesuper AS rolsuper,+ true AS rolinherit,+ false AS rolcreaterole,+ u.usecreatedb AS rolcreatedb,+ true AS rolcanlogin,+ -1 AS rolconnlimit,+ u.valuntil as rolvaliduntil+ FROM pg_catalog.pg_user u+ ORDER BY 1;+ `+ var instanceRoles []*storepb.InstanceRole+ rows, err := driver.db.QueryContext(ctx, query)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ for rows.Next() {+ var role string+ var super, inherit, createrole, createdb, canLogin bool+ var connectionLimit int32+ var validUntil sql.NullString+ if err := rows.Scan(+ &role,+ &super,+ &inherit,+ &createrole,+ &createdb,+ &canLogin,+ &connectionLimit,+ &validUntil,+ ); err != nil {+ return nil, err+ }-// DeleteRole deletes the role by name.-func (*Driver) DeleteRole(_ context.Context, _ string) error {- return errors.Errorf("delete role for Redshift is not implemented yet")+ var attributes []string+ if super {+ attributes = append(attributes, "Superuser")+ }+ if !inherit {+ attributes = append(attributes, "No inheritance")+ }+ if createrole {+ attributes = append(attributes, "Create role")+ }+ if createdb {+ attributes = append(attributes, "Create DB")+ }+ if !canLogin {+ attributes = append(attributes, "Cannot login")+ }+ if connectionLimit >= 0 {+ if connectionLimit == 0 {+ attributes = append(attributes, "No connections")+ } else if connectionLimit == 1 {+ attributes = append(attributes, "1 connection")+ } else {+ attributes = append(attributes, fmt.Sprintf("%d connections", connectionLimit))+ }+ }+ if validUntil.Valid {+ attributes = append(attributes, fmt.Sprintf("Password valid until %s", validUntil.String))+ }+ attribute := strings.Join(attributes, " ")+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: role,+ Attribute: &attribute,+ })+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return instanceRoles, nil}diff --git a/backend/plugin/db/redshift/sync.go b/backend/plugin/db/redshift/sync.goindex f1ffe2a902..7cdd187720 100644--- a/backend/plugin/db/redshift/sync.go+++ b/backend/plugin/db/redshift/sync.go@@ -46,90 +46,14 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: instanceRoles,- Databases: filteredDatabases,+ Version: version,+ Databases: filteredDatabases,+ Metadata: &storepb.InstanceMetadata{+ Roles: instanceRoles,+ },}, nil}-func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {- // Reference: https://sourcegraph.com/github.com/postgres/postgres@REL_14_0/-/blob/src/bin/psql/describe.c?L3792- query := `- SELECT- u.usename AS rolename,- u.usesuper AS rolsuper,- true AS rolinherit,- false AS rolcreaterole,- u.usecreatedb AS rolcreatedb,- true AS rolcanlogin,- -1 AS rolconnlimit,- u.valuntil as rolvaliduntil- FROM pg_catalog.pg_user u- ORDER BY 1;- `- var instanceRoles []*storepb.InstanceRoleMetadata- rows, err := driver.db.QueryContext(ctx, query)- if err != nil {- return nil, err- }- defer rows.Close()- for rows.Next() {- var role string- var super, inherit, createrole, createdb, canLogin bool- var connectionLimit int32- var validUntil sql.NullString- if err := rows.Scan(- &role,- &super,- &inherit,- &createrole,- &createdb,- &canLogin,- &connectionLimit,- &validUntil,- ); err != nil {- return nil, err- }-- var attributes []string- if super {- attributes = append(attributes, "Superuser")- }- if !inherit {- attributes = append(attributes, "No inheritance")- }- if createrole {- attributes = append(attributes, "Create role")- }- if createdb {- attributes = append(attributes, "Create DB")- }- if !canLogin {- attributes = append(attributes, "Cannot login")- }- if connectionLimit >= 0 {- if connectionLimit == 0 {- attributes = append(attributes, "No connections")- } else if connectionLimit == 1 {- attributes = append(attributes, "1 connection")- } else {- attributes = append(attributes, fmt.Sprintf("%d connections", connectionLimit))- }- }- if validUntil.Valid {- attributes = append(attributes, fmt.Sprintf("Password valid until %s", validUntil.String))- }- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: role,- Grant: strings.Join(attributes, ", "),- })- }- if err := rows.Err(); err != nil {- return nil, err- }- return instanceRoles, nil-}-// SyncDBSchema syncs a single database schema.func (driver *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchemaMetadata, error) {// Query db infodiff --git a/backend/plugin/db/risingwave/role.go b/backend/plugin/db/risingwave/role.goindex 46a1920ad4..e599cd30de 100644--- a/backend/plugin/db/risingwave/role.go+++ b/backend/plugin/db/risingwave/role.go@@ -333,13 +333,13 @@ func convertToAttributeStatement(r *db.DatabaseRoleUpsertMessage) string {return attribute}-func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {query := `SELECT r.rolname, r.rolsuper, r.rolinherit, r.rolcreaterole, r.rolcreatedb, r.rolcanlogin, r.rolreplication, r.rolvaliduntil, r.rolbypassrlsFROM pg_catalog.pg_roles rWHERE r.rolname !~ '^pg_';`- var instanceRoles []*storepb.InstanceRoleMetadata+ var instanceRoles []*storepb.InstanceRolerows, err := driver.db.QueryContext(ctx, query)if err != nil {return nil, util.FormatErrorWithQuery(err, query)@@ -388,10 +388,10 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instanceif bypassRLS {attributes = append(attributes, "Bypass RLS+")}-- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: role,- Grant: strings.Join(attributes, ", "),+ attribute := strings.Join(attributes, " ")+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: role,+ Attribute: &attribute,})}if err := rows.Err(); err != nil {diff --git a/backend/plugin/db/risingwave/sync.go b/backend/plugin/db/risingwave/sync.goindex fec85094e2..0b2f89d5b2 100644--- a/backend/plugin/db/risingwave/sync.go+++ b/backend/plugin/db/risingwave/sync.go@@ -38,9 +38,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: instanceRoles,- Databases: databases,+ Version: version,+ Databases: databases,+ Metadata: &storepb.InstanceMetadata{+ Roles: instanceRoles,+ },}, nil}diff --git a/backend/plugin/db/snowflake/role.go b/backend/plugin/db/snowflake/role.goindex c1d711451f..35b918944a 100644--- a/backend/plugin/db/snowflake/role.go+++ b/backend/plugin/db/snowflake/role.go@@ -4,39 +4,11 @@ import ("context""strings"- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"storepb "github.com/bytebase/bytebase/proto/generated-go/store")-// CreateRole creates the role.-func (*Driver) CreateRole(_ context.Context, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("create role for Snowflake is not implemented yet")-}--// UpdateRole updates the role.-func (*Driver) UpdateRole(_ context.Context, _ string, _ *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("update role for Snowflake is not implemented yet")-}--// FindRole finds the role by name.-func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("find role for Snowflake is not implemented yet")-}--// ListRole lists the role.-func (*Driver) ListRole(_ context.Context) ([]*db.DatabaseRoleMessage, error) {- return nil, errors.Errorf("list role for Snowflake is not implemented yet")-}--// DeleteRole deletes the role by name.-func (*Driver) DeleteRole(_ context.Context, _ string) error {- return errors.Errorf("delete role for Snowflake is not implemented yet")-}--func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {grantQuery := `SELECTGRANTEE_NAME,@@ -73,7 +45,7 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceWHERE DELETED_ON IS NULLORDER BY name ASC`- var instanceRoles []*storepb.InstanceRoleMetadata+ var instanceRoles []*storepb.InstanceRolerows, err := driver.db.QueryContext(ctx, userQuery)if err != nil {return nil, util.FormatErrorWithQuery(err, userQuery)@@ -87,9 +59,10 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instancereturn nil, err}- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: name,- Grant: strings.Join(grants[name], ", "),+ attribute := strings.Join(grants[name], ", ")+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: name,+ Attribute: &attribute,})}if err := rows.Err(); err != nil {diff --git a/backend/plugin/db/snowflake/sync.go b/backend/plugin/db/snowflake/sync.goindex bcd495d467..a9c66bc1a7 100644--- a/backend/plugin/db/snowflake/sync.go+++ b/backend/plugin/db/snowflake/sync.go@@ -47,9 +47,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: instanceRoles,- Databases: databaseMetadataSlice,+ Version: version,+ Databases: databaseMetadataSlice,+ Metadata: &storepb.InstanceMetadata{+ Roles: instanceRoles,+ },}, nil}diff --git a/backend/plugin/db/starrocks/role.go b/backend/plugin/db/starrocks/role.goindex b9c54bdb69..25504f3013 100644--- a/backend/plugin/db/starrocks/role.go+++ b/backend/plugin/db/starrocks/role.go@@ -34,6 +34,6 @@ func (*Driver) DeleteRole(_ context.Context, _ string) error {return errors.Errorf("not implemented")}-func (*Driver) getInstanceRoles(_ context.Context) ([]*storepb.InstanceRoleMetadata, error) {+func (*Driver) getInstanceRoles(_ context.Context) ([]*storepb.InstanceRole, error) {return nil, nil}diff --git a/backend/plugin/db/starrocks/sync.go b/backend/plugin/db/starrocks/sync.goindex 5e3bc872aa..1e5c2fc819 100644--- a/backend/plugin/db/starrocks/sync.go+++ b/backend/plugin/db/starrocks/sync.go@@ -56,7 +56,7 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}}- users, err := driver.getInstanceRoles(ctx)+ instanceRoles, err := driver.getInstanceRoles(ctx)if err != nil {return nil, err}@@ -97,11 +97,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: users,- Databases: databases,+ Version: version,+ Databases: databases,Metadata: &storepb.InstanceMetadata{MysqlLowerCaseTableNames: int32(lowerCaseTableNames),+ Roles: instanceRoles,},}, nil}diff --git a/backend/plugin/db/tidb/role.go b/backend/plugin/db/tidb/role.goindex a59faf8a42..b281ea788b 100644--- a/backend/plugin/db/tidb/role.go+++ b/backend/plugin/db/tidb/role.go@@ -382,8 +382,8 @@ func (driver *Driver) findRoleGrant(ctx context.Context, name string) (string, ereturn strings.Join(grantList, ";\n"), nil}-func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {- var instanceRoles []*storepb.InstanceRoleMetadata+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRole, error) {+ var instanceRoles []*storepb.InstanceRolevar users []stringvar err errorusers, err = driver.getUsersFromMySQLUser(ctx)@@ -404,9 +404,10 @@ func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.Instanceif err != nil {return nil, errors.Wrapf(err, "failed to get grants for %s", name)}- instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{- Name: name,- Grant: strings.Join(grantList, "\n"),+ attribute := strings.Join(grantList, "\n")+ instanceRoles = append(instanceRoles, &storepb.InstanceRole{+ Name: name,+ Attribute: &attribute,})}return instanceRoles, nildiff --git a/backend/plugin/db/tidb/sync.go b/backend/plugin/db/tidb/sync.goindex 8b752a77a4..de52f6a44f 100644--- a/backend/plugin/db/tidb/sync.go+++ b/backend/plugin/db/tidb/sync.go@@ -72,7 +72,7 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}}- users, err := driver.getInstanceRoles(ctx)+ instanceRoles, err := driver.getInstanceRoles(ctx)if err != nil {return nil, err}@@ -109,11 +109,11 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, e}return &db.InstanceMetadata{- Version: version,- InstanceRoles: users,- Databases: databases,+ Version: version,+ Databases: databases,Metadata: &storepb.InstanceMetadata{MysqlLowerCaseTableNames: int32(lowerCaseTableNames),+ Roles: instanceRoles,},}, nil}diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.goindex 16983b0cd5..ff070d9bf3 100644--- a/backend/runner/schemasync/syncer.go+++ b/backend/runner/schemasync/syncer.go@@ -260,13 +260,14 @@ func (s *Syncer) SyncInstance(ctx context.Context, instance *store.InstanceMessareturn nil, errors.Wrapf(err, "failed to sync instance: %s", instance.ResourceID)}+ if instanceMeta.Metadata == nil {+ instanceMeta.Metadata = &storepb.InstanceMetadata{}+ }+ instanceMeta.Metadata.LastSyncTime = timestamppb.Now()updateInstance := &store.UpdateInstanceMessage{ResourceID: instance.ResourceID,- Metadata: &storepb.InstanceMetadata{- LastSyncTime: timestamppb.Now(),- MysqlLowerCaseTableNames: instanceMeta.Metadata.GetMysqlLowerCaseTableNames(),- },- UpdaterID: api.SystemBotID,+ Metadata: instanceMeta.Metadata,+ UpdaterID: api.SystemBotID,}if instanceMeta.Version != instance.EngineVersion {updateInstance.EngineVersion = &instanceMeta.Version@@ -276,17 +277,6 @@ func (s *Syncer) SyncInstance(ctx context.Context, instance *store.InstanceMessareturn nil, err}- var instanceUsers []*store.InstanceUserMessage- for _, instanceUser := range instanceMeta.InstanceRoles {- instanceUsers = append(instanceUsers, &store.InstanceUserMessage{- Name: instanceUser.Name,- Grant: instanceUser.Grant,- })- }- if err := s.store.UpsertInstanceUsers(ctx, instance.UID, instanceUsers); err != nil {- return updatedInstance, err- }-databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID})if err != nil {return updatedInstance, errors.Wrapf(err, "failed to sync database for instance: %s. Failed to find database list", instance.ResourceID)diff --git a/backend/store/instance_user.go b/backend/store/instance_user.godeleted file mode 100644index 46c752a68b..0000000000--- a/backend/store/instance_user.go+++ /dev/null@@ -1,185 +0,0 @@-package store--import (- "context"- "fmt"- "strings"- "time"-- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/common"- api "github.com/bytebase/bytebase/backend/legacyapi"-)--// InstanceUserMessage is the mssage for instance user.-type InstanceUserMessage struct {- Name string- Grant string-}--// FindInstanceUserMessage is the message for finding instance users.-type FindInstanceUserMessage struct {- InstanceUID int- Name *string-}--// GetInstanceUser gets an instance users.-func (s *Store) GetInstanceUser(ctx context.Context, find *FindInstanceUserMessage) (*InstanceUserMessage, error) {- instanceUsers, err := s.ListInstanceUsers(ctx, find)- if err != nil {- return nil, err- }- if len(instanceUsers) == 0 {- return nil, nil- } else if len(instanceUsers) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d instance users with filter %+v, expect 1", len(instanceUsers), find)}- }- return instanceUsers[0], nil-}--// ListInstanceUsers lists all the instance users.-func (s *Store) ListInstanceUsers(ctx context.Context, find *FindInstanceUserMessage) ([]*InstanceUserMessage, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer tx.Rollback()-- instanceUsers, err := listInstanceUsersImpl(ctx, tx, find)- if err != nil {- return nil, err- }-- if err := tx.Commit(); err != nil {- return nil, err- }-- return instanceUsers, nil-}--// UpsertInstanceUsers will reconcile instance users for the instance.-func (s *Store) UpsertInstanceUsers(ctx context.Context, instanceUID int, instanceUsers []*InstanceUserMessage) error {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return err- }- defer tx.Rollback()-- oldInstanceUsers, err := listInstanceUsersImpl(ctx, tx, &FindInstanceUserMessage{InstanceUID: instanceUID})- if err != nil {- return err- }- deletes, upserts := getInstanceUsersDiff(oldInstanceUsers, instanceUsers)- if len(deletes) == 0 && len(upserts) == 0 {- return nil- }-- // Delete instance users that no longer exist.- if len(deletes) > 0 {- deleteArgs := []any{instanceUID}- var deletePlaceholders []string- for i, d := range deletes {- deleteArgs = append(deleteArgs, d)- deletePlaceholders = append(deletePlaceholders, fmt.Sprintf("$%d", i+2))- }- deleteQuery := fmt.Sprintf(`- DELETE FROM instance_user WHERE instance_id = $1 AND name IN (%s)- `, strings.Join(deletePlaceholders, ", "))- if _, err := tx.ExecContext(ctx, deleteQuery, deleteArgs...); err != nil {- return err- }- }- // Upsert instance users.- if len(upserts) > 0 {- args := []any{}- var placeholders []string- for i, instanceUser := range upserts {- args = append(args, api.SystemBotID, api.SystemBotID, time.Now().Unix(), instanceUID, instanceUser.Name, instanceUser.Grant)- placeholders = append(placeholders, fmt.Sprintf("($%d, $%d, $%d, $%d, $%d, $%d)", 6*i+1, 6*i+2, 6*i+3, 6*i+4, 6*i+5, 6*i+6))- }- query := fmt.Sprintf(`- INSERT INTO instance_user (- creator_id,- updater_id,- updated_ts,- instance_id,- name,- "grant"- )- VALUES %s- ON CONFLICT (instance_id, name) DO UPDATE SET- updater_id = excluded.updater_id,- updated_ts = extract(epoch from now()),- "grant" = excluded.grant- `, strings.Join(placeholders, ", "))- if _, err := tx.ExecContext(ctx, query, args...); err != nil {- return err- }- }-- return tx.Commit()-}--func getInstanceUsersDiff(oldInstanceUsers, instanceUsers []*InstanceUserMessage) ([]string, []*InstanceUserMessage) {- instanceUserNamesMap := make(map[string]bool)- oldInstanceUserMap := make(map[string]*InstanceUserMessage)- var deletes []string- var upserts []*InstanceUserMessage- for _, instanceUser := range instanceUsers {- instanceUserNamesMap[instanceUser.Name] = true- }- for _, oldInstanceUser := range oldInstanceUsers {- oldInstanceUserMap[oldInstanceUser.Name] = oldInstanceUser- }-- for _, oldInstanceUser := range oldInstanceUsers {- if _, ok := instanceUserNamesMap[oldInstanceUser.Name]; !ok {- deletes = append(deletes, oldInstanceUser.Name)- }- }- for _, instanceUser := range instanceUsers {- if old, ok := oldInstanceUserMap[instanceUser.Name]; !ok || old.Grant != instanceUser.Grant {- upserts = append(upserts, instanceUser)- }- }- return deletes, upserts-}--func listInstanceUsersImpl(ctx context.Context, tx *Tx, find *FindInstanceUserMessage) ([]*InstanceUserMessage, error) {- where, args := []string{"TRUE"}, []any{}-- where, args = append(where, fmt.Sprintf("instance_id = $%d", len(args)+1)), append(args, find.InstanceUID)- if v := find.Name; v != nil {- where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)- }-- var instanceUsers []*InstanceUserMessage- rows, err := tx.QueryContext(ctx, `- SELECT- name, "grant"- FROM instance_user- WHERE `+strings.Join(where, " AND ")+`- ORDER BY name ASC- `,- args...,- )- if err != nil {- return nil, err- }- defer rows.Close()- for rows.Next() {- var instanceUser InstanceUserMessage- if err := rows.Scan(- &instanceUser.Name,- &instanceUser.Grant,- ); err != nil {- return nil, err- }- instanceUsers = append(instanceUsers, &instanceUser)- }- if err := rows.Err(); err != nil {- return nil, err- }- return instanceUsers, nil-}diff --git a/backend/store/instance_user_test.go b/backend/store/instance_user_test.godeleted file mode 100644index 9651f4a001..0000000000--- a/backend/store/instance_user_test.go+++ /dev/null@@ -1,23 +0,0 @@-package store--import (- "testing"-- "github.com/stretchr/testify/require"-)--func TestGetInstanceUsersDiff(t *testing.T) {- oldInstanceUsers := []*InstanceUserMessage{- {Name: "a", Grant: "1"},- {Name: "b", Grant: "2"},- {Name: "c", Grant: "3"},- }- newInstanceUsers := []*InstanceUserMessage{- {Name: "b", Grant: "2"},- {Name: "c", Grant: "8"},- {Name: "d", Grant: "4"},- }- toDelete, upserts := getInstanceUsersDiff(oldInstanceUsers, newInstanceUsers)- require.Equal(t, []string{"a"}, toDelete)- require.Equal(t, []*InstanceUserMessage{{Name: "c", Grant: "8"}, {Name: "d", Grant: "4"}}, upserts)-}diff --git a/frontend/src/types/proto/store/instance.ts b/frontend/src/types/proto/store/instance.tsindex 59583bbc69..7ec5076e0c 100644--- a/frontend/src/types/proto/store/instance.ts+++ b/frontend/src/types/proto/store/instance.ts@@ -32,8 +32,8 @@ export interface InstanceMetadata {/** InstanceRole is the API message for instance role. */export interface InstanceRole {- /** The role name. It's unique within the instance. */- roleName: string;+ /** The role name. */+ name: string;/** The connection count limit for this role. */connectionLimit?:| number@@ -218,13 +218,13 @@ export const InstanceMetadata = {};function createBaseInstanceRole(): InstanceRole {- return { roleName: "", connectionLimit: undefined, validUntil: undefined, attribute: undefined };+ return { name: "", connectionLimit: undefined, validUntil: undefined, attribute: undefined };}export const InstanceRole = {encode(message: InstanceRole, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {- if (message.roleName !== "") {- writer.uint32(10).string(message.roleName);+ if (message.name !== "") {+ writer.uint32(10).string(message.name);}if (message.connectionLimit !== undefined) {writer.uint32(16).int32(message.connectionLimit);@@ -250,7 +250,7 @@ export const InstanceRole = {break;}- message.roleName = reader.string();+ message.name = reader.string();continue;case 2:if (tag !== 16) {@@ -284,7 +284,7 @@ export const InstanceRole = {fromJSON(object: any): InstanceRole {return {- roleName: isSet(object.roleName) ? globalThis.String(object.roleName) : "",+ name: isSet(object.name) ? globalThis.String(object.name) : "",connectionLimit: isSet(object.connectionLimit) ? globalThis.Number(object.connectionLimit) : undefined,validUntil: isSet(object.validUntil) ? globalThis.String(object.validUntil) : undefined,attribute: isSet(object.attribute) ? globalThis.String(object.attribute) : undefined,@@ -293,8 +293,8 @@ export const InstanceRole = {toJSON(message: InstanceRole): unknown {const obj: any = {};- if (message.roleName !== "") {- obj.roleName = message.roleName;+ if (message.name !== "") {+ obj.name = message.name;}if (message.connectionLimit !== undefined) {obj.connectionLimit = Math.round(message.connectionLimit);@@ -313,7 +313,7 @@ export const InstanceRole = {},fromPartial(object: DeepPartial<InstanceRole>): InstanceRole {const message = createBaseInstanceRole();- message.roleName = object.roleName ?? "";+ message.name = object.name ?? "";message.connectionLimit = object.connectionLimit ?? undefined;message.validUntil = object.validUntil ?? undefined;message.attribute = object.attribute ?? undefined;diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex d9990e4833..580c80c9f6 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -10373,9 +10373,9 @@ components:InstanceRole:type: objectproperties:- roleName:+ name:type: string- description: The role name. It's unique within the instance.+ description: The role name.connectionLimit:type: integerdescription: The connection count limit for this role.diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex 02f764440e..f16bc5eea4 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -2112,7 +2112,7 @@ InstanceRole is the API message for instance role.| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| role_name | [string](#string) | | The role name. It's unique within the instance. |+| name | [string](#string) | | The role name. || connection_limit | [int32](#int32) | optional | The connection count limit for this role. || valid_until | [string](#string) | optional | The expiration for the role's password. || attribute | [string](#string) | optional | The role attribute. For PostgreSQL, it containt super_user, no_inherit, create_role, create_db, can_login, replication and bypass_rls. Docs: https://www.postgresql.org/docs/current/role-attributes.html For MySQL, it's the global privileges as GRANT statements, which means it only contains "GRANT ... ON *.* TO ...". Docs: https://dev.mysql.com/doc/refman/8.0/en/grant.html |diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex c10e506b76..4d5fe4750d 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -5848,10 +5848,10 @@ The default is 10 if the value is unset or zero. </p></td><tbody><tr>- <td>role_name</td>+ <td>name</td><td><a href="#string">string</a></td><td></td>- <td><p>The role name. It's unique within the instance. </p></td>+ <td><p>The role name. </p></td></tr><tr>diff --git a/proto/generated-go/store/instance.pb.go b/proto/generated-go/store/instance.pb.goindex 5590d092ec..35772c33bb 100644--- a/proto/generated-go/store/instance.pb.go+++ b/proto/generated-go/store/instance.pb.go@@ -153,8 +153,8 @@ type InstanceRole struct {sizeCache protoimpl.SizeCacheunknownFields protoimpl.UnknownFields- // The role name. It's unique within the instance.- RoleName string `protobuf:"bytes,1,opt,name=role_name,json=roleName,proto3" json:"role_name,omitempty"`+ // The role name.+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`// The connection count limit for this role.ConnectionLimit *int32 `protobuf:"varint,2,opt,name=connection_limit,json=connectionLimit,proto3,oneof" json:"connection_limit,omitempty"`// The expiration for the role's password.@@ -197,9 +197,9 @@ func (*InstanceRole) Descriptor() ([]byte, []int) {return file_store_instance_proto_rawDescGZIP(), []int{2}}-func (x *InstanceRole) GetRoleName() string {+func (x *InstanceRole) GetName() string {if x != nil {- return x.RoleName+ return x.Name}return ""}@@ -255,23 +255,22 @@ var file_store_instance_proto_rawDesc = []byte{0x74, 0x53, 0x79, 0x6e, 0x63, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x32, 0x0a, 0x05, 0x72, 0x6f, 0x6c,0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62,0x61, 0x73, 0x65, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6e,- 0x63, 0x65, 0x52, 0x6f, 0x6c, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x22, 0xd7, 0x01,- 0x0a, 0x0c, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x52, 0x6f, 0x6c, 0x65, 0x12, 0x1b,- 0x0a, 0x09, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,- 0x09, 0x52, 0x08, 0x72, 0x6f, 0x6c, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2e, 0x0a, 0x10, 0x63,- 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18,- 0x02, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74,- 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x88, 0x01, 0x01, 0x12, 0x24, 0x0a, 0x0b, 0x76,- 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x75, 0x6e, 0x74, 0x69, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09,- 0x48, 0x01, 0x52, 0x0a, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x55, 0x6e, 0x74, 0x69, 0x6c, 0x88, 0x01,- 0x01, 0x12, 0x21, 0x0a, 0x09, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x18, 0x04,- 0x20, 0x01, 0x28, 0x09, 0x48, 0x02, 0x52, 0x09, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74,- 0x65, 0x88, 0x01, 0x01, 0x42, 0x13, 0x0a, 0x11, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74,- 0x69, 0x6f, 0x6e, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x42, 0x0e, 0x0a, 0x0c, 0x5f, 0x76, 0x61,- 0x6c, 0x69, 0x64, 0x5f, 0x75, 0x6e, 0x74, 0x69, 0x6c, 0x42, 0x0c, 0x0a, 0x0a, 0x5f, 0x61, 0x74,- 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x42, 0x14, 0x5a, 0x12, 0x67, 0x65, 0x6e, 0x65, 0x72,- 0x61, 0x74, 0x65, 0x64, 0x2d, 0x67, 0x6f, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70,- 0x72, 0x6f, 0x74, 0x6f, 0x33,+ 0x63, 0x65, 0x52, 0x6f, 0x6c, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x22, 0xce, 0x01,+ 0x0a, 0x0c, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x52, 0x6f, 0x6c, 0x65, 0x12, 0x12,+ 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61,+ 0x6d, 0x65, 0x12, 0x2e, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e,+ 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x0f,+ 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x88,+ 0x01, 0x01, 0x12, 0x24, 0x0a, 0x0b, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x75, 0x6e, 0x74, 0x69,+ 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x48, 0x01, 0x52, 0x0a, 0x76, 0x61, 0x6c, 0x69, 0x64,+ 0x55, 0x6e, 0x74, 0x69, 0x6c, 0x88, 0x01, 0x01, 0x12, 0x21, 0x0a, 0x09, 0x61, 0x74, 0x74, 0x72,+ 0x69, 0x62, 0x75, 0x74, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x48, 0x02, 0x52, 0x09, 0x61,+ 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x88, 0x01, 0x01, 0x42, 0x13, 0x0a, 0x11, 0x5f,+ 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74,+ 0x42, 0x0e, 0x0a, 0x0c, 0x5f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x75, 0x6e, 0x74, 0x69, 0x6c,+ 0x42, 0x0c, 0x0a, 0x0a, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x42, 0x14,+ 0x5a, 0x12, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x2d, 0x67, 0x6f, 0x2f, 0x73,+ 0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,}var (diff --git a/proto/store/instance.proto b/proto/store/instance.protoindex ba5910a0b2..4345c0ea03 100644--- a/proto/store/instance.proto+++ b/proto/store/instance.proto@@ -32,8 +32,8 @@ message InstanceMetadata {// InstanceRole is the API message for instance role.message InstanceRole {- // The role name. It's unique within the instance.- string role_name = 1;+ // The role name.+ string name = 1;// The connection count limit for this role.optional int32 connection_limit = 2;