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 policy in environment for OpenAPI (#3758)
ecmadao10387ca1f84c
diff --git a/api/v1/environment.go b/api/v1/environment.goindex c2d8ec18f1..e4f3c920a5 100644--- a/api/v1/environment.go+++ b/api/v1/environment.go@@ -1,24 +1,34 @@package v1+import (+ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/advisor"+)+// Environment is the API message for an environment.type Environment struct {ID int `json:"id"`+ // Related fields+ EnvironmentTierPolicy *api.EnvironmentTierPolicy `json:"environmentTierPolicy,omitempty"`+ PipelineApprovalPolicy *api.PipelineApprovalPolicy `json:"pipelineApprovalPolicy,omitempty"`+ BackupPlanPolicy *api.BackupPlanPolicy `json:"backupPlanPolicy,omitempty"`+ SQLReviewPolicy *advisor.SQLReviewPolicy `json:"sqlReviewPolicy,omitempty"`+// Domain specific fieldsName string `json:"name"`Order int `json:"order"`}-// EnvironmentPatch is the API message for patching an environment.-type EnvironmentPatch struct {+// EnvironmentUpsert is the API message for upsert an environment.+type EnvironmentUpsert struct {+ // Related fields+ EnvironmentTierPolicy *api.EnvironmentTierPolicy `json:"environmentTierPolicy"`+ PipelineApprovalPolicy *api.PipelineApprovalPolicy `json:"pipelineApprovalPolicy"`+ BackupPlanPolicy *api.BackupPlanPolicy `json:"backupPlanPolicy"`+ SQLReviewPolicy *advisor.SQLReviewPolicy `json:"sqlReviewPolicy"`+// Domain specific fieldsName *string `json:"name"`Order *int `json:"order"`}--// EnvironmentCreate is the API message for creating an environment.-type EnvironmentCreate struct {- // Domain specific fields- Name string `json:"name"`- Order *int `json:"order"`-}diff --git a/server/environment.go b/server/environment.goindex 59ac1ca34b..4efca94516 100644--- a/server/environment.go+++ b/server/environment.go@@ -13,6 +13,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/store")func (s *Server) registerEnvironmentRoutes(g *echo.Group) {@@ -23,8 +24,11 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformed create environment request").SetInternal(err)}- envCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)- env, err := s.createEnvironment(ctx, envCreate)+ env, err := s.createEnvironment(ctx, &store.EnvironmentCreate{+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),+ Name: envCreate.Name,+ Order: envCreate.Order,+ })if err != nil {return err}@@ -62,15 +66,18 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Environment ID is not a number: %s", c.Param("environmentID"))).SetInternal(err)}- envPatch := &api.EnvironmentPatch{- ID: id,- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),- }+ envPatch := &api.EnvironmentPatch{}if err := jsonapi.UnmarshalPayload(c.Request().Body, envPatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch environment request").SetInternal(err)}- env, err := s.updateEnvironment(ctx, envPatch)+ env, err := s.updateEnvironment(ctx, &store.EnvironmentPatch{+ ID: id,+ RowStatus: envPatch.RowStatus,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ Name: envPatch.Name,+ Order: envPatch.Order,+ })if err != nil {return err}@@ -94,8 +101,12 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {if !ok {return echo.NewHTTPError(http.StatusBadRequest, "Malformed environment reorder request").SetInternal(errors.New("failed to convert request item to *api.EnvironmentPatch"))}- envPatch.UpdaterID = c.Get(getPrincipalIDContextKey()).(int)- if _, err := s.store.PatchEnvironment(ctx, envPatch); err != nil {++ if _, err := s.store.PatchEnvironment(ctx, &store.EnvironmentPatch{+ ID: envPatch.ID,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ Order: envPatch.Order,+ }); err != nil {if common.ErrorCode(err) == common.NotFound {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Environment ID not found: %d", envPatch.ID))}@@ -143,7 +154,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {})}-func (s *Server) createEnvironment(ctx context.Context, create *api.EnvironmentCreate) (*api.Environment, error) {+func (s *Server) createEnvironment(ctx context.Context, create *store.EnvironmentCreate) (*api.Environment, error) {normalRowStatus := api.NormalenvFind := &api.EnvironmentFind{RowStatus: &normalRowStatus,@@ -173,7 +184,7 @@ func (s *Server) createEnvironment(ctx context.Context, create *api.EnvironmentCreturn env, nil}-func (s *Server) updateEnvironment(ctx context.Context, patch *api.EnvironmentPatch) (*api.Environment, error) {+func (s *Server) updateEnvironment(ctx context.Context, patch *store.EnvironmentPatch) (*api.Environment, error) {if v := patch.Name; v != nil {if err := api.IsValidEnvironmentName(*v); err != nil {return nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)diff --git a/server/openapi_environment.go b/server/openapi_environment.goindex 1e0c368f57..ecd91ddb0e 100644--- a/server/openapi_environment.go+++ b/server/openapi_environment.go@@ -1,10 +1,12 @@package serverimport (+ "context""encoding/json""fmt""io""net/http"+ "reflect""strconv""time"@@ -13,6 +15,7 @@ import ("github.com/bytebase/bytebase/api"openAPIV1 "github.com/bytebase/bytebase/api/v1""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/store")func (s *Server) registerOpenAPIRoutesForEnvironment(g *echo.Group) {@@ -40,7 +43,11 @@ func (s *Server) listEnvironment(c echo.Context) error {response := []*openAPIV1.Environment{}for _, env := range envList {- response = append(response, convertToOpenAPIEnvironment(env))+ env, err := s.convertToOpenAPIEnvironment(ctx, env)+ if err != nil {+ return err+ }+ response = append(response, env)}return c.JSON(http.StatusOK, response)@@ -53,21 +60,48 @@ func (s *Server) createEnvironmentByOpenAPI(c echo.Context) error {return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body").SetInternal(err)}- envCreate := &openAPIV1.EnvironmentCreate{}- if err := json.Unmarshal(body, envCreate); err != nil {+ upsert := &openAPIV1.EnvironmentUpsert{}+ if err := json.Unmarshal(body, upsert); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed create environment request").SetInternal(err)}+ if upsert.Name == nil || *upsert.Name == "" {+ return echo.NewHTTPError(http.StatusBadRequest, "Environment name is required")+ }- env, err := s.createEnvironment(ctx, &api.EnvironmentCreate{- CreatorID: c.Get(getPrincipalIDContextKey()).(int),- Name: envCreate.Name,- Order: envCreate.Order,+ if err := s.validateEnvironmentPolicy(api.PolicyTypePipelineApproval, upsert.PipelineApprovalPolicy); err != nil {+ return err+ }+ if err := s.validateEnvironmentPolicy(api.PolicyTypeBackupPlan, upsert.BackupPlanPolicy); err != nil {+ return err+ }+ if err := s.validateEnvironmentPolicy(api.PolicyTypeEnvironmentTier, upsert.EnvironmentTierPolicy); err != nil {+ return err+ }+ if err := s.validateEnvironmentPolicy(api.PolicyTypeSQLReview, upsert.SQLReviewPolicy); err != nil {+ return err+ }++ creatorID := c.Get(getPrincipalIDContextKey()).(int)++ env, err := s.createEnvironment(ctx, &store.EnvironmentCreate{+ CreatorID: creatorID,+ EnvironmentTierPolicy: upsert.EnvironmentTierPolicy,+ PipelineApprovalPolicy: upsert.PipelineApprovalPolicy,+ BackupPlanPolicy: upsert.BackupPlanPolicy,+ SQLReviewPolicy: upsert.SQLReviewPolicy,+ Name: *upsert.Name,+ Order: upsert.Order,})if err != nil {return err}- return c.JSON(http.StatusOK, convertToOpenAPIEnvironment(env))+ res, err := s.convertToOpenAPIEnvironment(ctx, env)+ if err != nil {+ return err+ }++ return c.JSON(http.StatusOK, res)}func (s *Server) getEnvironmentByID(c echo.Context) error {@@ -85,7 +119,12 @@ func (s *Server) getEnvironmentByID(c echo.Context) error {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find environment").SetInternal(err)}- return c.JSON(http.StatusOK, convertToOpenAPIEnvironment(env))+ res, err := s.convertToOpenAPIEnvironment(ctx, env)+ if err != nil {+ return err+ }++ return c.JSON(http.StatusOK, res)}func (s *Server) updateEnvironmentByOpenAPI(c echo.Context) error {@@ -100,22 +139,44 @@ func (s *Server) updateEnvironmentByOpenAPI(c echo.Context) error {return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body").SetInternal(err)}- envPatch := &openAPIV1.EnvironmentPatch{}- if err := json.Unmarshal(body, envPatch); err != nil {+ upsert := &openAPIV1.EnvironmentUpsert{}+ if err := json.Unmarshal(body, upsert); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch environment request").SetInternal(err)}- env, err := s.updateEnvironment(ctx, &api.EnvironmentPatch{- ID: id,- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),- Name: envPatch.Name,- Order: envPatch.Order,+ if err := s.validateEnvironmentPolicy(api.PolicyTypePipelineApproval, upsert.PipelineApprovalPolicy); err != nil {+ return err+ }+ if err := s.validateEnvironmentPolicy(api.PolicyTypeBackupPlan, upsert.BackupPlanPolicy); err != nil {+ return err+ }+ if err := s.validateEnvironmentPolicy(api.PolicyTypeEnvironmentTier, upsert.EnvironmentTierPolicy); err != nil {+ return err+ }+ if err := s.validateEnvironmentPolicy(api.PolicyTypeSQLReview, upsert.SQLReviewPolicy); err != nil {+ return err+ }++ env, err := s.updateEnvironment(ctx, &store.EnvironmentPatch{+ ID: id,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ EnvironmentTierPolicy: upsert.EnvironmentTierPolicy,+ PipelineApprovalPolicy: upsert.PipelineApprovalPolicy,+ BackupPlanPolicy: upsert.BackupPlanPolicy,+ SQLReviewPolicy: upsert.SQLReviewPolicy,+ Name: upsert.Name,+ Order: upsert.Order,})if err != nil {return err}- return c.JSON(http.StatusOK, convertToOpenAPIEnvironment(env))+ res, err := s.convertToOpenAPIEnvironment(ctx, env)+ if err != nil {+ return err+ }++ return c.JSON(http.StatusOK, res)}func (s *Server) deleteEnvironmentByOpenAPI(c echo.Context) error {@@ -135,7 +196,7 @@ func (s *Server) deleteEnvironmentByOpenAPI(c echo.Context) error {rowStatus := string(api.Archived)name := fmt.Sprintf("archived_%s_%d", env.Name, time.Now().Unix())- if _, err := s.updateEnvironment(ctx, &api.EnvironmentPatch{+ if _, err := s.updateEnvironment(ctx, &store.EnvironmentPatch{ID: id,UpdaterID: c.Get(getPrincipalIDContextKey()).(int),RowStatus: &rowStatus,@@ -147,10 +208,63 @@ func (s *Server) deleteEnvironmentByOpenAPI(c echo.Context) error {return c.String(http.StatusOK, "ok")}-func convertToOpenAPIEnvironment(env *api.Environment) *openAPIV1.Environment {+func (s *Server) convertToOpenAPIEnvironment(ctx context.Context, env *api.Environment) (*openAPIV1.Environment, error) {+ backupPolicy, err := s.store.GetBackupPlanPolicyByEnvID(ctx, env.ID)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find the backup policy for environment %d", env.ID)).SetInternal(err)+ }+ pipelineApprovalPolicy, err := s.store.GetPipelineApprovalPolicy(ctx, env.ID)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find the pipeline approval policy for environment %d", env.ID)).SetInternal(err)+ }+ environmentTierPolicy, err := s.store.GetEnvironmentTierPolicyByEnvID(ctx, env.ID)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find the environment tier policy for environment %d", env.ID)).SetInternal(err)+ }++ environmentResourceType := api.PolicyResourceTypeEnvironment+ sqlReviewPolicy, err := s.store.GetNormalSQLReviewPolicy(ctx, &api.PolicyFind{ResourceType: &environmentResourceType, ResourceID: &env.ID})+ if err != nil {+ if e, ok := err.(*common.Error); ok && e.Code != common.NotFound {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find the SQL review policy for environment %d", env.ID)).SetInternal(err)+ }+ }+return &openAPIV1.Environment{- ID: env.ID,- Name: env.Name,- Order: env.Order,+ ID: env.ID,+ Name: env.Name,+ Order: env.Order,+ BackupPlanPolicy: backupPolicy,+ PipelineApprovalPolicy: pipelineApprovalPolicy,+ EnvironmentTierPolicy: environmentTierPolicy,+ SQLReviewPolicy: sqlReviewPolicy,+ }, nil+}++func (s *Server) validateEnvironmentPolicy(policyType api.PolicyType, policy interface{}) error {+ if policy == nil || reflect.ValueOf(policy).IsNil() {+ return nil+ }++ bytes, err := json.Marshal(policy)+ payload := string(bytes)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, err.Error()).SetInternal(err)}++ policyUpsert := &api.PolicyUpsert{+ ResourceType: api.PolicyResourceTypeEnvironment,+ Type: api.PolicyTypePipelineApproval,+ Payload: &payload,+ }++ if err := s.hasAccessToUpsertPolicy(policyUpsert); err != nil {+ return echo.NewHTTPError(http.StatusForbidden, err.Error()).SetInternal(err)+ }++ if err := api.ValidatePolicy(api.PolicyResourceTypeEnvironment, policyType, &payload); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid %s policy: %s", policyType, payload)).SetInternal(err)+ }++ return nil}diff --git a/store/environment.go b/store/environment.goindex 8c12b0cdfe..e71c628203 100644--- a/store/environment.go+++ b/store/environment.go@@ -3,6 +3,7 @@ package storeimport ("context""database/sql"+ "encoding/json""fmt""sort""strings"@@ -11,8 +12,46 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/advisor")+// EnvironmentCreate is the API message for creating an environment.+// TODO(ed): This is an temporary struct to compatible with OpenAPI and JSONAPI. Find way to move it into the API package.+type EnvironmentCreate struct {+ // Standard fields+ CreatorID int++ // Related fields+ EnvironmentTierPolicy *api.EnvironmentTierPolicy+ PipelineApprovalPolicy *api.PipelineApprovalPolicy+ BackupPlanPolicy *api.BackupPlanPolicy+ SQLReviewPolicy *advisor.SQLReviewPolicy++ // Domain specific fields+ Name string+ Order *int+}++// EnvironmentPatch is the API message for patching an environment.+// TODO(ed): This is an temporary struct to compatible with OpenAPI and JSONAPI. Find way to move it into the API package.+type EnvironmentPatch struct {+ ID int++ // Standard fields+ RowStatus *string+ UpdaterID int++ // Related fields+ EnvironmentTierPolicy *api.EnvironmentTierPolicy+ PipelineApprovalPolicy *api.PipelineApprovalPolicy+ BackupPlanPolicy *api.BackupPlanPolicy+ SQLReviewPolicy *advisor.SQLReviewPolicy++ // Domain specific fields+ Name *string+ Order *int+}+// environmentRaw is the store model for an Environment.// Fields have exactly the same meanings as Environment.type environmentRaw struct {@@ -48,7 +87,7 @@ func (raw *environmentRaw) toEnvironment() *api.Environment {}// CreateEnvironment creates an instance of Environment.-func (s *Store) CreateEnvironment(ctx context.Context, create *api.EnvironmentCreate) (*api.Environment, error) {+func (s *Store) CreateEnvironment(ctx context.Context, create *EnvironmentCreate) (*api.Environment, error) {environmentRaw, err := s.createEnvironmentRaw(ctx, create)if err != nil {return nil, errors.Wrapf(err, "failed to create Environment with EnvironmentCreate[%+v]", create)@@ -81,7 +120,7 @@ func (s *Store) FindEnvironment(ctx context.Context, find *api.EnvironmentFind)}// PatchEnvironment patches an instance of Environment.-func (s *Store) PatchEnvironment(ctx context.Context, patch *api.EnvironmentPatch) (*api.Environment, error) {+func (s *Store) PatchEnvironment(ctx context.Context, patch *EnvironmentPatch) (*api.Environment, error) {environmentRaw, err := s.patchEnvironmentRaw(ctx, patch)if err != nil {return nil, errors.Wrapf(err, "failed to patch Environment with EnvironmentPatch[%+v]", patch)@@ -140,7 +179,7 @@ func (s *Store) composeEnvironment(ctx context.Context, raw *environmentRaw) (*a}// createEnvironmentRaw creates a new environment.-func (s *Store) createEnvironmentRaw(ctx context.Context, create *api.EnvironmentCreate) (*environmentRaw, error) {+func (s *Store) createEnvironmentRaw(ctx context.Context, create *EnvironmentCreate) (*environmentRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -152,6 +191,27 @@ func (s *Store) createEnvironmentRaw(ctx context.Context, create *api.Environmenreturn nil, err}+ if p := create.PipelineApprovalPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypePipelineApproval, p); err != nil {+ return nil, err+ }+ }+ if p := create.BackupPlanPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypeBackupPlan, p); err != nil {+ return nil, err+ }+ }+ if p := create.EnvironmentTierPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypeEnvironmentTier, p); err != nil {+ return nil, err+ }+ }+ if p := create.SQLReviewPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, environment, api.PolicyTypeSQLReview, p); err != nil {+ return nil, err+ }+ }+if err := tx.Commit(); err != nil {return nil, FormatError(err)}@@ -163,6 +223,30 @@ func (s *Store) createEnvironmentRaw(ctx context.Context, create *api.Environmenreturn environment, nil}+func upsertEnvironmentPolicy(+ ctx context.Context,+ tx *Tx,+ env *environmentRaw,+ policyType api.PolicyType,+ policy interface{},+) (*policyRaw, error) {+ bytes, err := json.Marshal(policy)+ payload := string(bytes)+ if err != nil {+ return nil, FormatError(err)+ }++ policyUpsert := &api.PolicyUpsert{+ ResourceType: api.PolicyResourceTypeEnvironment,+ ResourceID: env.ID,+ Type: policyType,+ UpdaterID: env.CreatorID,+ Payload: &payload,+ }++ return upsertPolicyImpl(ctx, tx, policyUpsert)+}+// findEnvironmentRaw retrieves a list of environments based on find.func (s *Store) findEnvironmentRaw(ctx context.Context, find *api.EnvironmentFind) ([]*environmentRaw, error) {tx, err := s.db.BeginTx(ctx, nil)@@ -224,7 +308,7 @@ func (s *Store) getEnvironmentByIDRaw(ctx context.Context, id int) (*environment// patchEnvironmentRaw updates an existing environment by ID.// Returns ENOTFOUND if environment does not exist.-func (s *Store) patchEnvironmentRaw(ctx context.Context, patch *api.EnvironmentPatch) (*environmentRaw, error) {+func (s *Store) patchEnvironmentRaw(ctx context.Context, patch *EnvironmentPatch) (*environmentRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -236,6 +320,27 @@ func (s *Store) patchEnvironmentRaw(ctx context.Context, patch *api.EnvironmentPreturn nil, FormatError(err)}+ if p := patch.PipelineApprovalPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypePipelineApproval, p); err != nil {+ return nil, err+ }+ }+ if p := patch.BackupPlanPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypeBackupPlan, p); err != nil {+ return nil, err+ }+ }+ if p := patch.EnvironmentTierPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypeEnvironmentTier, p); err != nil {+ return nil, err+ }+ }+ if p := patch.SQLReviewPolicy; p != nil {+ if _, err := upsertEnvironmentPolicy(ctx, tx, envRaw, api.PolicyTypeSQLReview, p); err != nil {+ return nil, err+ }+ }+if err := tx.Commit(); err != nil {return nil, FormatError(err)}@@ -248,7 +353,7 @@ func (s *Store) patchEnvironmentRaw(ctx context.Context, patch *api.EnvironmentP}// createEnvironmentImpl creates a new environment.-func (Store) createEnvironmentImpl(ctx context.Context, tx *Tx, create *api.EnvironmentCreate) (*environmentRaw, error) {+func (Store) createEnvironmentImpl(ctx context.Context, tx *Tx, create *EnvironmentCreate) (*environmentRaw, error) {var order intif create.Order != nil {@@ -363,7 +468,7 @@ func (*Store) findEnvironmentImpl(ctx context.Context, tx *Tx, find *api.Environ}// patchEnvironmentImpl updates a environment by ID. Returns the new state of the environment after update.-func (*Store) patchEnvironmentImpl(ctx context.Context, tx *Tx, patch *api.EnvironmentPatch) (*environmentRaw, error) {+func (*Store) patchEnvironmentImpl(ctx context.Context, tx *Tx, patch *EnvironmentPatch) (*environmentRaw, error) {// Build UPDATE clause.set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}if v := patch.RowStatus; v != nil {