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(sql-review): implement MySQL collation-allowlist rule (#2949)
rebelice77eb7b301e68
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex c98ac1976b..996fec87aa 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -151,6 +151,9 @@ const (// MySQLCharsetAllowlist is an advisor type for MySQL charset allowlist.MySQLCharsetAllowlist Type = "bb.plugin.advisor.mysql.charset.allowlist"+ // MySQLCollationAllowlist is an advisor type for MySQL collation allowlist.+ MySQLCollationAllowlist Type = "bb.plugin.advisor.mysql.collation.allowlist"+// MySQLIndexTypeNoBlob is an advisor type for MySQL index type no blob.MySQLIndexTypeNoBlob Type = "bb.plugin.advisor.mysql.index.type-no-blob"diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex f0b518ca71..5113409929 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -106,6 +106,9 @@ const (DeleteUseOrderBy Code = 1105DeleteUseLimit Code = 1106InsertNotSpecifyColumn Code = 1107++ // 1201 ~ 1299 collation error code.+ DisabledCollation Code = 1201)// Int returns the int type of code.diff --git a/plugin/advisor/mysql/advisor_charset_allowlist.go b/plugin/advisor/mysql/advisor_charset_allowlist.goindex c4b3ce24c3..7b8917afac 100644--- a/plugin/advisor/mysql/advisor_charset_allowlist.go+++ b/plugin/advisor/mysql/advisor_charset_allowlist.go@@ -37,7 +37,7 @@ func (*CharsetAllowlistAdvisor) Check(ctx advisor.Context, statement string) ([]if err != nil {return nil, err}- payload, err := advisor.UnmarshalCharsetAllowlistRulePayload(ctx.Rule.Payload)+ payload, err := advisor.UnmarshalAllowlistRulePayload(ctx.Rule.Payload)if err != nil {return nil, err}@@ -46,7 +46,7 @@ func (*CharsetAllowlistAdvisor) Check(ctx advisor.Context, statement string) ([]title: string(ctx.Rule.Type),allowlist: make(map[string]bool),}- for _, charset := range payload.CharsetAllowlist {+ for _, charset := range payload.Allowlist {checker.allowlist[strings.ToLower(charset)] = true}@@ -80,6 +80,7 @@ type charsetAllowlistChecker struct {func (checker *charsetAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {code := advisor.Okvar disabledCharset string+ line := checker.lineswitch node := in.(type) {case *ast.CreateDatabaseStmt:charset := getDatabaseCharset(node.Options)@@ -92,12 +93,14 @@ func (checker *charsetAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {if _, exist := checker.allowlist[charset]; charset != "" && !exist {code = advisor.DisabledCharsetdisabledCharset = charset+ break}for _, column := range node.Cols {charset := getColumnCharset(column)if _, exist := checker.allowlist[charset]; charset != "" && !exist {code = advisor.DisabledCharsetdisabledCharset = charset+ line = column.OriginTextPosition()break}}@@ -142,7 +145,7 @@ func (checker *charsetAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {Code: code,Title: checker.title,Content: fmt.Sprintf("\"%s\" used disabled charset '%s'", checker.text, disabledCharset),- Line: checker.line,+ Line: line,})}@@ -178,5 +181,5 @@ func getTableCharset(optionList []*ast.TableOption) string {}func getColumnCharset(column *ast.ColumnDef) string {- return column.Tp.GetCharset()+ return strings.ToLower(column.Tp.GetCharset())}diff --git a/plugin/advisor/mysql/advisor_charset_allowlist_test.go b/plugin/advisor/mysql/advisor_charset_allowlist_test.goindex 4a6f684550..063a080398 100644--- a/plugin/advisor/mysql/advisor_charset_allowlist_test.go+++ b/plugin/advisor/mysql/advisor_charset_allowlist_test.go@@ -140,8 +140,8 @@ func TestCharsetAllowlist(t *testing.T) {},}- payload, err := json.Marshal(advisor.CharsetAllowlistRulePayload{- CharsetAllowlist: []string{"utf8mb4"},+ payload, err := json.Marshal(advisor.AllowlistRulePayload{+ Allowlist: []string{"utf8mb4"},})require.NoError(t, err)advisor.RunSQLReviewRuleTests(t, tests, &CharsetAllowlistAdvisor{}, &advisor.SQLReviewRule{diff --git a/plugin/advisor/mysql/advisor_collation_allowlist.go b/plugin/advisor/mysql/advisor_collation_allowlist.gonew file mode 100644index 0000000000..6a1bb201dd--- /dev/null+++ b/plugin/advisor/mysql/advisor_collation_allowlist.go@@ -0,0 +1,185 @@+package mysql++// Framework code is generated by the generator.++import (+ "fmt"+ "strings"++ "github.com/pingcap/tidb/parser/ast"++ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/db"+)++var (+ _ advisor.Advisor = (*CollationAllowlistAdvisor)(nil)+ _ ast.Visitor = (*collationAllowlistChecker)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLCollationAllowlist, &CollationAllowlistAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLCollationAllowlist, &CollationAllowlistAdvisor{})+}++// CollationAllowlistAdvisor is the advisor checking for collation allowlist.+type CollationAllowlistAdvisor struct {+}++// Check checks for collation allowlist.+func (*CollationAllowlistAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ stmtList, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ payload, err := advisor.UnmarshalAllowlistRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &collationAllowlistChecker{+ level: level,+ title: string(ctx.Rule.Type),+ allowlist: make(map[string]bool),+ }+ for _, collation := range payload.Allowlist {+ checker.allowlist[strings.ToLower(collation)] = true+ }++ for _, stmt := range stmtList {+ checker.text = stmt.Text()+ checker.line = stmt.OriginTextPosition()+ (stmt).Accept(checker)+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return checker.adviceList, nil+}++type collationAllowlistChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+ line int+ allowlist map[string]bool+}++// Enter implements the ast.Visitor interface.+func (checker *collationAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {+ code := advisor.Ok+ var disabledCollation string+ line := checker.line+ switch node := in.(type) {+ case *ast.CreateDatabaseStmt:+ collation := getDatabaseCollation(node.Options)+ if _, exists := checker.allowlist[collation]; collation != "" && !exists {+ code = advisor.DisabledCollation+ disabledCollation = collation+ }+ case *ast.CreateTableStmt:+ collation := getTableCollation(node.Options)+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {+ code = advisor.DisabledCollation+ disabledCollation = collation+ break+ }+ for _, column := range node.Cols {+ collation := getColumnCollation(column)+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {+ code = advisor.DisabledCollation+ disabledCollation = collation+ line = column.OriginTextPosition()+ break+ }+ }+ case *ast.AlterDatabaseStmt:+ collation := getDatabaseCollation(node.Options)+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {+ code = advisor.DisabledCollation+ disabledCollation = collation+ }+ case *ast.AlterTableStmt:+ for _, spec := range node.Specs {+ switch spec.Tp {+ case ast.AlterTableOption:+ collation := getTableCollation(spec.Options)+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {+ code = advisor.DisabledCollation+ disabledCollation = collation+ }+ case ast.AlterTableAddColumns:+ for _, column := range spec.NewColumns {+ collation := getColumnCollation(column)+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {+ code = advisor.DisabledCollation+ disabledCollation = collation+ break+ }+ }+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:+ collation := getColumnCollation(spec.NewColumns[0])+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {+ code = advisor.DisabledCollation+ disabledCollation = collation+ break+ }+ }+ }+ }++ if code != advisor.Ok {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: code,+ Title: checker.title,+ Content: fmt.Sprintf("\"%s\" used disabled collation '%s'", checker.text, disabledCollation),+ Line: line,+ })+ }++ return in, false+}++// Leave implements the ast.Visitor interface.+func (*collationAllowlistChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++func getDatabaseCollation(optionList []*ast.DatabaseOption) string {+ for _, option := range optionList {+ if option.Tp == ast.DatabaseOptionCollate {+ return strings.ToLower(option.Value)+ }+ }+ return ""+}++func getTableCollation(optionList []*ast.TableOption) string {+ for _, option := range optionList {+ if option.Tp == ast.TableOptionCollate {+ return strings.ToLower(option.StrValue)+ }+ }+ return ""+}++func getColumnCollation(column *ast.ColumnDef) string {+ for _, option := range column.Options {+ if option.Tp == ast.ColumnOptionCollate {+ return strings.ToLower(option.StrValue)+ }+ }+ return ""+}diff --git a/plugin/advisor/mysql/advisor_collation_allowlist_test.go b/plugin/advisor/mysql/advisor_collation_allowlist_test.gonew file mode 100644index 0000000000..51dc931d55--- /dev/null+++ b/plugin/advisor/mysql/advisor_collation_allowlist_test.go@@ -0,0 +1,141 @@+package mysql++// Framework code is generated by the generator.++import (+ "encoding/json"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/plugin/advisor"+)++func TestCollationAllowlist(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `CREATE TABLE t(a int) COLLATE utf8mb4_polish_ci`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE t(a varchar(255))`,+ Want: []advisor.Advice{+ {+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ },+ },+ },+ {+ Statement: `CREATE TABLE t(a int) COLLATE latin1_bin`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCollation,+ Title: "collation.allowlist",+ Content: "\"CREATE TABLE t(a int) COLLATE latin1_bin\" used disabled collation 'latin1_bin'",+ Line: 1,+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(a int);+ ALTER TABLE t COLLATE latin1_bin`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCollation,+ Title: "collation.allowlist",+ Content: "\"ALTER TABLE t COLLATE latin1_bin\" used disabled collation 'latin1_bin'",+ Line: 3,+ },+ },+ },+ {+ Statement: `ALTER DATABASE test COLLATE latin1_bin`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCollation,+ Title: "collation.allowlist",+ Content: "\"ALTER DATABASE test COLLATE latin1_bin\" used disabled collation 'latin1_bin'",+ Line: 1,+ },+ },+ },+ {+ Statement: `CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCollation,+ Title: "collation.allowlist",+ Content: "\"CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin)\" used disabled collation 'latin1_bin'",+ Line: 1,+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(b int);+ ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCollation,+ Title: "collation.allowlist",+ Content: "\"ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin\" used disabled collation 'latin1_bin'",+ Line: 3,+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(a int);+ ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCollation,+ Title: "collation.allowlist",+ Content: "\"ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin\" used disabled collation 'latin1_bin'",+ Line: 3,+ },+ },+ },+ {+ Statement: `+ CREATE TABLE t(a int);+ ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCollation,+ Title: "collation.allowlist",+ Content: "\"ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin\" used disabled collation 'latin1_bin'",+ Line: 3,+ },+ },+ },+ }++ payload, err := json.Marshal(advisor.AllowlistRulePayload{+ Allowlist: []string{"utf8mb4_polish_ci"},+ })+ require.NoError(t, err)+ advisor.RunSQLReviewRuleTests(t, tests, &CollationAllowlistAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleCollationAllowlist,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: string(payload),+ }, advisor.MockMySQLDatabase)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 68fc7a7464..0cc4fb7bd0 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -118,6 +118,9 @@ const (// SchemaRuleCharsetAllowlist enforce the charset allowlist.SchemaRuleCharsetAllowlist SQLReviewRuleType = "charset.allowlist"+ // SchemaRuleCollationAllowlist enforce the collation allowlist.+ SchemaRuleCollationAllowlist SQLReviewRuleType = "collation.allowlist"+// SchemaRuleInsertRowLimit enforce the insert row limit.SchemaRuleInsertRowLimit SQLReviewRuleType = "insert.row-limit"// SchemaRuleInsertMustSpecifyColumn enforce the insert column specified.@@ -254,9 +257,9 @@ type TypeRestrictionRulePayload struct {TypeList []string `json:"typeList"`}-// CharsetAllowlistRulePayload is the payload for charset allowlist rule.-type CharsetAllowlistRulePayload struct {- CharsetAllowlist []string `json:"charsetAllowlist"`+// AllowlistRulePayload is the payload for allowlist rules.+type AllowlistRulePayload struct {+ Allowlist []string `json:"allowlist"`}// UnamrshalNamingRulePayloadAsRegexp will unmarshal payload to NamingRulePayload and compile it as regular expression.@@ -367,13 +370,13 @@ func UnmarshalTypeRestrictionRulePayload(payload string) (*TypeRestrictionRulePareturn &trr, nil}-// UnmarshalCharsetAllowlistRulePayload will unmarshal payload to CharsetAllowlistRulePayload.-func UnmarshalCharsetAllowlistRulePayload(payload string) (*CharsetAllowlistRulePayload, error) {- var cwr CharsetAllowlistRulePayload- if err := json.Unmarshal([]byte(payload), &cwr); err != nil {- return nil, errors.Wrapf(err, "failed to unmarshal charset allowlist rule payload %q", payload)+// UnmarshalAllowlistRulePayload will unmarshal payload to AllowlistRulePayload.+func UnmarshalAllowlistRulePayload(payload string) (*AllowlistRulePayload, error) {+ var allowlist AllowlistRulePayload+ if err := json.Unmarshal([]byte(payload), &allowlist); err != nil {+ return nil, errors.Wrapf(err, "failed to unmarshal allowlist rule payload %q", payload)}- return &cwr, nil+ return &allowlist, nil}// SQLReviewCheckContext is the context for SQL review check.@@ -784,6 +787,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLCharsetAllowlist, nil}+ case SchemaRuleCollationAllowlist:+ switch engine {+ case db.MySQL, db.TiDB:+ return MySQLCollationAllowlist, nil+ }case SchemaRuleIndexPKType:switch engine {case db.MySQL, db.TiDB: