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: migrate collation_allowlist (#9292)
zll60071af49c81f51
diff --git a/backend/plugin/advisor/mysqlwip/advisor_collation_allowlist.go b/backend/plugin/advisor/mysqlwip/advisor_collation_allowlist.goindex 15ab8a8774..05feb1e396 100644--- a/backend/plugin/advisor/mysqlwip/advisor_collation_allowlist.go+++ b/backend/plugin/advisor/mysqlwip/advisor_collation_allowlist.go@@ -1,31 +1,36 @@package mysqlwip-// Framework code is generated by the generator.-import ("fmt""strings"- "github.com/pingcap/tidb/parser/ast"+ "github.com/antlr4-go/antlr/v4"+ mysql "github.com/bytebase/mysql-parser""github.com/pkg/errors""github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")var (_ advisor.Advisor = (*CollationAllowlistAdvisor)(nil)- _ ast.Visitor = (*collationAllowlistChecker)(nil))+func init() {+ // only for mysqlwip test.+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, 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, _ string) ([]advisor.Advice, error) {- stmtList, ok := ctx.AST.([]ast.StmtNode)+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)if !ok {- return nil, errors.Errorf("failed to convert to StmtNode")+ return nil, errors.Errorf("failed to convert to mysql parse result")}level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)@@ -39,16 +44,15 @@ func (*CollationAllowlistAdvisor) Check(ctx advisor.Context, _ string) ([]advisochecker := &collationAllowlistChecker{level: level,title: string(ctx.Rule.Type),- allowlist: make(map[string]bool),+ allowList: make(map[string]bool),}for _, collation := range payload.List {- checker.allowlist[strings.ToLower(collation)] = true+ checker.allowList[strings.ToLower(collation)] = true}for _, stmt := range stmtList {- checker.text = stmt.Text()- checker.line = stmt.OriginTextPosition()- (stmt).Accept(checker)+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)}if len(checker.adviceList) == 0 {@@ -63,117 +67,134 @@ func (*CollationAllowlistAdvisor) Check(ctx advisor.Context, _ string) ([]adviso}type collationAllowlistChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine intadviceList []advisor.Advicelevel advisor.Statustitle stringtext string- line int- allowlist map[string]bool+ 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- }- }+func (checker *collationAllowlistChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}++// EnterCreateDatabase is called when production createDatabase is entered.+func (checker *collationAllowlistChecker) EnterCreateDatabase(ctx *mysql.CreateDatabaseContext) {+ for _, option := range ctx.AllCreateDatabaseOption() {+ if option.DefaultCollation() != nil {+ collation := mysqlparser.NormalizeMySQLCollationName(option.DefaultCollation().CollationName())+ checker.checkCollation(collation, ctx.GetStart().GetLine())}}+}- if code != advisor.Ok {+func (checker *collationAllowlistChecker) checkCollation(collation string, lineNumber int) {+ collation = strings.ToLower(collation)+ if _, exists := checker.allowList[collation]; collation != "" && !exists {checker.adviceList = append(checker.adviceList, advisor.Advice{Status: checker.level,- Code: code,+ Code: advisor.DisabledCollation,Title: checker.title,- Content: fmt.Sprintf("\"%s\" used disabled collation '%s'", checker.text, disabledCollation),- Line: line,+ Content: fmt.Sprintf("\"%s\" used disabled collation '%s'", checker.text, collation),+ Line: checker.baseLine + lineNumber,})}-- return in, false}-// Leave implements the ast.Visitor interface.-func (*collationAllowlistChecker) Leave(in ast.Node) (ast.Node, bool) {- return in, true-}+// EnterCreateTable is called when production createTable is entered.+func (checker *collationAllowlistChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ if ctx.CreateTableOptions() != nil {+ for _, option := range ctx.CreateTableOptions().AllCreateTableOption() {+ if option.DefaultCollation() != nil {+ collation := mysqlparser.NormalizeMySQLCollationName(option.DefaultCollation().CollationName())+ collation = strings.ToLower(collation)+ checker.checkCollation(collation, option.GetStart().GetLine())+ }+ }+ }-func getDatabaseCollation(optionList []*ast.DatabaseOption) string {- for _, option := range optionList {- if option.Tp == ast.DatabaseOptionCollate {- return strings.ToLower(option.Value)+ if ctx.TableElementList() != nil {+ for _, tableElement := range ctx.TableElementList().AllTableElement() {+ if tableElement.ColumnDefinition() != nil {+ if tableElement.ColumnDefinition() == nil {+ continue+ }+ columnDef := tableElement.ColumnDefinition()+ if columnDef.FieldDefinition() == nil {+ continue+ }+ if columnDef.FieldDefinition().AllColumnAttribute() == nil {+ continue+ }+ for _, attr := range columnDef.FieldDefinition().AllColumnAttribute() {+ if attr.Collate() != nil {+ collation := mysqlparser.NormalizeMySQLCollationName(attr.Collate().CollationName())+ checker.checkCollation(collation, tableElement.GetStart().GetLine())+ }+ }+ }}}- return ""}-func getTableCollation(optionList []*ast.TableOption) string {- for _, option := range optionList {- if option.Tp == ast.TableOptionCollate {- return strings.ToLower(option.StrValue)+// EnterAlterDatabase is called when production alterDatabase is entered.+func (checker *collationAllowlistChecker) EnterAlterDatabase(ctx *mysql.AlterDatabaseContext) {+ for _, option := range ctx.AllAlterDatabaseOption() {+ if option.CreateDatabaseOption() == nil || option.CreateDatabaseOption().DefaultCollation() == nil {+ continue}+ charset := mysqlparser.NormalizeMySQLCollationName(option.CreateDatabaseOption().DefaultCollation().CollationName())+ checker.checkCollation(charset, ctx.GetStart().GetLine())}- return ""}-func getColumnCollation(column *ast.ColumnDef) string {- for _, option := range column.Options {- if option.Tp == ast.ColumnOptionCollate {- return strings.ToLower(option.StrValue)+// EnterAlterTable is called when production alterTable is entered.+func (checker *collationAllowlistChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {+ if ctx.AlterTableActions() == nil {+ return+ }+ if ctx.AlterTableActions().AlterCommandList() == nil {+ return+ }+ if ctx.AlterTableActions().AlterCommandList().AlterList() == nil {+ return+ }++ for _, item := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {+ if item.FieldDefinition() == nil {+ continue+ }+ if item.FieldDefinition().DataType() == nil {+ continue+ }+ if item.FieldDefinition().DataType().CharsetWithOptBinary() == nil {+ continue+ }+ for _, attr := range item.FieldDefinition().AllColumnAttribute() {+ if attr.Collate() == nil {+ continue+ }+ collation := mysqlparser.NormalizeMySQLCollationName(attr.Collate().CollationName())+ checker.checkCollation(collation, item.GetStart().GetLine())+ }+ }+ // alter table option+ for _, option := range ctx.AlterTableActions().AlterCommandList().AlterList().AllCreateTableOptionsSpaceSeparated() {+ if option == nil {+ continue+ }+ for _, tableOption := range option.AllCreateTableOption() {+ if tableOption == nil {+ continue+ }+ if tableOption.DefaultCollation() == nil {+ continue+ }+ collation := mysqlparser.NormalizeMySQLCollationName(tableOption.DefaultCollation().CollationName())+ checker.checkCollation(collation, tableOption.GetStart().GetLine())}}- return ""}diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.goindex 6122b7abc4..d406af7f09 100644--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go@@ -116,6 +116,9 @@ func TestMySQLWIPRules(t *testing.T) {// advisor.SchemaRuleCharsetAllowlist enforce the charset allowlist.advisor.SchemaRuleCharsetAllowlist,++ // advisor.SchemaRuleCollationAllowlist enforce the collation allowlist.+ advisor.SchemaRuleCollationAllowlist,}for _, rule := range mysqlwipRules {diff --git a/backend/plugin/advisor/mysqlwip/test/system_collation_allowlist.yaml b/backend/plugin/advisor/mysqlwip/test/system_collation_allowlist.yamlindex cdba824bb8..f38ef2b24f 100644--- a/backend/plugin/advisor/mysqlwip/test/system_collation_allowlist.yaml+++ b/backend/plugin/advisor/mysqlwip/test/system_collation_allowlist.yaml@@ -1,14 +1,13 @@-- statement: CREATE TABLE t(a int) COLLATE utf8mb4_polish_ci+- statement: CREATE TABLE t(a int) COLLATE utf8mb4_polish_ci;want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "CREATE TABLE t(a int) COLLATE utf8mb4_polish_ci- ;" used disabled collation 'utf8mb4_polish_ci'- line: 2+ "CREATE TABLE t(a int) COLLATE utf8mb4_polish_ci;" used disabled collation 'utf8mb4_polish_ci'+ line: 1details: ""-- statement: CREATE TABLE t(a varchar(255))+- statement: CREATE TABLE t(a varchar(255));want:- status: SUCCESScode: 0@@ -16,85 +15,74 @@content: ""line: 0details: ""-- statement: CREATE TABLE t(a int) COLLATE latin1_bin+- statement: CREATE TABLE t(a int) COLLATE latin1_bin;want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "CREATE TABLE t(a int) COLLATE latin1_bin- ;" used disabled collation 'latin1_bin'- line: 2+ "CREATE TABLE t(a int) COLLATE latin1_bin;" used disabled collation 'latin1_bin'+ line: 1details: ""- statement: |-CREATE TABLE t(a int);- ALTER TABLE t COLLATE latin1_bin+ ALTER TABLE t COLLATE latin1_bin;want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "- ALTER TABLE t COLLATE latin1_bin- ;" used disabled collation 'latin1_bin'- line: 3+ "ALTER TABLE t COLLATE latin1_bin;" used disabled collation 'latin1_bin'+ line: 2details: ""-- statement: ALTER DATABASE test COLLATE latin1_bin+- statement: ALTER DATABASE test COLLATE latin1_bin;want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "ALTER DATABASE test COLLATE latin1_bin- ;" used disabled collation 'latin1_bin'- line: 2+ "ALTER DATABASE test COLLATE latin1_bin;" used disabled collation 'latin1_bin'+ line: 1details: ""-- statement: CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin)+- statement: CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin);want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin)- ;" used disabled collation 'latin1_bin'+ "CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin);" used disabled collation 'latin1_bin'line: 1details: ""- statement: |-CREATE TABLE t(b int);- ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin+ ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin;want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "- ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin- ;" used disabled collation 'latin1_bin'- line: 3+ "ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin;" used disabled collation 'latin1_bin'+ line: 2details: ""- statement: |-CREATE TABLE t(a int);- ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin+ ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin;want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "- ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin- ;" used disabled collation 'latin1_bin'- line: 3+ "ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin;" used disabled collation 'latin1_bin'+ line: 2details: ""- statement: |-CREATE TABLE t(a int);- ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin+ ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin;want:- status: WARNcode: 1201title: system.collation.allowlistcontent: |-- "- ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin- ;" used disabled collation 'latin1_bin'- line: 3+ "ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin;" used disabled collation 'latin1_bin'+ line: 2details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 995998cf85..31a12dc17d 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1477,6 +1477,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty}case SchemaRuleCollationAllowlist:switch engine {+ // only for mysqlwip test.+ case storepb.Engine_ENGINE_UNSPECIFIED:+ return MySQLCollationAllowlist, nilcase storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:return MySQLCollationAllowlist, nilcase storepb.Engine_POSTGRES:diff --git a/backend/plugin/parser/mysql/normalize.go b/backend/plugin/parser/mysql/normalize.goindex d097538935..3504d3761a 100644--- a/backend/plugin/parser/mysql/normalize.go+++ b/backend/plugin/parser/mysql/normalize.go@@ -263,6 +263,19 @@ func NormalizeMySQLCharsetName(ctx parser.ICharsetNameContext) string {return ""}+// NormalizeMySQLCollationName noamalizes the given collation name.+func NormalizeMySQLCollationName(ctx parser.ICollationNameContext) string {+ switch {+ case ctx.TextOrIdentifier() != nil:+ return NormalizeMySQLTextOrIdentifier(ctx.TextOrIdentifier())+ case ctx.DEFAULT_SYMBOL() != nil:+ return "DEFAULT"+ case ctx.BINARY_SYMBOL() != nil:+ return "BINARY"+ }+ return ""+}+// NormalizeMySQLDataType noamalizes the given dataType.// campact for tidb parser compatibility.// eg: varchar(5).