Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: masking sensitive column supports complex queries (#3702)

rebeliced32aae42f97e
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 9377ae423a..c1d501c7fa 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -450,9 +450,10 @@ type ConnectionContext struct {
// QueryContext is the context to query.
type QueryContext struct {
// Limit is the maximum row count returned. No limit enforced if limit <= 0
- Limit int
- ReadOnly bool
- SensitiveDataMap SensitiveDataMap
+ Limit int
+ ReadOnly bool
+ SensitiveDataMaskType SensitiveDataMaskType
+ SensitiveSchemaInfo *SensitiveSchemaInfo
// CurrentDatabase is for MySQL
CurrentDatabase string
@@ -561,16 +562,6 @@ func FormatParamNameInNumberedPosition(paramNames []string) string {
return fmt.Sprintf("WHERE %s ", strings.Join(parts, " AND "))
}
-// SensitiveData is the struct for sensitive column.
-type SensitiveData struct {
- Database string
- Table string
- Column string
-}
-
-// SensitiveDataMap is the map for sensitive data.
-type SensitiveDataMap map[SensitiveData]SensitiveDataMaskType
-
// SensitiveDataMaskType is the mask type for sensitive data.
type SensitiveDataMaskType string
@@ -579,3 +570,32 @@ const (
// The default method is subject to change.
SensitiveDataMaskTypeDefault SensitiveDataMaskType = "DEFAULT"
)
+
+// SensitiveSchemaInfo is the schema info using to extract sensitive fields.
+type SensitiveSchemaInfo struct {
+ DatabaseList []DatabaseSchema
+}
+
+// DatabaseSchema is the database schema using to extract sensitive fields.
+type DatabaseSchema struct {
+ Name string
+ TableList []TableSchema
+}
+
+// TableSchema is the table schema using to extract sensitive fields.
+type TableSchema struct {
+ Name string
+ ColumnList []ColumnInfo
+}
+
+// ColumnInfo is the column info using to extract sensitive fields.
+type ColumnInfo struct {
+ Name string
+ Sensitive bool
+}
+
+// SensitiveField is the struct about SELECT fields.
+type SensitiveField struct {
+ Name string
+ Sensitive bool
+}
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index 0b85057242..8aa2e97915 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -16,9 +16,6 @@ import (
"github.com/pkg/errors"
"go.uber.org/zap"
- tidbparser "github.com/pingcap/tidb/parser"
- tidbast "github.com/pingcap/tidb/parser/ast"
-
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
@@ -361,11 +358,15 @@ func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string,
return nil, FormatError(err)
}
- fieldMap, err := extractSensitiveField(dbType, statement, queryContext.CurrentDatabase, columnNames, queryContext.SensitiveDataMap)
+ fieldList, err := extractSensitiveField(dbType, statement, queryContext.CurrentDatabase, queryContext.SensitiveSchemaInfo)
if err != nil {
return nil, err
}
+ if len(fieldList) != 0 && len(fieldList) != len(columnNames) {
+ return nil, errors.Errorf("failed to extract sensitive fields: %q", statement)
+ }
+
columnTypes, err := rows.ColumnTypes()
if err != nil {
return nil, FormatError(err)
@@ -405,7 +406,7 @@ func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string,
rowData := []interface{}{}
for i := range columnTypes {
- if sensitive, ok := fieldMap[i]; ok && sensitive {
+ if len(fieldList) > 0 && fieldList[i].Sensitive {
rowData = append(rowData, "******")
continue
}
@@ -687,138 +688,6 @@ func fromStoredVersion(storedVersion string) (bool, string, string, error) {
return true, fmt.Sprintf("%d.%d.%d", major, minor, patch), suffix, nil
}
-type sensitiveFiledMap map[int]bool
-
-func extractSensitiveField(dbType db.Type, statement string, currentDatabase string, fieldName []string, sensitiveDataMap db.SensitiveDataMap) (sensitiveFiledMap, error) {
- fieldMap := make(sensitiveFiledMap)
- switch dbType {
- case db.MySQL, db.TiDB:
- default:
- return fieldMap, nil
- }
-
- if sensitiveDataMap == nil {
- return fieldMap, nil
- }
- p := tidbparser.New()
-
- // To support MySQL8 window function syntax.
- // See https://github.com/bytebase/bytebase/issues/175.
- p.EnableWindowFunc(true)
- nodeList, _, err := p.Parse(statement, "", "")
- if err != nil {
- return nil, err
- }
- if len(nodeList) != 1 {
- return nil, errors.Errorf("expect one statement but found %d", len(nodeList))
- }
- node, ok := nodeList[0].(*tidbast.SelectStmt)
- if !ok {
- return fieldMap, nil
- }
-
- selectStmt, ok := extractMySQLOriginSelect(node)
- if !ok {
- return fieldMap, nil
- }
-
- databaseName, tableName, ok := extractMySQLSingleTable(selectStmt.From)
- if !ok {
- return fieldMap, nil
- }
- if databaseName == "" {
- databaseName = currentDatabase
- }
- starLength := extractMySQLStarLength(fieldName, selectStmt)
- fieldPosition := 0
- for _, field := range selectStmt.Fields.Fields {
- if field.WildCard != nil {
- for i := 0; i < starLength; i++ {
- position := fieldPosition + i
- column := db.SensitiveData{
- Database: databaseName,
- Table: tableName,
- Column: fieldName[position],
- }
- if _, ok := sensitiveDataMap[column]; ok {
- fieldMap[position] = true
- }
- }
- fieldPosition += starLength
- } else {
- if field.Expr != nil {
- columnName, ok := field.Expr.(*tidbast.ColumnNameExpr)
- if ok {
- column := db.SensitiveData{
- Database: databaseName,
- Table: tableName,
- Column: columnName.Name.Name.O,
- }
- if _, ok := sensitiveDataMap[column]; ok {
- fieldMap[fieldPosition] = true
- }
- }
- }
- fieldPosition++
- }
- }
- return fieldMap, nil
-}
-
-func extractMySQLOriginSelect(in *tidbast.SelectStmt) (*tidbast.SelectStmt, bool) {
- // For read only MySQL query, we will run as SELECT * FROM (sql) result LIMIT,
- // so we need to extract the origin SELECT statement.
- // details see getMySQLStatementWithResultLimit()
- if in == nil || in.From == nil || in.From.TableRefs == nil || in.From.TableRefs.Left == nil || in.From.TableRefs.Right != nil {
- return nil, false
- }
- tableSource, ok := in.From.TableRefs.Left.(*tidbast.TableSource)
- if !ok {
- return nil, false
- }
- selectStmt, ok := tableSource.Source.(*tidbast.SelectStmt)
- if !ok {
- return nil, false
- }
- return selectStmt, true
-}
-
-// extractMySQLStarLength works for single table in FROM clause.
-func extractMySQLStarLength(fieldName []string, selectStmt *tidbast.SelectStmt) int {
- starFieldCount := 0
- for _, field := range selectStmt.Fields.Fields {
- if field.WildCard != nil {
- starFieldCount++
- }
- }
- if starFieldCount == 0 {
- return 0
- }
- nonStarFieldCount := len(selectStmt.Fields.Fields) - starFieldCount
- return (len(fieldName) - nonStarFieldCount) / starFieldCount
-}
-
-func extractMySQLSingleTable(fromClause *tidbast.TableRefsClause) (string, string, bool) {
- if fromClause == nil || fromClause.TableRefs == nil {
- return "", "", false
- }
- if fromClause.TableRefs.Right != nil {
- return "", "", false
- }
- if fromClause.TableRefs.Left == nil {
- return "", "", false
- }
- tableSource, ok := fromClause.TableRefs.Left.(*tidbast.TableSource)
- if !ok {
- return "", "", false
- }
- tableName, ok := tableSource.Source.(*tidbast.TableName)
- if !ok {
- return "", "", false
- }
- return tableName.Schema.O, tableName.Name.O, true
-}
-
// IsAffectedRowsStatement returns true if the statement will return the number of affected rows.
func IsAffectedRowsStatement(stmt string) bool {
affectedRowsStatementPrefix := []string{"INSERT ", "UPDATE ", "DELETE "}
diff --git a/plugin/db/util/driverutil_test.go b/plugin/db/util/driverutil_test.go
index 1cfe2c3071..4332cb5b98 100644
--- a/plugin/db/util/driverutil_test.go
+++ b/plugin/db/util/driverutil_test.go
@@ -238,66 +238,265 @@ func generateOneMBInsert() string {
}
func TestExtractSensitiveField(t *testing.T) {
+ const (
+ defaultDatabase = "db"
+ )
+ var (
+ defaultDatabaseSchema = &db.SensitiveSchemaInfo{
+ DatabaseList: []db.DatabaseSchema{
+ {
+ Name: defaultDatabase,
+ TableList: []db.TableSchema{
+ {
+ Name: "t",
+ ColumnList: []db.ColumnInfo{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+ )
tests := []struct {
- statement string
- fieldName []string
- sensitiveDataMap db.SensitiveDataMap
- fieldMap sensitiveFiledMap
+ statement string
+ schemaInfo *db.SensitiveSchemaInfo
+ fieldList []db.SensitiveField
}{
{
- statement: "select * from (select * from t) result LIMIT 100000;",
- fieldName: []string{"a", "b", "c", "d"},
- sensitiveDataMap: db.SensitiveDataMap{
- db.SensitiveData{
- Database: "db",
- Table: "t",
- Column: "a",
- }: db.SensitiveDataMaskTypeDefault,
- db.SensitiveData{
- Database: "db",
- Table: "t",
- Column: "d",
- }: db.SensitiveDataMaskTypeDefault,
+ // Test for UNION.
+ statement: `select * from t UNION ALL select * from t`,
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
+ },
+ },
+ {
+ // Test for JOIN with ON clause.
+ statement: `select * from t as t1 join t as t2 on t1.a = t2.a`,
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
+ },
+ },
+ {
+ // Test for natural JOIN.
+ statement: `select * from t as t1 natural join t as t2`,
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
+ },
+ },
+ {
+ // Test for JOIN with USING clause.
+ statement: `select * from t as t1 join t as t2 using(a)`,
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
},
- fieldMap: sensitiveFiledMap{
- 0: true,
- 3: true,
+ },
+ {
+ // Test for functions.
+ statement: `select max(a), a-b, a=b, a>b, b in (a, c, d) from (select * from t) result`,
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "max(a)",
+ Sensitive: true,
+ },
+ {
+ Name: "a-b",
+ Sensitive: true,
+ },
+ {
+ Name: "a=b",
+ Sensitive: true,
+ },
+ {
+ Name: "a>b",
+ Sensitive: true,
+ },
+ {
+ Name: "b in (a, c, d)",
+ Sensitive: true,
+ },
},
},
{
- statement: "select * from (select *, a, t.*, b from db.t) result LIMIT 100000;",
- fieldName: []string{"a", "b", "c", "a", "a", "b", "c", "b"},
- sensitiveDataMap: db.SensitiveDataMap{
- db.SensitiveData{
- Database: "db",
- Table: "t",
- Column: "a",
- }: db.SensitiveDataMaskTypeDefault,
- db.SensitiveData{
- Database: "db",
- Table: "t",
- Column: "c",
- }: db.SensitiveDataMaskTypeDefault,
+ // Test for non-associated sub-query
+ statement: "select t.a, (select max(a) from t) from t as t1 join t on t.a = t1.b",
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "(select max(a) from t)",
+ Sensitive: true,
+ },
},
- fieldMap: sensitiveFiledMap{
- 0: true,
- 2: true,
- 3: true,
- 4: true,
- 6: true,
+ },
+ {
+ // Test for sub-query
+ statement: "select * from (select * from t) result LIMIT 100000;",
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d",
+ Sensitive: true,
+ },
+ },
+ },
+ {
+ // Test for field name.
+ statement: "select * from (select a, t.b, db.t.c, d as d1 from db.t) result LIMIT 100000;",
+ schemaInfo: defaultDatabaseSchema,
+ fieldList: []db.SensitiveField{
+ {
+ Name: "a",
+ Sensitive: true,
+ },
+ {
+ Name: "b",
+ Sensitive: false,
+ },
+ {
+ Name: "c",
+ Sensitive: false,
+ },
+ {
+ Name: "d1",
+ Sensitive: true,
+ },
},
},
{
- statement: "select 1;",
- fieldName: []string{"1"},
- sensitiveDataMap: db.SensitiveDataMap{},
- fieldMap: sensitiveFiledMap{},
+ // Test for no FROM clause.
+ statement: "select 1;",
+ schemaInfo: &db.SensitiveSchemaInfo{},
+ fieldList: []db.SensitiveField{{Name: "1", Sensitive: false}},
},
}
for _, test := range tests {
- res, err := extractSensitiveField(db.MySQL, test.statement, "db", test.fieldName, test.sensitiveDataMap)
+ res, err := extractSensitiveField(db.MySQL, test.statement, defaultDatabase, test.schemaInfo)
require.NoError(t, err)
- require.Equal(t, test.fieldMap, res)
+ require.Equal(t, test.fieldList, res, test.statement)
}
}
diff --git a/plugin/db/util/mask_sensitive_data.go b/plugin/db/util/mask_sensitive_data.go
new file mode 100644
index 0000000000..d029701689
--- /dev/null
+++ b/plugin/db/util/mask_sensitive_data.go
@@ -0,0 +1,427 @@
+package util
+
+import (
+ "github.com/bytebase/bytebase/plugin/db"
+
+ "github.com/pkg/errors"
+
+ tidbparser "github.com/pingcap/tidb/parser"
+ tidbast "github.com/pingcap/tidb/parser/ast"
+)
+
+type sensitiveFieldExtractor struct {
+ currentDatabase string
+ schemaInfo *db.SensitiveSchemaInfo
+
+ // SELECT statement specific field.
+ fromFieldList []fieldInfo
+}
+
+func extractSensitiveField(dbType db.Type, statement string, currentDatabase string, schemaInfo *db.SensitiveSchemaInfo) ([]db.SensitiveField, error) {
+ if schemaInfo == nil {
+ return nil, nil
+ }
+
+ switch dbType {
+ case db.MySQL, db.TiDB:
+ extractor := &sensitiveFieldExtractor{
+ currentDatabase: currentDatabase,
+ schemaInfo: schemaInfo,
+ }
+ return extractor.extractMySQLSensitiveField(statement)
+ default:
+ return nil, nil
+ }
+}
+
+func (extractor *sensitiveFieldExtractor) extractMySQLSensitiveField(statement string) ([]db.SensitiveField, error) {
+ p := tidbparser.New()
+
+ // To support MySQL8 window function syntax.
+ // See https://github.com/bytebase/bytebase/issues/175.
+ p.EnableWindowFunc(true)
+ nodeList, _, err := p.Parse(statement, "", "")
+ if err != nil {
+ return nil, err
+ }
+ if len(nodeList) != 1 {
+ return nil, errors.Errorf("expect one statement but found %d", len(nodeList))
+ }
+ node := nodeList[0]
+
+ switch node.(type) {
+ case *tidbast.SelectStmt:
+ case *tidbast.SetOprStmt:
+ default:
+ return nil, errors.Errorf("expect a query statement but found %T", node)
+ }
+
+ fieldList, err := extractor.extractNode(node)
+ if err != nil {
+ return nil, err
+ }
+ result := []db.SensitiveField{}
+ for _, field := range fieldList {
+ result = append(result, db.SensitiveField{
+ Name: field.name,
+ Sensitive: field.sensitive,
+ })
+ }
+ return result, nil
+}
+
+type fieldInfo struct {
+ name string
+ table string
+ database string
+ sensitive bool
+}
+
+// TODO(rebelice): support Common Table Expression later.
+func (extractor *sensitiveFieldExtractor) extractNode(in tidbast.Node) ([]fieldInfo, error) {
+ if in == nil {
+ return nil, nil
+ }
+
+ switch node := in.(type) {
+ case *tidbast.SelectStmt:
+ return extractor.extractSelect(node)
+ case *tidbast.Join:
+ return extractor.extractJoin(node)
+ case *tidbast.TableSource:
+ return extractor.extractTableSource(node)
+ case *tidbast.TableName:
+ return extractor.extractTableName(node)
+ case *tidbast.SetOprStmt:
+ return extractor.extractSetOpr(node)
+ }
+ return nil, nil
+}
+
+func (extractor *sensitiveFieldExtractor) extractSetOpr(node *tidbast.SetOprStmt) ([]fieldInfo, error) {
+ result := []fieldInfo{}
+ for i, selectStmt := range node.SelectList.Selects {
+ fieldList, err := extractor.extractNode(selectStmt)
+ if err != nil {
+ return nil, err
+ }
+ if i == 0 {
+ result = fieldList
+ } else {
+ if len(result) != len(fieldList) {
+ // The error content comes from MySQL.
+ return nil, errors.Errorf("The used SELECT statements have a different number of columns")
+ }
+ for index := 0; index < len(result); index++ {
+ if fieldList[index].sensitive {
+ result[index].sensitive = true
+ }
+ }
+ }
+ }
+ return result, nil
+}
+
+func (extractor *sensitiveFieldExtractor) extractSelect(node *tidbast.SelectStmt) ([]fieldInfo, error) {
+ var fromFieldList []fieldInfo
+ var err error
+ if node.From != nil {
+ fromFieldList, err = extractor.extractNode(node.From.TableRefs)
+ if err != nil {
+ return nil, err
+ }
+ extractor.fromFieldList = fromFieldList
+ defer func() {
+ extractor.fromFieldList = nil
+ }()
+ }
+
+ var result []fieldInfo
+
+ if node.Fields != nil {
+ for _, field := range node.Fields.Fields {
+ if field.WildCard != nil {
+ if field.WildCard.Table.O == "" {
+ result = append(result, fromFieldList...)
+ } else {
+ for _, fromField := range fromFieldList {
+ sameDatabase := (field.WildCard.Schema.O == fromField.database || (field.WildCard.Schema.O == "" && fromField.database == extractor.currentDatabase))
+ sameTable := (field.WildCard.Table.O == fromField.table)
+ if sameDatabase && sameTable {
+ result = append(result, fromField)
+ }
+ }
+ }
+ } else {
+ sensitive, err := extractor.extractColumnFromExprNode(field.Expr)
+ if err != nil {
+ return nil, err
+ }
+ fieldName := extractFieldName(field)
+ result = append(result, fieldInfo{
+ database: "",
+ table: "",
+ name: fieldName,
+ sensitive: sensitive,
+ })
+ }
+ }
+ }
+
+ return result, nil
+}
+
+func extractFieldName(in *tidbast.SelectField) string {
+ if in.AsName.O != "" {
+ return in.AsName.O
+ }
+
+ if in.Expr != nil {
+ if columnName, ok := in.Expr.(*tidbast.ColumnNameExpr); ok {
+ return columnName.Name.Name.O
+ }
+ return in.Text()
+ }
+ return ""
+}
+
+func (extractor *sensitiveFieldExtractor) extractColumnFromExprNode(in tidbast.ExprNode) (sensitive bool, err error) {
+ if in == nil {
+ return false, nil
+ }
+
+ switch node := in.(type) {
+ case *tidbast.ColumnNameExpr:
+ for _, field := range extractor.fromFieldList {
+ sameDatabase := (node.Name.Schema.O == field.database || (node.Name.Schema.O == "" && field.database == extractor.currentDatabase))
+ sameTable := (node.Name.Table.O == field.table || node.Name.Table.O == "")
+ sameColumn := (node.Name.Name.O == field.name)
+ if sameDatabase && sameTable && sameColumn {
+ return field.sensitive, nil
+ }
+ }
+ return false, nil
+ case *tidbast.BinaryOperationExpr:
+ return extractor.extractColumnFromExprNodeList([]tidbast.ExprNode{node.L, node.R})
+ case *tidbast.UnaryOperationExpr:
+ return extractor.extractColumnFromExprNode(node.V)
+ case *tidbast.FuncCallExpr:
+ return extractor.extractColumnFromExprNodeList(node.Args)
+ case *tidbast.FuncCastExpr:
+ return extractor.extractColumnFromExprNode(node.Expr)
+ case *tidbast.AggregateFuncExpr:
+ return extractor.extractColumnFromExprNodeList(node.Args)
+ case *tidbast.PatternInExpr:
+ nodeList := []tidbast.ExprNode{}
+ nodeList = append(nodeList, node.Expr)
+ nodeList = append(nodeList, node.List...)
+ nodeList = append(nodeList, node.Sel)
+ return extractor.extractColumnFromExprNodeList(nodeList)
+ case *tidbast.PatternLikeExpr:
+ return extractor.extractColumnFromExprNodeList([]tidbast.ExprNode{node.Expr, node.Pattern})
+ case *tidbast.PatternRegexpExpr:
+ return extractor.extractColumnFromExprNodeList([]tidbast.ExprNode{node.Expr, node.Pattern})
+ case *tidbast.SubqueryExpr:
+ // Subquery in SELECT fields is special.
+ // It can only be the non-associated subquery.
+ // We can extract this subquery as the alone node.
+ // The reason for new extractor is that non-associated subquery cannot access the fromFieldList.
+ // Also, we still need the current fromFieldList, overriding it is not expected.
+ subqueryExtractor := &sensitiveFieldExtractor{
+ currentDatabase: extractor.currentDatabase,
+ schemaInfo: extractor.schemaInfo,
+ }
+ fieldList, err := subqueryExtractor.extractNode(node.Query)
+ if err != nil {
+ return false, err
+ }
+ for _, field := range fieldList {
+ if field.sensitive {
+ return true, nil
+ }
+ }
+ return false, nil
+ case *tidbast.CompareSubqueryExpr:
+ return extractor.extractColumnFromExprNodeList([]tidbast.ExprNode{node.L, node.R})
+ case *tidbast.ExistsSubqueryExpr:
+ return extractor.extractColumnFromExprNode(node.Sel)
+ case *tidbast.IsNullExpr:
+ return extractor.extractColumnFromExprNode(node.Expr)
+ case *tidbast.IsTruthExpr:
+ return extractor.extractColumnFromExprNode(node.Expr)
+ case *tidbast.BetweenExpr:
+ return extractor.extractColumnFromExprNodeList([]tidbast.ExprNode{node.Expr, node.Left, node.Right})
+ case *tidbast.CaseExpr:
+ nodeList := []tidbast.ExprNode{}
+ nodeList = append(nodeList, node.Value)
+ nodeList = append(nodeList, node.ElseClause)
+ for _, whenClause := range node.WhenClauses {
+ nodeList = append(nodeList, whenClause.Expr)
+ nodeList = append(nodeList, whenClause.Result)
+ }
+ return extractor.extractColumnFromExprNodeList(nodeList)
+ case *tidbast.ParenthesesExpr:
+ return extractor.extractColumnFromExprNode(node.Expr)
+ case *tidbast.RowExpr:
+ return extractor.extractColumnFromExprNodeList(node.Values)
+ case *tidbast.VariableExpr:
+ return extractor.extractColumnFromExprNode(node.Value)
+ case *tidbast.PositionExpr:
+ return extractor.extractColumnFromExprNode(node.P)
+ case *tidbast.MatchAgainst:
+ return extractor.extractColumnFromExprNode(node.Against)
+ case *tidbast.WindowFuncExpr:
+ return extractor.extractColumnFromExprNodeList(node.Args)
+ case *tidbast.ValuesExpr,
+ *tidbast.TableNameExpr,
+ *tidbast.MaxValueExpr,
+ *tidbast.SetCollationExpr,
+ *tidbast.TrimDirectionExpr,
+ *tidbast.TimeUnitExpr,
+ *tidbast.GetFormatSelectorExpr,
+ *tidbast.DefaultExpr:
+ // No expression need to extract.
+ }
+ return false, nil
+}
+
+func (extractor *sensitiveFieldExtractor) extractColumnFromExprNodeList(nodeList []tidbast.ExprNode) (sensitive bool, err error) {
+ for _, node := range nodeList {
+ nodeSensitive, err := extractor.extractColumnFromExprNode(node)
+ if err != nil {
+ return false, err
+ }
+ if nodeSensitive {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+func (extractor *sensitiveFieldExtractor) extractTableSource(node *tidbast.TableSource) ([]fieldInfo, error) {
+ fieldList, err := extractor.extractNode(node.Source)
+ if err != nil {
+ return nil, err
+ }
+ var res []fieldInfo
+ if node.AsName.O != "" {
+ for _, field := range fieldList {
+ res = append(res, fieldInfo{
+ name: field.name,
+ table: node.AsName.O,
+ database: field.database,
+ sensitive: field.sensitive,
+ })
+ }
+ } else {
+ res = fieldList
+ }
+ return res, nil
+}
+
+func (extractor *sensitiveFieldExtractor) findTableSchema(databaseName string, tableName string) (db.TableSchema, bool) {
+ for _, database := range extractor.schemaInfo.DatabaseList {
+ if databaseName == database.Name || (databaseName == "" && extractor.currentDatabase == database.Name) {
+ for _, table := range database.TableList {
+ if tableName == table.Name {
+ return table, true
+ }
+ }
+ }
+ }
+ return db.TableSchema{}, false
+}
+
+func (extractor *sensitiveFieldExtractor) extractTableName(node *tidbast.TableName) ([]fieldInfo, error) {
+ tableSchema, exists := extractor.findTableSchema(node.Schema.O, node.Name.O)
+ if !exists {
+ return nil, errors.Errorf("Table %q.%q not found", node.Schema.O, node.Name.O)
+ }
+
+ var res []fieldInfo
+ for _, column := range tableSchema.ColumnList {
+ res = append(res, fieldInfo{
+ name: column.Name,
+ table: tableSchema.Name,
+ database: node.Schema.O,
+ sensitive: column.Sensitive,
+ })
+ }
+ return res, nil
+}
+
+func (extractor *sensitiveFieldExtractor) extractJoin(node *tidbast.Join) ([]fieldInfo, error) {
+ if node.Right == nil {
+ // This case is not Join
+ return extractor.extractNode(node.Left)
+ }
+ leftFieldInfo, err := extractor.extractNode(node.Left)
+ if err != nil {
+ return nil, err
+ }
+ rightFieldInfo, err := extractor.extractNode(node.Right)
+ if err != nil {
+ return nil, err
+ }
+ return mergeJoinField(node, leftFieldInfo, rightFieldInfo)
+}
+
+func mergeJoinField(node *tidbast.Join, leftField []fieldInfo, rightField []fieldInfo) ([]fieldInfo, error) {
+ leftFieldMap := make(map[string]fieldInfo)
+ rightFieldMap := make(map[string]fieldInfo)
+ var result []fieldInfo
+ for _, field := range leftField {
+ leftFieldMap[field.name] = field
+ }
+ for _, field := range rightField {
+ rightFieldMap[field.name] = field
+ }
+ if node.NaturalJoin {
+ // Natural Join will merge the same column name field.
+ for _, field := range leftField {
+ // Merge the sensitive attribute for the same column name field.
+ if rField, exists := rightFieldMap[field.name]; exists && rField.sensitive {
+ field.sensitive = true
+ }
+ result = append(result, field)
+ }
+
+ for _, field := range rightField {
+ if _, exists := leftFieldMap[field.name]; !exists {
+ result = append(result, field)
+ }
+ }
+ } else {
+ if len(node.Using) != 0 {
+ // ... JOIN ... USING (...) will merge the column in USING.
+ usingMap := make(map[string]bool)
+ for _, column := range node.Using {
+ usingMap[column.Name.O] = true
+ }
+
+ for _, field := range leftField {
+ _, existsInUsingMap := usingMap[field.name]
+ rField, existsInRightField := rightFieldMap[field.name]
+ // Merge the sensitive attribute for the column name field in USING.
+ if existsInUsingMap && existsInRightField && rField.sensitive {
+ field.sensitive = true
+ }
+ result = append(result, field)
+ }
+
+ for _, field := range rightField {
+ _, existsInUsingMap := usingMap[field.name]
+ _, existsInLeftField := leftFieldMap[field.name]
+ if existsInUsingMap && existsInLeftField {
+ continue
+ }
+ result = append(result, field)
+ }
+ } else {
+ result = append(result, leftField...)
+ result = append(result, rightField...)
+ }
+ }
+
+ return result, nil
+}
diff --git a/server/sql.go b/server/sql.go
index 874a434183..fe930c9d3f 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -308,14 +308,14 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
}
}
- var sensitiveDataMap db.SensitiveDataMap
+ var sensitiveSchemaInfo *db.SensitiveSchemaInfo
if instance.Engine == db.MySQL || instance.Engine == db.TiDB {
databaseList, err := parser.ExtractDatabaseList(parser.MySQL, exec.Statement)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get database list: %s", exec.Statement)).SetInternal(err)
}
- sensitiveDataMap, err = s.getSensitiveData(ctx, instance.Engine, instance.ID, databaseList, exec.DatabaseName)
+ sensitiveSchemaInfo, err = s.getSensitiveSchemaInfo(ctx, instance.Engine, instance.ID, databaseList, exec.DatabaseName)
if err != nil {
return err
}
@@ -331,10 +331,12 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
defer driver.Close(ctx)
rowSet, err := driver.Query(ctx, exec.Statement, &db.QueryContext{
- Limit: exec.Limit,
- ReadOnly: true,
- CurrentDatabase: exec.DatabaseName,
- SensitiveDataMap: sensitiveDataMap,
+ Limit: exec.Limit,
+ ReadOnly: true,
+ CurrentDatabase: exec.DatabaseName,
+ // TODO(rebelice): we cannot deal with multi-SensitiveDataMaskType now. Fix it.
+ SensitiveDataMaskType: db.SensitiveDataMaskTypeDefault,
+ SensitiveSchemaInfo: sensitiveSchemaInfo,
})
if err != nil {
return nil, err
@@ -480,10 +482,10 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
defer driver.Close(ctx)
rowSet, err := driver.Query(ctx, exec.Statement, &db.QueryContext{
- Limit: exec.Limit,
- ReadOnly: false,
- CurrentDatabase: exec.DatabaseName,
- SensitiveDataMap: nil,
+ Limit: exec.Limit,
+ ReadOnly: false,
+ CurrentDatabase: exec.DatabaseName,
+ SensitiveSchemaInfo: nil,
})
if err != nil {
return nil, err
@@ -715,8 +717,12 @@ func (s *Server) getDatabase(ctx context.Context, instanceID int, databaseName s
return dbList[0], nil
}
-func (s *Server) getSensitiveData(ctx context.Context, engineType db.Type, instanceID int, databaseList []string, currentDatabase string) (db.SensitiveDataMap, error) {
- res := make(db.SensitiveDataMap)
+func (s *Server) getSensitiveSchemaInfo(ctx context.Context, engineType db.Type, instanceID int, databaseList []string, currentDatabase string) (*db.SensitiveSchemaInfo, error) {
+ type sensitiveDataMap map[api.SensitiveData]api.SensitiveDataMaskType
+ isEmpty := true
+ result := &db.SensitiveSchemaInfo{
+ DatabaseList: []db.DatabaseSchema{},
+ }
for _, name := range databaseList {
databaseName := name
if name == "" {
@@ -735,20 +741,67 @@ func (s *Server) getSensitiveData(ctx context.Context, engineType db.Type, insta
return nil, err
}
+ columnMap := make(sensitiveDataMap)
+
policy, err := s.store.GetSensitiveDataPolicy(ctx, database.ID)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find sensitive data policy for database `%s` in instance ID: %d", databaseName, instanceID))
}
for _, data := range policy.SensitiveDataList {
- res[db.SensitiveData{
- Database: databaseName,
- Table: data.Table,
- Column: data.Column,
- }] = db.SensitiveDataMaskType(data.Type)
+ columnMap[api.SensitiveData{
+ Table: data.Table,
+ Column: data.Column,
+ }] = data.Type
+ }
+
+ tableList, err := s.store.FindTable(ctx, &api.TableFind{
+ DatabaseID: &database.ID,
+ })
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find table list for database %q", databaseName))
+ }
+
+ databaseSchema := db.DatabaseSchema{
+ Name: databaseName,
+ TableList: []db.TableSchema{},
+ }
+ for _, table := range tableList {
+ tableSchema := db.TableSchema{
+ Name: table.Name,
+ ColumnList: []db.ColumnInfo{},
+ }
+ columnList, err := s.store.FindColumn(ctx, &api.ColumnFind{
+ DatabaseID: &database.ID,
+ TableID: &table.ID,
+ })
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find column list for table %q.%q", databaseName, table.Name))
+ }
+
+ for _, column := range columnList {
+ _, sensitive := columnMap[api.SensitiveData{
+ Table: table.Name,
+ Column: column.Name,
+ }]
+ tableSchema.ColumnList = append(tableSchema.ColumnList, db.ColumnInfo{
+ Name: column.Name,
+ Sensitive: sensitive,
+ })
+ }
+ databaseSchema.TableList = append(databaseSchema.TableList, tableSchema)
}
+ if len(databaseSchema.TableList) > 0 {
+ isEmpty = false
+ }
+ result.DatabaseList = append(result.DatabaseList, databaseSchema)
}
- return res, nil
+ if isEmpty {
+ // If there is no tables, this query may access system databases, such as INFORMATION_SCHEMA.
+ // Skip to extract sensitive column for this query.
+ result = nil
+ }
+ return result, nil
}
func isExcludeDatabase(dbType db.Type, database string) bool {