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: refactor policy evaluation and place global policy at the highest (#14820)
Danny Xu3ad8d20c639e
diff --git a/backend/api/v1/masking_evaluator.go b/backend/api/v1/masking_evaluator.goindex 03eed1f578..48cdb483f1 100644--- a/backend/api/v1/masking_evaluator.go+++ b/backend/api/v1/masking_evaluator.go@@ -1,7 +1,6 @@package v1import (- "log/slog""reflect""time"@@ -77,159 +76,118 @@ func (m *maskingLevelEvaluator) getDataClassificationConfig(classificationID strreturn m.dataClassificationIDMap[classificationID]}-type maskingPolicyKey struct {- schema string- table string- column string-}--type maskData struct {- Schema string- Table string- Column string- MaskingLevel storepb.MaskingLevel- FullMaskingAlgorithmID string- PartialMaskingAlgorithmID string-}+var (+ defaultFullAlgorithm = &storepb.Algorithm{+ Id: "default-full",+ }+ defaultPartialAlgorithm = &storepb.Algorithm{+ Id: "default-partial",+ }+)// nolint-func (m *maskingLevelEvaluator) evaluateMaskingAlgorithmOfColumn(databaseMessage *store.DatabaseMessage, schemaName, tableName, columnName, columnSemanticTypeID, columnClassification string, databaseProjectDataClassificationID string, maskingPolicyMap map[maskingPolicyKey]*maskData, filteredMaskingExceptions []*storepb.MaskingExceptionPolicy_MaskingException) (*storepb.Algorithm, storepb.MaskingLevel, error) {- maskingLevel, err := m.evaluateMaskingLevelOfColumn(databaseMessage, schemaName, tableName, columnName, columnClassification, databaseProjectDataClassificationID, maskingPolicyMap, filteredMaskingExceptions)+func (m *maskingLevelEvaluator) evaluateMaskingAlgorithmOfColumn(+ databaseMessage *store.DatabaseMessage,+ schemaName, tableName, columnName,+ databaseProjectDataClassificationID string,+ columnConfig *storepb.ColumnCatalog,+ filteredMaskingExceptions []*storepb.MaskingExceptionPolicy_MaskingException,+) (*storepb.Algorithm, storepb.MaskingLevel, error) {+ // TODO(d): deprecate globalMaskingLevel.+ globalMaskingLevel, err := m.evaluateGlobalMaskingLevelOfColumn(databaseMessage, schemaName, tableName, columnName, databaseProjectDataClassificationID, columnConfig)if err != nil {return nil, storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED, errors.Wrapf(err, "failed to evaluate masking level of column")}- if maskingLevel == storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED || maskingLevel == storepb.MaskingLevel_NONE {- return nil, maskingLevel, nil- }- key := maskingPolicyKey{- schema: schemaName,- table: tableName,- column: columnName,- }- if maskingData, ok := maskingPolicyMap[key]; ok {- algorithmID := ""- switch maskingLevel {- case storepb.MaskingLevel_PARTIAL:- algorithmID = maskingData.PartialMaskingAlgorithmID- case storepb.MaskingLevel_FULL:- algorithmID = maskingData.FullMaskingAlgorithmID- }- if algorithmID != "" {- if v, ok := m.maskingAlgorithms[algorithmID]; ok {- return v, maskingLevel, nil++ fullAlgorithmID, partialAlgorithmID := columnConfig.GetFullMaskingAlgorithmId(), columnConfig.GetPartialMaskingAlgorithmId()+ if fullAlgorithmID == "" && partialAlgorithmID == "" && columnConfig.GetSemanticTypeId() != "" {+ semanticType, ok := m.semanticTypesMap[columnConfig.GetSemanticTypeId()]+ if ok {+ if semanticType.GetFullMaskAlgorithmId() != "" {+ fullAlgorithmID = semanticType.GetFullMaskAlgorithmId()+ }+ if semanticType.GetPartialMaskAlgorithmId() != "" {+ partialAlgorithmID = semanticType.GetPartialMaskAlgorithmId()}- slog.Warn(- "failed to find the masking algorithm",- slog.String("algorithm", algorithmID),- slog.String("schema", schemaName),- slog.String("table", tableName),- slog.String("column", columnName),- )- // If we cannot find the algorithm, we just log the warning and treat it is as none masking.- return nil, storepb.MaskingLevel_NONE, nil}}-- if columnSemanticTypeID == "" {- return nil, maskingLevel, nil+ var fullAlgorithm, partialAlgorithm *storepb.Algorithm+ if fullAlgorithmID != "" {+ fullAlgorithm = m.maskingAlgorithms[fullAlgorithmID]}-- semanticType, ok := m.semanticTypesMap[columnSemanticTypeID]- if !ok {- slog.Warn(- "failed to find the semantic type",- slog.String("semantic_type", columnSemanticTypeID),- slog.String("schema", schemaName),- slog.String("table", tableName),- slog.String("column", columnName),- )- return nil, storepb.MaskingLevel_NONE, nil+ if partialAlgorithmID != "" {+ partialAlgorithm = m.maskingAlgorithms[partialAlgorithmID]}- algorithmID := ""- switch maskingLevel {- case storepb.MaskingLevel_PARTIAL:- algorithmID = semanticType.PartialMaskAlgorithmId- case storepb.MaskingLevel_FULL:- algorithmID = semanticType.FullMaskAlgorithmId+ if fullAlgorithm == nil {+ fullAlgorithm = defaultFullAlgorithm}- if algorithmID != "" {- if v, ok := m.maskingAlgorithms[algorithmID]; ok {- return v, maskingLevel, nil- }- slog.Warn(- "failed to find the masking algorithm",- slog.String("algorithm", algorithmID),- slog.String("schema", schemaName),- slog.String("table", tableName),- slog.String("column", columnName),- )- // If we cannot find the algorithm, we just log the warning and treat it is as none masking.+ if partialAlgorithm == nil {+ partialAlgorithm = defaultPartialAlgorithm+ }++ switch globalMaskingLevel {+ case storepb.MaskingLevel_NONE:return nil, storepb.MaskingLevel_NONE, nil+ case storepb.MaskingLevel_PARTIAL, storepb.MaskingLevel_FULL:+ pass, err := evaluateExceptionOfColumn(databaseMessage, schemaName, tableName, columnName, filteredMaskingExceptions)+ if err != nil {+ return nil, storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED, err+ }+ if pass {+ return nil, storepb.MaskingLevel_NONE, nil+ }+ if globalMaskingLevel == storepb.MaskingLevel_FULL {+ return fullAlgorithm, globalMaskingLevel, nil+ }+ if globalMaskingLevel == storepb.MaskingLevel_PARTIAL {+ return partialAlgorithm, globalMaskingLevel, nil+ }}- return nil, maskingLevel, nil+ switch columnConfig.GetMaskingLevel() {+ case storepb.MaskingLevel_NONE:+ return nil, storepb.MaskingLevel_NONE, nil+ case storepb.MaskingLevel_FULL:+ return fullAlgorithm, storepb.MaskingLevel_FULL, nil+ case storepb.MaskingLevel_PARTIAL:+ return partialAlgorithm, storepb.MaskingLevel_PARTIAL, nil+ }+ return nil, storepb.MaskingLevel_NONE, nil}-// evaluateMaskingLevelOfColumn evaluates the masking level of the given column.-//-// Args:-//-// - databaseMessage: the database message for the column belongs to.-//-// - databaseName / schemaName / tableName: the database / schema / table name for the column belongs to, schema can be empty likes in MySQL.-//-// - column: the column metadata.-//-// - databaseProjectDataClassificationID: the data classification id of the project the database belongs to.-//-// - maskingPolicyMap: the map of maskingPolicy for the database column belongs to.-//-// - filteredMaskingExceptions: the exceptions should apply for current principal.-func (m *maskingLevelEvaluator) evaluateMaskingLevelOfColumn(databaseMessage *store.DatabaseMessage, schemaName, tableName, columnName, columnClassification string, databaseProjectDataClassificationID string, maskingPolicyMap map[maskingPolicyKey]*maskData, filteredMaskingExceptions []*storepb.MaskingExceptionPolicy_MaskingException) (storepb.MaskingLevel, error) {- finalLevel := storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED-- key := maskingPolicyKey{- schema: schemaName,- table: tableName,- column: columnName,- }- maskingData, ok := maskingPolicyMap[key]- if (!ok) || (maskingData.MaskingLevel == storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED) {- dataClassificationConfig := m.getDataClassificationConfig(databaseProjectDataClassificationID)- // If the column has DEFAULT masking level in maskingPolicy or not set yet,- // we will eval the maskingRulePolicy to get the maskingLevel.- columnClassificationLevel := getClassificationLevelOfColumn(columnClassification, dataClassificationConfig)- for _, maskingRule := range m.maskingRules {- maskingRuleAttributes := map[string]any{- "environment_id": databaseMessage.EffectiveEnvironmentID,- "project_id": databaseMessage.ProjectID,- "instance_id": databaseMessage.InstanceID,- "database_name": databaseMessage.DatabaseName,- "schema_name": schemaName,- "table_name": tableName,- "column_name": columnName,- "classification_level": columnClassificationLevel,- }- pass, err := evaluateMaskingRulePolicyCondition(maskingRule.Condition.Expression, maskingRuleAttributes)- if err != nil {- return storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED, errors.Wrapf(err, "failed to evaluate masking rule policy condition")- }- if pass {- finalLevel = maskingRule.MaskingLevel- break- }+func (m *maskingLevelEvaluator) evaluateGlobalMaskingLevelOfColumn(+ databaseMessage *store.DatabaseMessage,+ schemaName, tableName, columnName string,+ databaseProjectDataClassificationID string,+ columnConfig *storepb.ColumnCatalog,+) (storepb.MaskingLevel, error) {+ dataClassificationConfig := m.getDataClassificationConfig(databaseProjectDataClassificationID)+ // If the column has DEFAULT masking level in maskingPolicy or not set yet,+ // we will eval the maskingRulePolicy to get the maskingLevel.+ classificationLevel := getClassificationLevelOfColumn(columnConfig.GetClassificationId(), dataClassificationConfig)+ for _, maskingRule := range m.maskingRules {+ maskingRuleAttributes := map[string]any{+ "environment_id": databaseMessage.EffectiveEnvironmentID,+ "project_id": databaseMessage.ProjectID,+ "instance_id": databaseMessage.InstanceID,+ "database_name": databaseMessage.DatabaseName,+ "schema_name": schemaName,+ "table_name": tableName,+ "column_name": columnName,+ "classification_level": classificationLevel,+ }+ pass, err := evaluateMaskingRulePolicyCondition(maskingRule.Condition.Expression, maskingRuleAttributes)+ if err != nil {+ return storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED, errors.Wrapf(err, "failed to evaluate masking rule policy condition")+ }+ if pass {+ return maskingRule.MaskingLevel, nil}- } else {- finalLevel = maskingData.MaskingLevel- }-- if finalLevel == storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED || finalLevel == storepb.MaskingLevel_NONE {- return storepb.MaskingLevel_NONE, nil}+ return storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED, nil+}- // If the column has PARTIAL/FULL masking level,- // try to find the MaskingExceptionPolicy for current principal, return the minimum level of two.- // If there is no MaskingExceptionPolicy for current principal, return the masking level in maskingPolicy.+func evaluateExceptionOfColumn(databaseMessage *store.DatabaseMessage, schemaName, tableName, columnName string, filteredMaskingExceptions []*storepb.MaskingExceptionPolicy_MaskingException) (bool, error) {for _, filteredMaskingException := range filteredMaskingExceptions {maskingExceptionAttributes := map[string]any{"resource": map[string]any{@@ -243,15 +201,15 @@ func (m *maskingLevelEvaluator) evaluateMaskingLevelOfColumn(databaseMessage *st"time": time.Now(),},}- hit, err := evaluateMaskingExceptionPolicyCondition(filteredMaskingException.Condition, maskingExceptionAttributes)+ pass, err := evaluateMaskingExceptionPolicyCondition(filteredMaskingException.Condition, maskingExceptionAttributes)if err != nil {- return storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED, errors.Wrapf(err, "failed to evaluate masking exception policy condition")+ return false, errors.Wrapf(err, "failed to evaluate masking exception policy condition")}- if hit {- return storepb.MaskingLevel_NONE, nil+ if pass {+ return true, nil}}- return finalLevel, nil+ return false, nil}func getClassificationLevelOfColumn(columnClassificationID string, classificationConfig *storepb.DataClassificationSetting_DataClassificationConfig) string {diff --git a/backend/api/v1/masking_evaluator_test.go b/backend/api/v1/masking_evaluator_test.goindex b1dc92bde4..297705a286 100644--- a/backend/api/v1/masking_evaluator_test.go+++ b/backend/api/v1/masking_evaluator_test.go@@ -54,8 +54,7 @@ func TestEvalMaskingLevelOfColumn(t *testing.T) {schemaName stringtableName stringcolumnName string- columnClassification string- maskingPolicyMap map[maskingPolicyKey]*maskData+ columnCatalog *storepb.ColumnCatalogmaskingRulePolicy *storepb.MaskingRulePolicyfilteredMaskingExceptions []*storepb.MaskingExceptionPolicy_MaskingExceptiondataClassification *storepb.DataClassificationSetting@@ -63,13 +62,15 @@ func TestEvalMaskingLevelOfColumn(t *testing.T) {want storepb.MaskingLevel}{{- description: "Follow The Global Masking Rule If Column Masking Policy Is Default",- databaseMessage: defaultDatabaseMessage,- schemaName: "hiring",- tableName: "employees",- columnName: "salary",- columnClassification: "1-1-1",- maskingPolicyMap: map[maskingPolicyKey]*maskData{},+ description: "Follow The Global Masking Rule",+ databaseMessage: defaultDatabaseMessage,+ schemaName: "hiring",+ tableName: "employees",+ columnName: "salary",+ columnCatalog: &storepb.ColumnCatalog{+ ClassificationId: "1-1-1",+ MaskingLevel: storepb.MaskingLevel_NONE,+ },maskingRulePolicy: &storepb.MaskingRulePolicy{Rules: []*storepb.MaskingRulePolicy_MaskingRule{{@@ -86,56 +87,25 @@ func TestEvalMaskingLevelOfColumn(t *testing.T) {want: storepb.MaskingLevel_FULL,},{- description: "Follow The Global Masking Rule If Column Masking Policy Is Default And Respect The Exception",- databaseMessage: defaultDatabaseMessage,- schemaName: "hiring",- tableName: "employees",- columnName: "salary",- columnClassification: "1-1-1",- maskingPolicyMap: map[maskingPolicyKey]*maskData{},- maskingRulePolicy: &storepb.MaskingRulePolicy{- Rules: []*storepb.MaskingRulePolicy_MaskingRule{- {- // Classification hit.- Condition: &expr.Expr{Expression: `(table_name == "no_table") || (classification_level == "S2")`},- MaskingLevel: storepb.MaskingLevel_FULL,- },- },+ description: "Respect The Exception",+ databaseMessage: defaultDatabaseMessage,+ schemaName: "hiring",+ tableName: "employees",+ columnName: "salary",+ columnCatalog: &storepb.ColumnCatalog{+ ClassificationId: "1-1-1",},- filteredMaskingExceptions: []*storepb.MaskingExceptionPolicy_MaskingException{- {- Action: storepb.MaskingExceptionPolicy_MaskingException_QUERY,- Condition: &expr.Expr{- Expression: `(resource.instance_id == "neon-host") && (resource.database_name == "bb") && (resource.schema_name == "hiring") && (resource.table_name == "employees") && (resource.column_name == "salary")`,- },- Member: "users/1234",- },- },- dataClassification: defaultClassification,- databaseProjectDatabaseClassificationID: defaultProjectDatabaseDataClassificationID,-- want: storepb.MaskingLevel_NONE,- },- {- description: "Only Find The Lower Level in Exception",- databaseMessage: defaultDatabaseMessage,- schemaName: "hiring",- tableName: "employees",- columnName: "salary",- columnClassification: "1-1-1",- maskingPolicyMap: map[maskingPolicyKey]*maskData{},maskingRulePolicy: &storepb.MaskingRulePolicy{Rules: []*storepb.MaskingRulePolicy_MaskingRule{{// Classification hit.Condition: &expr.Expr{Expression: `(table_name == "no_table") || (classification_level == "S2")`},- MaskingLevel: storepb.MaskingLevel_PARTIAL,+ MaskingLevel: storepb.MaskingLevel_FULL,},},},filteredMaskingExceptions: []*storepb.MaskingExceptionPolicy_MaskingException{{- // Hit, but MaskingLevel_FULL > MaskingLevel_PARTIAL, do not replace the rule.Action: storepb.MaskingExceptionPolicy_MaskingException_QUERY,Condition: &expr.Expr{Expression: `(resource.instance_id == "neon-host") && (resource.database_name == "bb") && (resource.schema_name == "hiring") && (resource.table_name == "employees") && (resource.column_name == "salary")`,@@ -149,39 +119,20 @@ func TestEvalMaskingLevelOfColumn(t *testing.T) {want: storepb.MaskingLevel_NONE,},{- description: "Respect The Column Masking Policy",- databaseMessage: defaultDatabaseMessage,- schemaName: "hiring",- tableName: "employees",- columnName: "salary",- columnClassification: "1-1-1",- maskingPolicyMap: map[maskingPolicyKey]*maskData{- {- schema: "hiring",- table: "employees",- column: "salary",- }: {- Schema: "hiring",- Table: "employees",- Column: "salary",- MaskingLevel: storepb.MaskingLevel_FULL,- },- },- maskingRulePolicy: &storepb.MaskingRulePolicy{},- filteredMaskingExceptions: []*storepb.MaskingExceptionPolicy_MaskingException{- {- // Hit, and MaskingLevel_PARTIAL < MaskingLevel_FULL.- Action: storepb.MaskingExceptionPolicy_MaskingException_QUERY,- Condition: &expr.Expr{- Expression: `(resource.instance_id == "neon-host") && (resource.database_name == "bb") && (resource.schema_name == "hiring") && (resource.table_name == "employees") && (resource.column_name == "salary")`,- },- Member: "users/1234",- },+ description: "Column Catalog",+ databaseMessage: defaultDatabaseMessage,+ schemaName: "hiring",+ tableName: "employees",+ columnName: "salary",+ columnCatalog: &storepb.ColumnCatalog{+ ClassificationId: "1-1-1",+ MaskingLevel: storepb.MaskingLevel_FULL,},+ maskingRulePolicy: &storepb.MaskingRulePolicy{},dataClassification: defaultClassification,databaseProjectDatabaseClassificationID: defaultProjectDatabaseDataClassificationID,- want: storepb.MaskingLevel_NONE,+ want: storepb.MaskingLevel_FULL,},}@@ -189,7 +140,7 @@ func TestEvalMaskingLevelOfColumn(t *testing.T) {for _, tc := range testCases {m := newEmptyMaskingLevelEvaluator().withMaskingRulePolicy(tc.maskingRulePolicy).withDataClassificationSetting(tc.dataClassification)- result, err := m.evaluateMaskingLevelOfColumn(tc.databaseMessage, tc.schemaName, tc.tableName, tc.columnName, tc.columnClassification, tc.databaseProjectDatabaseClassificationID, tc.maskingPolicyMap, tc.filteredMaskingExceptions)+ _, result, err := m.evaluateMaskingAlgorithmOfColumn(tc.databaseMessage, tc.schemaName, tc.tableName, tc.columnName, tc.databaseProjectDatabaseClassificationID, tc.columnCatalog, tc.filteredMaskingExceptions)a.NoError(err, tc.description)a.Equal(tc.want, result, tc.description)}diff --git a/backend/api/v1/query_result_masker.go b/backend/api/v1/query_result_masker.goindex 663e288d04..2eecee2a2b 100644--- a/backend/api/v1/query_result_masker.go+++ b/backend/api/v1/query_result_masker.go@@ -184,38 +184,6 @@ func (s *QueryResultMasker) getMaskerForColumnResource(return masker.NewNoneMasker(), nil}- semanticTypeID := ""- if config != nil {- semanticTypeID = config.SemanticTypeId- }-- dbSchema, err := s.store.GetDBSchema(ctx, database.UID)- if err != nil {- return nil, status.Error(codes.Internal, err.Error())- }- maskingPolicyMap := make(map[maskingPolicyKey]*maskData)- for _, schemaConfig := range dbSchema.GetConfig().Schemas {- for _, tableConfig := range schemaConfig.GetTables() {- for _, columnConfig := range tableConfig.GetColumns() {- if columnConfig.MaskingLevel == storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED {- continue- }- maskingPolicyMap[maskingPolicyKey{- schema: schemaConfig.Name,- table: tableConfig.Name,- column: columnConfig.Name,- }] = &maskData{- Schema: schemaConfig.Name,- Table: tableConfig.Name,- Column: columnConfig.Name,- MaskingLevel: columnConfig.MaskingLevel,- FullMaskingAlgorithmID: columnConfig.FullMaskingAlgorithmId,- PartialMaskingAlgorithmID: columnConfig.PartialMaskingAlgorithmId,- }- }- }- }-var maskingExceptionPolicy *storepb.MaskingExceptionPolicy// If we cannot find the maskingExceptionPolicy before, we need to find it from the database and record it in cache.@@ -247,7 +215,7 @@ func (s *QueryResultMasker) getMaskerForColumnResource(}}- maskingAlgorithm, maskingLevel, err := m.evaluateMaskingAlgorithmOfColumn(database, sourceColumn.Schema, sourceColumn.Table, sourceColumn.Column, semanticTypeID, config.ClassificationId, project.DataClassificationConfigID, maskingPolicyMap, maskingExceptionContainsCurrentPrincipal)+ maskingAlgorithm, maskingLevel, err := m.evaluateMaskingAlgorithmOfColumn(database, sourceColumn.Schema, sourceColumn.Table, sourceColumn.Column, project.DataClassificationConfigID, config, maskingExceptionContainsCurrentPrincipal)if err != nil {return nil, errors.Wrapf(err, "failed to evaluate masking level of database %q, schema %q, table %q, column %q", sourceColumn.Database, sourceColumn.Schema, sourceColumn.Table, sourceColumn.Column)}@@ -317,6 +285,12 @@ func getMaskerByMaskingAlgorithmAndLevel(algorithm *storepb.Algorithm, level storeturn masker.NewNoneMasker()}}+ switch algorithm.GetId() {+ case "default-full":+ return masker.NewDefaultFullMasker()+ case "default-partial":+ return masker.NewDefaultRangeMasker()+ }switch m := algorithm.Mask.(type) {case *storepb.Algorithm_FullMask_: