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: mask sensitive field for PostgreSQL CTE (#4693)
rebelice3f62748e725d
diff --git a/backend/plugin/db/util/driverutil_test.go b/backend/plugin/db/util/driverutil_test.goindex 0a604a6e75..f0d5264fea 100644--- a/backend/plugin/db/util/driverutil_test.go+++ b/backend/plugin/db/util/driverutil_test.go@@ -755,6 +755,199 @@ func TestPostgreSQLExtractSensitiveField(t *testing.T) {schemaInfo *db.SensitiveSchemaInfofieldList []db.SensitiveField}{+ {+ // Test for Non-Recursive Common Table Expression with RECURSIVE key words.+ statement: `+ with recursive t1 as (+ select 1 as c1, 2 as c2, 3 as c3, 1 as n+ union+ select a, b, d, c from t+ )+ select * from t1;+ `,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "c1",+ Sensitive: true,+ },+ {+ Name: "c2",+ Sensitive: false,+ },+ {+ Name: "c3",+ Sensitive: true,+ },+ {+ Name: "n",+ Sensitive: false,+ },+ },+ },+ {+ // Test for Recursive Common Table Expression dependent closures.+ statement: `+ with recursive t1(cc1, cc2, cc3, n) as (+ select a as c1, b as c2, c as c3, 1 as n from t+ union+ select cc1 * cc2, cc2 + cc1, cc3 * cc2, n + 1 from t1 where n < 5+ )+ select * from t1;+ `,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "cc1",+ Sensitive: true,+ },+ {+ Name: "cc2",+ Sensitive: true,+ },+ {+ Name: "cc3",+ Sensitive: true,+ },+ {+ Name: "n",+ Sensitive: false,+ },+ },+ },+ {+ // Test for Recursive Common Table Expression.+ statement: `+ with recursive t1 as (+ select 1 as c1, 2 as c2, 3 as c3, 1 as n+ union+ select c1 * a, c2 * b, c3 * d, n + 1 from t1, t where n < 5+ )+ select * from t1;+ `,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "c1",+ Sensitive: true,+ },+ {+ Name: "c2",+ Sensitive: false,+ },+ {+ Name: "c3",+ Sensitive: true,+ },+ {+ Name: "n",+ Sensitive: false,+ },+ },+ },+ {+ // Test that Common Table Expression rename field names.+ statement: `with t1(d, c, b, a) as (select * from t) select * from t1`,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "d",+ Sensitive: true,+ },+ {+ Name: "c",+ Sensitive: false,+ },+ {+ Name: "b",+ Sensitive: false,+ },+ {+ Name: "a",+ Sensitive: true,+ },+ },+ },+ {+ // Test for Common Table Expression with UNION.+ statement: `with t1 as (select * from t), t2 as (select * from t1) select * from t1 union all select * from t2`,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "a",+ Sensitive: true,+ },+ {+ Name: "b",+ Sensitive: false,+ },+ {+ Name: "c",+ Sensitive: false,+ },+ {+ Name: "d",+ Sensitive: true,+ },+ },+ },+ {+ // Test for Common Table Expression reference.+ statement: `with t1 as (select * from t), t2 as (select * from t1) select * from t2`,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "a",+ Sensitive: true,+ },+ {+ Name: "b",+ Sensitive: false,+ },+ {+ Name: "c",+ Sensitive: false,+ },+ {+ Name: "d",+ Sensitive: true,+ },+ },+ },+ {+ // Test for multi-level Common Table Expression.+ statement: `with tt2 as (with tt2 as (select * from t) select max(a) from tt2) select * from tt2;`,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "max",+ Sensitive: true,+ },+ },+ },+ {+ // Test for Common Table Expression.+ statement: `with t1 as (select * from t) select * from t1`,+ schemaInfo: defaultDatabaseSchema,+ fieldList: []db.SensitiveField{+ {+ Name: "a",+ Sensitive: true,+ },+ {+ Name: "b",+ Sensitive: false,+ },+ {+ Name: "c",+ Sensitive: false,+ },+ {+ Name: "d",+ Sensitive: true,+ },+ },+ },{// Test for UNION.statement: `select 1 as c1, 2 as c2, 3 as c3, 4 UNION ALL select * from t`,diff --git a/backend/plugin/db/util/mask_sensitive_data.go b/backend/plugin/db/util/mask_sensitive_data.goindex 8f005be847..cc18a55739 100644--- a/backend/plugin/db/util/mask_sensitive_data.go+++ b/backend/plugin/db/util/mask_sensitive_data.go@@ -305,8 +305,141 @@ func (extractor *sensitiveFieldExtractor) pgFindTableSchema(tableName string) (dreturn db.TableSchema{}, errors.Errorf("Table %q not found", tableName)}+func (extractor *sensitiveFieldExtractor) pgExtractRecursiveCTE(node *pgquery.Node_CommonTableExpr) (db.TableSchema, error) {+ switch selectNode := node.CommonTableExpr.Ctequery.Node.(type) {+ case *pgquery.Node_SelectStmt:+ if selectNode.SelectStmt.Op != pgquery.SetOperation_SETOP_UNION {+ return extractor.pgExtractNonRecursiveCTE(node)+ }+ // For PostgreSQL, recursive CTE will be an UNION statement, and the left node is the initial part,+ // the right node is the recursive part.+ initialField, err := extractor.pgExtractSelect(&pgquery.Node_SelectStmt{SelectStmt: selectNode.SelectStmt.Larg})+ if err != nil {+ return db.TableSchema{}, err+ }+ if len(node.CommonTableExpr.Aliascolnames) > 0 {+ if len(node.CommonTableExpr.Aliascolnames) != len(initialField) {+ return db.TableSchema{}, errors.Errorf("The common table expression and column names list have different column counts")+ }+ for i, nameNode := range node.CommonTableExpr.Aliascolnames {+ stringNode, yes := nameNode.Node.(*pgquery.Node_String_)+ if !yes {+ return db.TableSchema{}, errors.Errorf("expect Node_String_ but found %T", nameNode.Node)+ }+ initialField[i].name = stringNode.String_.Str+ }+ }++ cteInfo := db.TableSchema{Name: pgNormalizeTableName("public", node.CommonTableExpr.Ctename)}+ for _, field := range initialField {+ cteInfo.ColumnList = append(cteInfo.ColumnList, db.ColumnInfo{+ Name: field.name,+ Sensitive: field.sensitive,+ })+ }++ // Compute dependent closures.+ // There are two ways to compute dependent closures:+ // 1. find the all dependent edges, then use graph theory traversal to find the closure.+ // 2. Iterate to simulate the CTE recursive process, each turn check whether the Sensitive state has changed, and stop if no change.+ //+ // Consider the option 2 can easy to implementation, because the simulate process has been written.+ // On the other hand, the number of iterations of the entire algorithm will not exceed the length of fields.+ // In actual use, the length of fields will not be more than 20 generally.+ // So I think it's OK for now.+ // If any performance issues in use, optimize here.+ extractor.cteOuterSchemaInfo = append(extractor.cteOuterSchemaInfo, cteInfo)+ defer func() {+ extractor.cteOuterSchemaInfo = extractor.cteOuterSchemaInfo[:len(extractor.cteOuterSchemaInfo)-1]+ }()+ for {+ fieldList, err := extractor.pgExtractSelect(&pgquery.Node_SelectStmt{SelectStmt: selectNode.SelectStmt.Rarg})+ if err != nil {+ return db.TableSchema{}, err+ }+ if len(fieldList) != len(cteInfo.ColumnList) {+ return db.TableSchema{}, errors.Errorf("The common table expression and column names list have different column counts")+ }++ changed := false+ for i, field := range fieldList {+ if field.sensitive && !cteInfo.ColumnList[i].Sensitive {+ changed = true+ cteInfo.ColumnList[i].Sensitive = true+ }+ }++ if !changed {+ break+ }+ extractor.cteOuterSchemaInfo[len(extractor.cteOuterSchemaInfo)-1] = cteInfo+ }+ return cteInfo, nil+ default:+ return extractor.pgExtractNonRecursiveCTE(node)+ }+}++func (extractor *sensitiveFieldExtractor) pgExtractNonRecursiveCTE(node *pgquery.Node_CommonTableExpr) (db.TableSchema, error) {+ fieldList, err := extractor.pgExtractNode(node.CommonTableExpr.Ctequery)+ if err != nil {+ return db.TableSchema{}, err+ }+ if len(node.CommonTableExpr.Aliascolnames) > 0 {+ if len(node.CommonTableExpr.Aliascolnames) != len(fieldList) {+ return db.TableSchema{}, errors.Errorf("The common table expression and column names list have different column counts")+ }+ var nameList []string+ for _, nameNode := range node.CommonTableExpr.Aliascolnames {+ stringNode, yes := nameNode.Node.(*pgquery.Node_String_)+ if !yes {+ return db.TableSchema{}, errors.Errorf("expect Node_String_ but found %T", nameNode.Node)+ }+ nameList = append(nameList, stringNode.String_.Str)+ }+ for i := 0; i < len(fieldList); i++ {+ fieldList[i].name = nameList[i]+ }+ }+ result := db.TableSchema{+ Name: pgNormalizeTableName("public", node.CommonTableExpr.Ctename),+ ColumnList: []db.ColumnInfo{},+ }++ for _, field := range fieldList {+ result.ColumnList = append(result.ColumnList, db.ColumnInfo{+ Name: field.name,+ Sensitive: field.sensitive,+ })+ }++ return result, nil+}+func (extractor *sensitiveFieldExtractor) pgExtractSelect(node *pgquery.Node_SelectStmt) ([]fieldInfo, error) {- // TODO(rebelice): consider the CTE.+ if node.SelectStmt.WithClause != nil {+ cteOuterLength := len(extractor.cteOuterSchemaInfo)+ defer func() {+ extractor.cteOuterSchemaInfo = extractor.cteOuterSchemaInfo[:cteOuterLength]+ }()+ for _, cte := range node.SelectStmt.WithClause.Ctes {+ in, yes := cte.Node.(*pgquery.Node_CommonTableExpr)+ if !yes {+ return nil, errors.Errorf("expect CommonTableExpr but found %T", cte.Node)+ }+ var cteTable db.TableSchema+ var err error+ if node.SelectStmt.WithClause.Recursive {+ cteTable, err = extractor.pgExtractRecursiveCTE(in)+ } else {+ cteTable, err = extractor.pgExtractNonRecursiveCTE(in)+ }+ if err != nil {+ return nil, err+ }+ extractor.cteOuterSchemaInfo = append(extractor.cteOuterSchemaInfo, cteTable)+ }+ }// The VALUES case.if len(node.SelectStmt.ValuesLists) > 0 {