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 charset allowlist rule (#2502)
rebeliced595bb531201
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 2c4ecb73a0..cecacf529e 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -40,7 +40,7 @@ func NewStatusBySQLReviewRuleLevel(level SQLReviewRuleLevel) (Status, error) {}// Type is the type of advisor.-//nolint+// nolinttype Type stringconst (@@ -142,6 +142,9 @@ const (// MySQLIndexKeyNumberLimit is an advisor type for MySQL index key number limit.MySQLIndexKeyNumberLimit Type = "bb.plugin.advisor.mysql.index.key-number-limit"+ // MySQLCharsetAllowlist is an advisor type for MySQL charset allowlist.+ MySQLCharsetAllowlist Type = "bb.plugin.advisor.mysql.charset.allowlist"+// PostgreSQL Advisor.// PostgreSQLSyntax is an advisor type for PostgreSQL syntax.diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex eb5df17f3e..fbc1551dc3 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -78,6 +78,9 @@ const (// 901 ~ 999 index error code.DuplicateColumnInIndex Code = 901++ // 1001 ~ 1099 charset error code.+ DisabledCharset Code = 1001)// Int returns the int type of code.diff --git a/plugin/advisor/mysql/advisor_charset_allowlist.go b/plugin/advisor/mysql/advisor_charset_allowlist.gonew file mode 100644index 0000000000..efd9da668d--- /dev/null+++ b/plugin/advisor/mysql/advisor_charset_allowlist.go@@ -0,0 +1,182 @@+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 = (*CharsetAllowlistAdvisor)(nil)+ _ ast.Visitor = (*charsetAllowlistChecker)(nil)+)++func init() {+ advisor.Register(db.MySQL, advisor.MySQLCharsetAllowlist, &CharsetAllowlistAdvisor{})+ advisor.Register(db.TiDB, advisor.MySQLCharsetAllowlist, &CharsetAllowlistAdvisor{})+}++// CharsetAllowlistAdvisor is the advisor checking for charset allowlist.+type CharsetAllowlistAdvisor struct {+}++// Check checks for charset allowlist.+func (*CharsetAllowlistAdvisor) 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.UnmarshalCharsetAllowlistRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &charsetAllowlistChecker{+ level: level,+ title: string(ctx.Rule.Type),+ allowlist: make(map[string]bool),+ }+ for _, charset := range payload.CharsetAllowlist {+ checker.allowlist[strings.ToLower(charset)] = 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 charsetAllowlistChecker 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 *charsetAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {+ code := advisor.Ok+ var disabledCharset string+ switch node := in.(type) {+ case *ast.CreateDatabaseStmt:+ charset := getDatabaseCharset(node.Options)+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {+ code = advisor.DisabledCharset+ disabledCharset = charset+ }+ case *ast.CreateTableStmt:+ charset := getTableCharset(node.Options)+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {+ code = advisor.DisabledCharset+ disabledCharset = charset+ }+ for _, column := range node.Cols {+ charset := getColumnCharset(column)+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {+ code = advisor.DisabledCharset+ disabledCharset = charset+ break+ }+ }+ case *ast.AlterDatabaseStmt:+ charset := getDatabaseCharset(node.Options)+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {+ code = advisor.DisabledCharset+ disabledCharset = charset+ }+ case *ast.AlterTableStmt:+ for _, spec := range node.Specs {+ switch spec.Tp {+ case ast.AlterTableOption:+ charset := getTableCharset(spec.Options)+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {+ code = advisor.DisabledCharset+ disabledCharset = charset+ }+ case ast.AlterTableAddColumns:+ for _, column := range spec.NewColumns {+ charset := getColumnCharset(column)+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {+ code = advisor.DisabledCharset+ disabledCharset = charset+ break+ }+ }+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:+ charset := getColumnCharset(spec.NewColumns[0])+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {+ code = advisor.DisabledCharset+ disabledCharset = charset+ 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 charset '%s'", checker.text, disabledCharset),+ Line: checker.line,+ })+ }++ return in, false+}++// Leave implements the ast.Visitor interface.+func (*charsetAllowlistChecker) Leave(in ast.Node) (ast.Node, bool) {+ return in, true+}++func getDatabaseCharset(optionList []*ast.DatabaseOption) string {+ for _, option := range optionList {+ if option.Tp == ast.DatabaseOptionCharset {+ return strings.ToLower(option.Value)+ }+ }++ return ""+}++func getTableCharset(optionList []*ast.TableOption) string {+ for _, option := range optionList {+ if option.Tp == ast.TableOptionCharset {+ if option.Default {+ return ""+ }+ return strings.ToLower(option.StrValue)+ }+ }++ return ""+}++func getColumnCharset(column *ast.ColumnDef) string {+ return column.Tp.Charset+}diff --git a/plugin/advisor/mysql/advisor_charset_allowlist_test.go b/plugin/advisor/mysql/advisor_charset_allowlist_test.gonew file mode 100644index 0000000000..47b69b3c7a--- /dev/null+++ b/plugin/advisor/mysql/advisor_charset_allowlist_test.go@@ -0,0 +1,145 @@+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 TestCharsetAllowlist(t *testing.T) {+ tests := []advisor.TestCase{+ {+ Statement: `CREATE TABLE t(a int) CHARSET utf8mb4`,+ 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) CHARSET ascii`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"CREATE TABLE t(a int) CHARSET ascii\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE t CHARSET ascii`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"ALTER TABLE t CHARSET ascii\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ {+ Statement: `CREATE DATABASE d CHARSET ascii`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"CREATE DATABASE d CHARSET ascii\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER DATABASE d CHARSET ascii`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"ALTER DATABASE d CHARSET ascii\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ {+ Statement: `CREATE TABLE t(a varchar(255) CHARSET ascii)`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"CREATE TABLE t(a varchar(255) CHARSET ascii)\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE t ADD COLUMN a varchar(255) CHARSET ascii`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"ALTER TABLE t ADD COLUMN a varchar(255) CHARSET ascii\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE t MODIFY COLUMN a varchar(255) CHARSET ascii`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"ALTER TABLE t MODIFY COLUMN a varchar(255) CHARSET ascii\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ {+ Statement: `ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARSET ascii`,+ Want: []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.DisabledCharset,+ Title: "charset.allowlist",+ Content: "\"ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARSET ascii\" used disabled charset 'ascii'",+ Line: 1,+ },+ },+ },+ }++ payload, err := json.Marshal(advisor.CharsetAllowlistRulePayload{+ CharsetAllowlist: []string{"utf8mb4"},+ })+ require.NoError(t, err)+ advisor.RunSQLReviewRuleTests(t, tests, &CharsetAllowlistAdvisor{}, &advisor.SQLReviewRule{+ Type: advisor.SchemaRuleCharsetAllowlist,+ Level: advisor.SchemaRuleLevelWarning,+ Payload: string(payload),+ }, advisor.MockMySQLDatabase)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 0ebba4eb3c..e97eebb451 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -102,6 +102,9 @@ const (// SchemaRuleIndexPKType enforce the type restriction of columns in primary key.SchemaRuleIndexPKType SQLReviewRuleType = "index.pk-type"+ // SchemaRuleCharsetAllowlist enforce the charset allowlist.+ SchemaRuleCharsetAllowlist SQLReviewRuleType = "charset.allowlist"+// TableNameTemplateToken is the token for table name.TableNameTemplateToken = "{{table}}"// ColumnListTemplateToken is the token for column name list.@@ -233,6 +236,11 @@ type TypeRestrictionRulePayload struct {TypeList []string `json:"typeList"`}+// CharsetAllowlistRulePayload is the payload for charset allowlist rule.+type CharsetAllowlistRulePayload struct {+ CharsetAllowlist []string `json:"charsetAllowlist"`+}+// UnamrshalNamingRulePayloadAsRegexp will unmarshal payload to NamingRulePayload and compile it as regular expression.func UnamrshalNamingRulePayloadAsRegexp(payload string) (*regexp.Regexp, int, error) {var nr NamingRulePayload@@ -341,6 +349,15 @@ 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)+ }+ return &cwr, nil+}+// SQLReviewCheckContext is the context for SQL review check.type SQLReviewCheckContext struct {Charset string@@ -576,6 +593,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errcase db.MySQL, db.TiDB:return MySQLTableDisallowCreateTableAs, nil}+ case SchemaRuleCharsetAllowlist:+ switch engine {+ case db.MySQL, db.TiDB:+ return MySQLCharsetAllowlist, nil+ }case SchemaRuleIndexPKType:switch engine {case db.MySQL, db.TiDB: