Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: add validator for environment and instance service (#4067)
Danny Xub6061f838893
diff --git a/server/api/v1/common.go b/server/api/v1/common.gonew file mode 100644index 0000000000..889dbd775b--- /dev/null+++ b/server/api/v1/common.go@@ -0,0 +1,20 @@+package v1++import (+ "regexp"++ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"+)++var resourceIDMatcher = regexp.MustCompile("^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$")++func convertDeletedToState(deleted bool) v1pb.State {+ if deleted {+ return v1pb.State_STATE_DELETED+ }+ return v1pb.State_STATE_ACTIVE+}++func isValidResourceID(resourceID string) bool {+ return resourceIDMatcher.MatchString(resourceID)+}diff --git a/server/api/v1/common_test.go b/server/api/v1/common_test.gonew file mode 100644index 0000000000..31f4c7a064--- /dev/null+++ b/server/api/v1/common_test.go@@ -0,0 +1,40 @@+package v1++import (+ "testing"++ "github.com/stretchr/testify/require"+)++func TestIsValidResourceID(t *testing.T) {+ tests := []struct {+ resourceID string+ want bool+ }{+ {+ resourceID: "hello123",+ want: true,+ },+ {+ resourceID: "hello-123",+ want: true,+ },+ {+ resourceID: "你好",+ want: false,+ },+ {+ resourceID: "123abc",+ want: false,+ },+ {+ resourceID: "a1234567890123456789012345678901234567890123456789012345678901234567890",+ want: false,+ },+ }++ for _, test := range tests {+ got := isValidResourceID(test.resourceID)+ require.Equal(t, test.want, got, test.resourceID)+ }+}diff --git a/server/api/v1/environment_service.go b/server/api/v1/environment_service.goindex 921c0eafbe..964d075fb9 100644--- a/server/api/v1/environment_service.go+++ b/server/api/v1/environment_service.go@@ -11,7 +11,9 @@ import ("github.com/pkg/errors"+ "github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ enterpriseAPI "github.com/bytebase/bytebase/enterprise/api"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1""github.com/bytebase/bytebase/store")@@ -21,13 +23,15 @@ const environmentNamePrefix = "environments/"// EnvironmentService implements the environment service.type EnvironmentService struct {v1pb.UnimplementedEnvironmentServiceServer- store *store.Store+ store *store.Store+ licenseService enterpriseAPI.LicenseService}// NewEnvironmentService creates a new EnvironmentService.-func NewEnvironmentService(store *store.Store) *EnvironmentService {+func NewEnvironmentService(store *store.Store, licenseService enterpriseAPI.LicenseService) *EnvironmentService {return &EnvironmentService{- store: store,+ store: store,+ licenseService: licenseService,}}@@ -66,6 +70,24 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, request *v1pif request.Environment == nil {return nil, status.Errorf(codes.InvalidArgument, "environment must be set")}++ if err := api.IsValidEnvironmentName(request.Environment.Title); err != nil {+ return nil, status.Errorf(codes.InvalidArgument, "invalid environment title, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.")+ }+ if !isValidResourceID(request.EnvironmentId) {+ return nil, status.Errorf(codes.InvalidArgument, "invalid environment ID %v", request.EnvironmentId)+ }++ // Environment limit in the plan.+ environments, err := s.store.ListEnvironmentV2(ctx, false /* showDeleted */)+ if err != nil {+ return nil, status.Errorf(codes.Internal, err.Error())+ }+ maximumEnvironmentLimit := s.licenseService.GetPlanLimitValue(api.PlanLimitMaximumEnvironment)+ if int64(len(environments)) >= maximumEnvironmentLimit {+ return nil, status.Errorf(codes.ResourceExhausted, "current plan can create up to %d environments.", maximumEnvironmentLimit)+ }+environment, err := s.store.CreateEnvironmentV2(ctx,&store.EnvironmentMessage{EnvironmentID: request.EnvironmentId,@@ -145,6 +167,15 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, request *v1preturn nil, status.Errorf(codes.InvalidArgument, "environment %q has been deleted", environmentID)}+ // All instances in the environment must be deleted.+ count, err := s.store.CountInstance(ctx, &store.CountInstanceMessage{EnvironmentID: &environmentID})+ if err != nil {+ return nil, status.Errorf(codes.Internal, err.Error())+ }+ if count > 0 {+ return nil, status.Errorf(codes.FailedPrecondition, "all instances in the environment should be deleted")+ }+if err := s.store.DeleteOrUndeleteEnvironmentV2(ctx, environmentID, true /* delete */, principalID); err != nil {return nil, status.Errorf(codes.Internal, err.Error())}@@ -191,14 +222,10 @@ func getEnvironmentID(name string) (string, error) {}func convertEnvironment(environment *store.EnvironmentMessage) *v1pb.Environment {- state := v1pb.State_STATE_ACTIVE- if environment.Deleted {- state = v1pb.State_STATE_DELETED- }return &v1pb.Environment{Name: fmt.Sprintf("%s%s", environmentNamePrefix, environment.EnvironmentID),Title: environment.Title,Order: environment.Order,- State: state,+ State: convertDeletedToState(environment.Deleted),}}diff --git a/server/api/v1/instance_service.go b/server/api/v1/instance_service.goindex 5bd56cc4fa..85dd48b26f 100644--- a/server/api/v1/instance_service.go+++ b/server/api/v1/instance_service.go@@ -13,6 +13,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ enterpriseAPI "github.com/bytebase/bytebase/enterprise/api""github.com/bytebase/bytebase/plugin/db"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1""github.com/bytebase/bytebase/store"@@ -23,13 +24,15 @@ const instanceNamePrefix = "instances/"// InstanceService implements the instance service.type InstanceService struct {v1pb.UnimplementedInstanceServiceServer- store *store.Store+ store *store.Store+ licenseService enterpriseAPI.LicenseService}// NewInstanceService creates a new InstanceService.-func NewInstanceService(store *store.Store) *InstanceService {+func NewInstanceService(store *store.Store, licenseService enterpriseAPI.LicenseService) *InstanceService {return &InstanceService{- store: store,+ store: store,+ licenseService: licenseService,}}@@ -87,12 +90,24 @@ func (s *InstanceService) CreateInstance(ctx context.Context, request *v1pb.Creaif err != nil {return nil, status.Errorf(codes.InvalidArgument, err.Error())}+ if !isValidResourceID(request.InstanceId) {+ return nil, status.Errorf(codes.InvalidArgument, "invalid instance ID %v", request.InstanceId)+ }++ // Instance limit in the plan.+ count, err := s.store.CountInstance(ctx, &store.CountInstanceMessage{})+ if err != nil {+ return nil, status.Errorf(codes.Internal, err.Error())+ }+ subscription := s.licenseService.LoadSubscription(ctx)+ if count >= subscription.InstanceCount {+ return nil, status.Errorf(codes.ResourceExhausted, "reached the maximum instance count %d", subscription.InstanceCount)+ }instanceMessage, err := convertToInstanceMessage(request.InstanceId, request.Instance)if err != nil {return nil, status.Errorf(codes.InvalidArgument, err.Error())}-principalID := ctx.Value(common.PrincipalIDContextKey).(int)instance, err := s.store.CreateInstanceV2(ctx,environmentID,@@ -102,6 +117,8 @@ func (s *InstanceService) CreateInstance(ctx context.Context, request *v1pb.Creaif err != nil {return nil, status.Errorf(codes.Internal, err.Error())}++ // TODO(d): sync instance databases.return convertToInstance(instance), nil}@@ -152,6 +169,9 @@ func (s *InstanceService) UpdateInstance(ctx context.Context, request *v1pb.Updaif err != nil {return nil, status.Errorf(codes.Internal, err.Error())}++ // TODO(d): sync instance databases.+return convertToInstance(ins), nil}@@ -285,18 +305,13 @@ func convertToInstance(instance *store.InstanceMessage) *v1pb.Instance {})}- state := v1pb.State_STATE_ACTIVE- if instance.Deleted {- state = v1pb.State_STATE_DELETED- }-return &v1pb.Instance{Name: fmt.Sprintf("%s%s%s%s", environmentNamePrefix, instance.EnvironmentID, instanceNamePrefix, instance.InstanceID),Title: instance.Title,Engine: engine,ExternalLink: instance.ExternalLink,DataSources: dataSourceList,- State: state,+ State: convertDeletedToState(instance.Deleted),}}diff --git a/server/instance.go b/server/instance.goindex a9d566a388..b49fa552a8 100644--- a/server/instance.go+++ b/server/instance.go@@ -438,11 +438,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {// instanceCountGuard is a feature guard for instance count.// We only count instances with NORMAL status since users cannot make any operations for ARCHIVED one.func (s *Server) instanceCountGuard(ctx context.Context) error {- status := api.Normal- count, err := s.store.CountInstance(ctx, &api.InstanceFind{- RowStatus: &status,- })-+ count, err := s.store.CountInstance(ctx, &store.CountInstanceMessage{})if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to count instance").SetInternal(err)}@@ -467,9 +463,6 @@ func (s *Server) createInstance(ctx context.Context, create *store.InstanceCreatif err := s.instanceCountGuard(ctx); err != nil {return nil, err}- if err := s.validateInstanceName(ctx, create.Name); err != nil {- return nil, err- }if err := s.validateDataSourceList(create.DataSourceList); err != nil {return nil, err}@@ -514,11 +507,6 @@ func (s *Server) createInstance(ctx context.Context, create *store.InstanceCreat}func (s *Server) updateInstance(ctx context.Context, patch *store.InstancePatch) (*api.Instance, error) {- if v := patch.Name; v != nil {- if err := s.validateInstanceName(ctx, *v); err != nil {- return nil, err- }- }if v := patch.DataSourceList; v != nil {if err := s.validateDataSourceList(v); err != nil {return nil, err@@ -610,21 +598,6 @@ func (s *Server) updateInstance(ctx context.Context, patch *store.InstancePatch)return instancePatched, nil}-func (s *Server) validateInstanceName(ctx context.Context, instanceName string) error {- count, err := s.store.CountInstance(ctx, &api.InstanceFind{- Name: &instanceName,- })- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to count the instance by name").SetInternal(err)- }-- if count > 0 {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Duplicate instance name %s", instanceName))- }-- return nil-}-func (*Server) validateDataSourceList(dataSourceList []*api.DataSourceCreate) error {dataSourceMap := map[api.DataSourceType]bool{}for _, dataSource := range dataSourceList {diff --git a/server/server.go b/server/server.goindex 25cefa70ca..e605bfc9e6 100644--- a/server/server.go+++ b/server/server.go@@ -307,6 +307,8 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {mux := runtime.NewServeMux()v1pb.RegisterGreeterServiceServer(s.grpcServer, &v1.GreeterServerImpl{})v1pb.RegisterAuthServiceServer(s.grpcServer, v1.NewAuthService(s.store, s.secret, &profile))+ v1pb.RegisterEnvironmentServiceServer(s.grpcServer, v1.NewEnvironmentService(s.store, s.licenseService))+ v1pb.RegisterInstanceServiceServer(s.grpcServer, v1.NewInstanceService(s.store, s.licenseService))opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}grpcEndpoint := fmt.Sprintf(":%d", profile.GrpcPort)if err := v1pb.RegisterAuthServiceHandlerFromEndpoint(ctx, mux, grpcEndpoint, opts); err != nil {diff --git a/store/instance.go b/store/instance.goindex 71630d3d8c..a06b44c8eb 100644--- a/store/instance.go+++ b/store/instance.go@@ -169,27 +169,6 @@ func (s *Store) PatchInstance(ctx context.Context, patch *InstancePatch) (*api.Ireturn instance, nil}-// CountInstance counts the number of instances.-func (s *Store) CountInstance(ctx context.Context, find *api.InstanceFind) (int, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return 0, FormatError(err)- }- defer tx.Rollback()-- where, args := findInstanceQuery(find)-- query := `SELECT COUNT(*) FROM instance WHERE ` + where- var count int- if err := tx.QueryRowContext(ctx, query, args...).Scan(&count); err != nil {- if err == sql.ErrNoRows {- return 0, common.FormatDBErrorEmptyRowWithQuery(query)- }- return 0, FormatError(err)- }- return count, nil-}-// CountInstanceGroupByEngineAndEnvironmentID counts the number of instances and group by engine and environment_id.// Used by the metric collector.func (s *Store) CountInstanceGroupByEngineAndEnvironmentID(ctx context.Context) ([]*metric.InstanceCountMetric, error) {@@ -1102,3 +1081,39 @@ func (s *Store) listInstanceImplV2(ctx context.Context, tx *Tx, find *FindInstanreturn instanceMessages, nil}++// CountInstanceMessage is the message for counting instances.+type CountInstanceMessage struct {+ EnvironmentID *string+}++// CountInstance counts the number of instances.+func (s *Store) CountInstance(ctx context.Context, find *CountInstanceMessage) (int, error) {+ where, args := []string{"instance.row_status = $1"}, []interface{}{api.Normal}+ if v := find.EnvironmentID; v != nil {+ where, args = append(where, fmt.Sprintf("environment.resource_id = $%d", len(args)+1)), append(args, *v)+ }++ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return 0, FormatError(err)+ }+ defer tx.Rollback()++ query := `SELECT COUNT(1) FROM instance WHERE row_status = $1`+ var count int+ if err := tx.QueryRowContext(ctx, `+ SELECT+ count(1)+ FROM instance+ LEFT JOIN environment+ ON environment.id = instance.environment_id+ WHERE `+strings.Join(where, " AND "),+ args...).Scan(&count); err != nil {+ if err == sql.ErrNoRows {+ return 0, common.FormatDBErrorEmptyRowWithQuery(query)+ }+ return 0, FormatError(err)+ }+ return count, nil+}