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: impl approval template finder runner (#5201)
p0ny0a60b933f010
diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.gonew file mode 100644index 0000000000..7b60f02db3--- /dev/null+++ b/backend/runner/approval/runner.go@@ -0,0 +1,285 @@+// Package approval is the runner for finding approval templates for issues.+package approval++import (+ "context"+ "reflect"+ "sort"+ "sync"+ "time"++ "github.com/google/cel-go/cel"+ "github.com/pkg/errors"+ "go.uber.org/zap"+ "google.golang.org/protobuf/encoding/protojson"++ "github.com/bytebase/bytebase/backend/common/log"+ "github.com/bytebase/bytebase/backend/component/dbfactory"+ api "github.com/bytebase/bytebase/backend/legacyapi"+ "github.com/bytebase/bytebase/backend/store"+ "github.com/bytebase/bytebase/backend/utils"++ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"+)++const approvalRunnerInterval = 30 * time.Second++var predefinedVariables = []cel.EnvOption{+ // string factors+ // use environment.resource_id+ cel.Variable("environment_id", cel.StringType),+ // use project.resource_id+ cel.Variable("project_id", cel.StringType),+ cel.Variable("database_name", cel.StringType),+ cel.Variable("db_engine", cel.StringType),+ cel.Variable("sql_type", cel.StringType),++ // number factors+ cel.Variable("affected_rows", cel.IntType),+}++var riskVariables = []cel.EnvOption{+ cel.Variable("risk", cel.IntType),+ cel.Variable("source", cel.IntType),+}++var issueTypeToRiskSource = map[api.IssueType]store.RiskSource{+ // RiskSourceDatabaseSchemaUpdate+ api.IssueDatabaseSchemaUpdate: store.RiskSourceDatabaseSchemaUpdate,+ api.IssueDatabaseSchemaUpdateGhost: store.RiskSourceDatabaseSchemaUpdate,+ // RiskSourceDatabaseDataUpdate+ api.IssueDatabaseDataUpdate: store.RiskSourceDatabaseDataUpdate,+ // RiskSourceDatabaseCreate+ api.IssueDatabaseCreate: store.RiskSourceDatabaseCreate,+ // RiskSourceUnknown+ api.IssueGeneral: store.RiskSourceUnknown,+ api.IssueDatabaseRestorePITR: store.RiskSourceUnknown,+}++// Runner is the runner for finding approval templates for issues.+type Runner struct {+ store *store.Store+ dbFactory *dbfactory.DBFactory+}++// NewRunner creates a new runner.+func NewRunner(store *store.Store, dbFactory *dbfactory.DBFactory) *Runner {+ return &Runner{+ store: store,+ dbFactory: dbFactory,+ }+}++// Run runs the runner.+func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {+ ticker := time.NewTicker(approvalRunnerInterval)+ defer ticker.Stop()+ defer wg.Done()+ for {+ select {+ case <-ticker.C:+ err := func() error {+ issues, err := r.store.ListIssueV2(ctx, &store.FindIssueMessage{+ StatusList: []api.IssueStatus{api.IssueOpen},+ })+ if err != nil {+ return err+ }+ risks, err := r.store.ListRisks(ctx)+ if err != nil {+ return err+ }+ approvalSetting, err := r.store.GetWorkspaceApprovalSetting(ctx)+ if err != nil {+ return err+ }+ for _, issue := range issues {+ payload := &storepb.IssuePayload{}+ if err := protojson.Unmarshal([]byte(issue.Payload), payload); err != nil {+ return err+ }+ if payload.Approval != nil && payload.Approval.ApprovalFindingDone {+ continue+ }++ riskLevel, err := getIssueRiskLevel(ctx, r.store, issue, risks)+ if err != nil {+ return err+ }+ if riskLevel == 0 {+ continue+ }+ approvalTemplate, err := getApprovalTemplate(approvalSetting, riskLevel, issueTypeToRiskSource[issue.Type])+ if err != nil {+ return err+ }+ payload = &storepb.IssuePayload{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalTemplates: []*storepb.ApprovalTemplate{approvalTemplate},+ Approvers: nil,+ },+ }+ payloadBytes, err := protojson.Marshal(payload)+ if err != nil {+ return err+ }+ payloadStr := string(payloadBytes)+ if _, err := r.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{+ Payload: &payloadStr,+ }, api.SystemBotID); err != nil {+ return err+ }+ }++ return nil+ }()+ if err != nil {+ log.Error("approval runner", zap.Error(err))+ }++ case <-ctx.Done():+ return+ }+ }+}++func getApprovalTemplate(approvalSetting *storepb.WorkspaceApprovalSetting, riskLevel int64, riskSource store.RiskSource) (*storepb.ApprovalTemplate, error) {+ e, err := cel.NewEnv(riskVariables...)+ if err != nil {+ return nil, err+ }+ for _, rule := range approvalSetting.Rules {+ if rule.Expression == nil {+ continue+ }+ ast := cel.ParsedExprToAst(rule.Expression)+ prg, err := e.Program(ast)+ if err != nil {+ return nil, err+ }++ res, _, err := prg.Eval(map[string]interface{}{+ "risk": riskLevel,+ "source": convertToSource(riskSource),+ })+ if err != nil {+ return nil, err+ }++ val, err := res.ConvertToNative(reflect.TypeOf(false))+ if err != nil {+ return nil, errors.Wrap(err, "expect bool result")+ }+ if boolVal, ok := val.(bool); ok && boolVal {+ return rule.Template, nil+ }+ }+ return nil, nil+}++func getIssueRiskLevel(ctx context.Context, s *store.Store, issue *store.IssueMessage, risks []*store.RiskMessage) (int64, error) {+ tasks, err := s.ListTasks(ctx, &api.TaskFind{+ PipelineID: &issue.PipelineUID,+ StatusList: &[]api.TaskStatus{api.TaskPendingApproval},+ })+ if err != nil {+ return 0, err+ }+ var maxRiskLevel int64+ for _, task := range tasks {+ riskLevel, err := getTaskRiskLevel(ctx, s, issue, task, risks)+ if err != nil {+ return 0, err+ }+ if riskLevel > maxRiskLevel {+ maxRiskLevel = riskLevel+ }+ }++ return maxRiskLevel, nil+}++func getTaskRiskLevel(ctx context.Context, s *store.Store, issue *store.IssueMessage, task *store.TaskMessage, risks []*store.RiskMessage) (int64, error) {+ instance, err := s.GetInstanceV2(ctx, &store.FindInstanceMessage{+ UID: &task.InstanceID,+ })+ if err != nil {+ return 0, err+ }++ pass, err := utils.PassAllCheck(task, api.TaskCheckStatusWarn, task.TaskCheckRunRawList, instance.Engine)+ if err != nil {+ return 0, err+ }+ if !pass {+ return 0, nil+ }++ var databaseName string+ if task.Type != api.TaskDatabaseCreate {+ database, err := s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{+ UID: task.DatabaseID,+ })+ if err != nil {+ return 0, err+ }+ databaseName = database.DatabaseName+ }++ e, err := cel.NewEnv(predefinedVariables...)+ if err != nil {+ return 0, err+ }++ // higher risks go first+ sort.Slice(risks, func(i, j int) bool {+ return risks[i].Level > risks[j].Level+ })+ for _, risk := range risks {+ if risk.Source != issueTypeToRiskSource[issue.Type] {+ continue+ }++ ast := cel.ParsedExprToAst(risk.Expression)+ prg, err := e.Program(ast)+ if err != nil {+ return 0, err+ }++ // TODO(p0ny): approval, impl other factors.+ res, _, err := prg.Eval(map[string]interface{}{+ "environment_id": instance.EnvironmentID,+ "project_id": issue.Project.ResourceID,+ "database_name": databaseName,+ "db_engine": instance.Engine,+ "sql_type": "UNKNOWN",+ "affected_rows": 0,+ })+ if err != nil {+ return 0, err+ }++ val, err := res.ConvertToNative(reflect.TypeOf(false))+ if err != nil {+ return 0, errors.Wrap(err, "expect bool result")+ }+ if boolVal, ok := val.(bool); ok && boolVal {+ return risk.Level, nil+ }+ }+ return 0, nil+}++func convertToSource(source store.RiskSource) v1pb.Risk_Source {+ switch source {+ case store.RiskSourceDatabaseCreate:+ return v1pb.Risk_CREATE_DATABASE+ case store.RiskSourceDatabaseSchemaUpdate:+ return v1pb.Risk_DDL+ case store.RiskSourceDatabaseDataUpdate:+ return v1pb.Risk_DML+ }+ return v1pb.Risk_SOURCE_UNSPECIFIED+}diff --git a/backend/server/issue.go b/backend/server/issue.goindex 567de302fa..f6b6169c5d 100644--- a/backend/server/issue.go+++ b/backend/server/issue.go@@ -15,6 +15,7 @@ import ("github.com/labstack/echo/v4""github.com/pkg/errors""go.uber.org/zap"+ "google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -27,6 +28,7 @@ import ("github.com/bytebase/bytebase/backend/plugin/vcs""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")func (s *Server) registerIssueRoutes(g *echo.Group) {@@ -406,6 +408,16 @@ func (s *Server) createIssue(ctx context.Context, issueCreate *api.IssueCreate,if assignee == nil {return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("assignee %d not found", issueCreate.AssigneeID))}+ // TODO(p0ny): remove issueCreate.Payload+ issueCreatePayload := &storepb.IssuePayload{}+ issueCreatePayload.Approval = &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ }+ issueCreatePayloadBytes, err := protojson.Marshal(issueCreatePayload)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal issue payload").SetInternal(err)+ }+issueCreateMessage := &store.IssueMessage{Project: project,Title: issueCreate.Name,@@ -413,7 +425,7 @@ func (s *Server) createIssue(ctx context.Context, issueCreate *api.IssueCreate,Description: issueCreate.Description,Assignee: assignee,NeedAttention: issueCreate.AssigneeNeedAttention,- Payload: issueCreate.Payload,+ Payload: string(issueCreatePayloadBytes),}if issueCreate.ValidateOnly {diff --git a/backend/store/migration/prod/1.15/0002##backfill_issue_payload.sql b/backend/store/migration/prod/1.15/0002##backfill_issue_payload.sqlnew file mode 100644index 0000000000..816784692e--- /dev/null+++ b/backend/store/migration/prod/1.15/0002##backfill_issue_payload.sql@@ -0,0 +1,2 @@+UPDATE issue+SET payload = '{"approval": {"approvalFindingDone": true}}'\ No newline at end of filediff --git a/backend/store/pg_engine_test.go b/backend/store/pg_engine_test.goindex 34823300f6..47da6469e7 100644--- a/backend/store/pg_engine_test.go+++ b/backend/store/pg_engine_test.go@@ -222,5 +222,5 @@ func TestMigrationCompatibility(t *testing.T) {func TestGetCutoffVersion(t *testing.T) {releaseVersion, err := getProdCutoffVersion()require.NoError(t, err)- require.Equal(t, semver.MustParse("1.15.1"), releaseVersion)+ require.Equal(t, semver.MustParse("1.15.2"), releaseVersion)}diff --git a/go.mod b/go.modindex d3d073cbdb..2bc91e7df8 100644--- a/go.mod+++ b/go.mod@@ -18,6 +18,7 @@ require (github.com/go-sql-driver/mysql v1.6.0github.com/golang-jwt/jwt v3.2.2+incompatiblegithub.com/golang-jwt/jwt/v4 v4.4.2+ github.com/google/cel-go v0.13.0github.com/google/go-cmp v0.5.9github.com/google/jsonapi v1.0.0github.com/google/uuid v1.3.0@@ -65,6 +66,7 @@ require ()require (+ github.com/antlr/antlr4/runtime/Go/antlr v1.4.10 // indirectgithub.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirectgithub.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirectgithub.com/golang-sql/sqlexp v0.1.0 // indirect@@ -75,6 +77,7 @@ require (github.com/jcmturner/goidentity/v6 v6.0.1 // indirectgithub.com/jcmturner/gokrb5/v8 v8.4.2 // indirectgithub.com/jcmturner/rpc/v2 v2.0.3 // indirect+ github.com/stoewer/go-strcase v1.2.0 // indirect)require (diff --git a/go.sum b/go.sumindex 878a4cda0b..36edf08c11 100644--- a/go.sum+++ b/go.sum@@ -104,6 +104,8 @@ github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qYgithub.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q=github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=+github.com/antlr/antlr4/runtime/Go/antlr v1.4.10 h1:yL7+Jz0jTC6yykIK/Wh74gnTJnrGr5AyrNMXuA0gves=+github.com/antlr/antlr4/runtime/Go/antlr v1.4.10/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY=github.com/apache/arrow/go/arrow v0.0.0-20211112161151-bc219186db40 h1:q4dksr6ICHXqG5hm0ZW5IHyeEJXoIJSOZeBLmWPNeIQ=github.com/apache/arrow/go/arrow v0.0.0-20211112161151-bc219186db40/go.mod h1:Q7yQnSMnLvcXlZ8RV+jwz/6y1rQTqbX6C82SndT52Zs=github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=@@ -420,6 +422,8 @@ github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWgithub.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=+github.com/google/cel-go v0.13.0 h1:z+8OBOcmh7IeKyqwT/6IlnMvy621fYUqnTVPEdegGlU=+github.com/google/cel-go v0.13.0/go.mod h1:K2hpQgEjDp18J76a2DKFRlPBPpgRZgi6EbnpDgIhJ8s=github.com/google/flatbuffers v2.0.0+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=github.com/google/flatbuffers v22.10.26+incompatible h1:z1QiaMyPu1x3Z6xf2u1dsLj1ZxicdGSeaLpCuIsQNZM=github.com/google/flatbuffers v22.10.26+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=@@ -924,6 +928,8 @@ github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIngithub.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=github.com/stathat/consistent v1.0.0 h1:ZFJ1QTRn8npNBKW065raSZ8xfOqhpb8vLOkfp4CcL/U=+github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU=+github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=