Skip to content

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

feat: mask sensitive column for MySQL (#3483)

rebelice1ff023ab8d5f
diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.go
index 4487188991..e6939c8b3a 100644
--- a/plugin/advisor/utils_for_tests.go
+++ b/plugin/advisor/utils_for_tests.go
@@ -192,7 +192,7 @@ func (*MockDriver) Execute(_ context.Context, _ string, _ bool) error {
}
// Query implements the Driver interface.
-func (*MockDriver) Query(_ context.Context, statement string, _ int, _ bool) ([]interface{}, error) {
+func (*MockDriver) Query(_ context.Context, statement string, _ int, _ bool, _ database.SensitiveDataMap) ([]interface{}, error) {
switch statement {
// For TestStatementDMLDryRun
case "EXPLAIN DELETE FROM tech_book":
diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.go
index 5508a12763..212b11266d 100644
--- a/plugin/db/clickhouse/clickhouse.go
+++ b/plugin/db/clickhouse/clickhouse.go
@@ -141,6 +141,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) err
}
// Query queries a SQL statement.
-func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool) ([]interface{}, error) {
- return util.Query(ctx, driver.dbType, driver.db, statement, limit, readOnly)
+func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool, sensitiveDataMap db.SensitiveDataMap) ([]interface{}, error) {
+ return util.Query(ctx, driver.dbType, driver.db, statement, limit, readOnly, sensitiveDataMap)
}
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 653442f00c..6c81acf8a0 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -460,7 +460,7 @@ type Driver interface {
Execute(ctx context.Context, statement string, createDatabase bool) error
// Used for execute readonly SELECT statement
// limit is the maximum row count returned. No limit enforced if limit <= 0
- Query(ctx context.Context, statement string, limit int, readOnly bool) ([]interface{}, error)
+ Query(ctx context.Context, statement string, limit int, readOnly bool, sensitiveDataMap SensitiveDataMap) ([]interface{}, error)
// Sync schema
// SyncInstance syncs the instance metadata.
@@ -549,8 +549,21 @@ func FormatParamNameInNumberedPosition(paramNames []string) string {
return fmt.Sprintf("WHERE %s ", strings.Join(parts, " AND "))
}
-// SensitiveColumnList is the list for sensitive columns.
-type SensitiveColumnList []string
+// 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
-// SensitiveSchema is the set of the sensitive columns group by table names.
-type SensitiveSchema map[string]SensitiveColumnList
+const (
+ // SensitiveDataMaskTypeDefault is the sensitive data type to hide data with a default method.
+ // The default method is subject to change.
+ SensitiveDataMaskTypeDefault SensitiveDataMaskType = "DEFAULT"
+)
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.go
index 6069eb307b..ad86ff94f8 100644
--- a/plugin/db/mysql/mysql.go
+++ b/plugin/db/mysql/mysql.go
@@ -196,8 +196,8 @@ func (driver *Driver) GetMigrationConnID(ctx context.Context) (string, error) {
}
// Query queries a SQL statement.
-func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool) ([]interface{}, error) {
- return util.Query(ctx, driver.dbType, driver.db, statement, limit, readOnly)
+func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool, sensitiveDataMap db.SensitiveDataMap) ([]interface{}, error) {
+ return util.Query(ctx, driver.dbType, driver.db, statement, limit, readOnly, sensitiveDataMap)
}
// transformDelimiter transform the delimiter to the MySQL default delimiter.
diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.go
index d66bfd5ccc..f7772cc44e 100644
--- a/plugin/db/pg/pg.go
+++ b/plugin/db/pg/pg.go
@@ -375,8 +375,8 @@ func (driver *Driver) GetCurrentDatabaseOwner() (string, error) {
}
// Query queries a SQL statement.
-func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool) ([]interface{}, error) {
- return util.Query(ctx, db.Postgres, driver.db, statement, limit, readOnly)
+func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool, sensitiveDataMap db.SensitiveDataMap) ([]interface{}, error) {
+ return util.Query(ctx, db.Postgres, driver.db, statement, limit, readOnly, sensitiveDataMap)
}
func (driver *Driver) switchDatabase(dbName string) error {
diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.go
index 44fd0989ad..6c1e9cc7ca 100644
--- a/plugin/db/snowflake/snowflake.go
+++ b/plugin/db/snowflake/snowflake.go
@@ -256,6 +256,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) err
}
// Query queries a SQL statement.
-func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool) ([]interface{}, error) {
- return util.Query(ctx, db.Snowflake, driver.db, statement, limit, readOnly)
+func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool, sensitiveDataMap db.SensitiveDataMap) ([]interface{}, error) {
+ return util.Query(ctx, db.Snowflake, driver.db, statement, limit, readOnly, sensitiveDataMap)
}
diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.go
index 69c7785e1f..b4ce7e5f4e 100644
--- a/plugin/db/sqlite/sqlite.go
+++ b/plugin/db/sqlite/sqlite.go
@@ -171,6 +171,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) err
}
// Query queries a SQL statement.
-func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool) ([]interface{}, error) {
- return util.Query(ctx, db.SQLite, driver.db, statement, limit, readOnly)
+func (driver *Driver) Query(ctx context.Context, statement string, limit int, readOnly bool, sensitiveDataMap db.SensitiveDataMap) ([]interface{}, error) {
+ return util.Query(ctx, db.SQLite, driver.db, statement, limit, readOnly, sensitiveDataMap)
}
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index bd88ea4b09..f7280129bc 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -16,6 +16,9 @@ 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"
@@ -321,7 +324,7 @@ func EndMigration(ctx context.Context, executor MigrationExecutor, startedNs int
}
// Query will execute a readonly / SELECT query.
-func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string, limit int, readOnly bool) ([]interface{}, error) {
+func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string, limit int, readOnly bool, sensitiveDataMap db.SensitiveDataMap) ([]interface{}, error) {
if !readOnly {
return queryAdmin(ctx, sqldb, statement, limit)
}
@@ -356,6 +359,11 @@ func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string,
return nil, FormatError(err)
}
+ fieldMap, err := extractSensitiveField(dbType, statement, columnNames, sensitiveDataMap)
+ if err != nil {
+ return nil, err
+ }
+
columnTypes, err := rows.ColumnTypes()
if err != nil {
return nil, FormatError(err)
@@ -395,6 +403,10 @@ 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 {
+ rowData = append(rowData, "******")
+ continue
+ }
if v, ok := (scanArgs[i]).(*sql.NullBool); ok && v.Valid {
rowData = append(rowData, v.Bool)
continue
@@ -672,3 +684,126 @@ 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, 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
+ }
+ 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.TableRefs.Right != 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
+}
diff --git a/plugin/db/util/driverutil_test.go b/plugin/db/util/driverutil_test.go
index 444a1be685..c76ace59a0 100644
--- a/plugin/db/util/driverutil_test.go
+++ b/plugin/db/util/driverutil_test.go
@@ -8,6 +8,10 @@ import (
"time"
"github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/plugin/db"
+ // Register pingcap parser driver.
+ _ "github.com/pingcap/tidb/types/parser_driver"
)
func TestToStoredVersion(t *testing.T) {
@@ -232,3 +236,62 @@ func generateOneMBInsert() string {
}
return fmt.Sprintf("INSERT INTO t values('%s')", string(b))
}
+
+func TestExtractSensitiveField(t *testing.T) {
+ tests := []struct {
+ statement string
+ fieldName []string
+ sensitiveDataMap db.SensitiveDataMap
+ fieldMap sensitiveFiledMap
+ }{
+ {
+ statement: "select * from (select * from t) result LIMIT 100000;",
+ fieldName: []string{"a", "b", "c", "d"},
+ sensitiveDataMap: db.SensitiveDataMap{
+ db.SensitiveData{
+ Database: "",
+ Table: "t",
+ Column: "a",
+ }: db.SensitiveDataMaskTypeDefault,
+ db.SensitiveData{
+ Database: "",
+ Table: "t",
+ Column: "d",
+ }: db.SensitiveDataMaskTypeDefault,
+ },
+ fieldMap: sensitiveFiledMap{
+ 0: true,
+ 3: 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,
+ },
+ fieldMap: sensitiveFiledMap{
+ 0: true,
+ 2: true,
+ 3: true,
+ 4: true,
+ 6: true,
+ },
+ },
+ }
+
+ for _, test := range tests {
+ res, err := extractSensitiveField(db.MySQL, test.statement, test.fieldName, test.sensitiveDataMap)
+ require.NoError(t, err)
+ require.Equal(t, test.fieldMap, res)
+ }
+}
diff --git a/server/sql.go b/server/sql.go
index 35cf529359..ff5bab530b 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -182,21 +182,10 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
}
var database *api.Database
if exec.DatabaseName != "" {
- databaseFind := &api.DatabaseFind{
- InstanceID: &instance.ID,
- Name: &exec.DatabaseName,
- }
- dbList, err := s.store.FindDatabase(ctx, databaseFind)
+ database, err = s.getDatabase(ctx, instance.ID, exec.DatabaseName)
if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database `%s` for instance ID: %d", exec.DatabaseName, instance.ID)).SetInternal(err)
+ return err
}
- if len(dbList) == 0 {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database `%s` for instance ID: %d not found", exec.DatabaseName, instance.ID))
- }
- if len(dbList) > 1 {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("There are multiple database `%s` for instance ID: %d", exec.DatabaseName, instance.ID))
- }
- database = dbList[0]
}
adviceLevel := advisor.Success
@@ -263,6 +252,19 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
}
}
+ var sensitiveDataMap db.SensitiveDataMap
+ 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)
+ if err != nil {
+ return err
+ }
+ }
+
start := time.Now().UnixNano()
bytes, queryErr := func() ([]byte, error) {
@@ -272,7 +274,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
}
defer driver.Close(ctx)
- rowSet, err := driver.Query(ctx, exec.Statement, exec.Limit, true /* readOnly */)
+ rowSet, err := driver.Query(ctx, exec.Statement, exec.Limit, true /* readOnly */, sensitiveDataMap)
if err != nil {
return nil, err
}
@@ -416,7 +418,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
}
defer driver.Close(ctx)
- rowSet, err := driver.Query(ctx, exec.Statement, exec.Limit, false /* readOnly */)
+ rowSet, err := driver.Query(ctx, exec.Statement, exec.Limit, false /* readOnly */, nil)
if err != nil {
return nil, err
}
@@ -883,3 +885,94 @@ func checkPostgreSQLIndexHit(statement string, plan string) []advisor.Advice {
}
return nil
}
+
+func (s *Server) getDatabase(ctx context.Context, instanceID int, databaseName string) (*api.Database, error) {
+ databaseFind := &api.DatabaseFind{
+ InstanceID: &instanceID,
+ Name: &databaseName,
+ }
+ dbList, err := s.store.FindDatabase(ctx, databaseFind)
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database `%s` for instance ID: %d", databaseName, instanceID)).SetInternal(err)
+ }
+ if len(dbList) == 0 {
+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database `%s` for instance ID: %d not found", databaseName, instanceID))
+ }
+ if len(dbList) > 1 {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("There are multiple database `%s` for instance ID: %d", databaseName, instanceID))
+ }
+ 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)
+ for _, name := range databaseList {
+ databaseName := name
+ if name == "" {
+ if currentDatabase == "" {
+ continue
+ }
+ databaseName = currentDatabase
+ }
+
+ if isExcludeDatabase(engineType, databaseName) {
+ continue
+ }
+
+ database, err := s.getDatabase(ctx, instanceID, databaseName)
+ if err != nil {
+ return nil, err
+ }
+
+ 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)
+ // use for current database
+ if name == "" {
+ res[db.SensitiveData{
+ Database: "",
+ Table: data.Table,
+ Column: data.Column,
+ }] = db.SensitiveDataMaskType(data.Type)
+ }
+ }
+ }
+
+ return res, nil
+}
+
+func isExcludeDatabase(dbType db.Type, database string) bool {
+ switch dbType {
+ case db.MySQL:
+ return isMySQLExcludeDatabase(database)
+ case db.TiDB:
+ if isMySQLExcludeDatabase(database) {
+ return true
+ }
+ return database == "metrics_schema"
+ default:
+ return false
+ }
+}
+
+func isMySQLExcludeDatabase(database string) bool {
+ if strings.ToLower(database) == "information_schema" {
+ return true
+ }
+
+ switch database {
+ case "mysql":
+ case "sys":
+ case "performance_schema":
+ default:
+ return false
+ }
+ return true
+}
diff --git a/store/policy.go b/store/policy.go
index 9d360054c4..cdb8f732c0 100644
--- a/store/policy.go
+++ b/store/policy.go
@@ -249,6 +249,20 @@ func (s *Store) GetEnvironmentTierPolicyByEnvID(ctx context.Context, environment
return api.UnmarshalEnvironmentTierPolicy(policy.Payload)
}
+// GetSensitiveDataPolicy will get the sensitive data policy for database ID.
+func (s *Store) GetSensitiveDataPolicy(ctx context.Context, databaseID int) (*api.SensitiveDataPolicy, error) {
+ databaseResourceType := api.PolicyResourceTypeDatabase
+ policy, err := s.getPolicyRaw(ctx, &api.PolicyFind{
+ ResourceType: &databaseResourceType,
+ ResourceID: &databaseID,
+ Type: api.PolicyTypeSensitiveData,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return api.UnmarshalSensitiveDataPolicy(policy.Payload)
+}
+
//
// private functions
//