Skip to content

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

feat(masking): support cosmosdb masking object and atomic type (#15256)

h3n4lda638fcbd396
diff --git a/backend/api/v1/catalog_masking.go b/backend/api/v1/catalog_masking.go
new file mode 100644
index 0000000000..028eafb484
--- /dev/null
+++ b/backend/api/v1/catalog_masking.go
@@ -0,0 +1,134 @@
+package v1
+
+import (
+ "github.com/bytebase/bytebase/backend/component/masker"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+)
+
+func walkAndMaskJSON(data any, objectSchema *storepb.ObjectSchema, semanticTypeToMasker map[string]masker.Masker) (any, error) {
+ switch data := data.(type) {
+ case map[string]any:
+ if objectSchema.Type == storepb.ObjectSchema_OBJECT {
+ if objectSchema.SemanticType != "" {
+ // If the outer semantic type is found, apply the masker recursively to the object.
+ if m, ok := semanticTypeToMasker[objectSchema.SemanticType]; ok {
+ maskedData, err := applyMaskerToData(data, m)
+ if err != nil {
+ return nil, err
+ }
+ return maskedData, nil
+ }
+ } else {
+ // Otherwise, recursively walk the object.
+ structKind := objectSchema.GetStructKind()
+ // Quick return if there is no struct kind in object schema.
+ if structKind == nil {
+ return data, nil
+ }
+ for key, value := range data {
+ if childObjectSchema, ok := structKind.Properties[key]; ok {
+ // Recursively walk the property if child object schema found.
+ var err error
+ data[key], err = walkAndMaskJSON(value, childObjectSchema, semanticTypeToMasker)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+ }
+ return data, nil
+ }
+ default:
+ // For JSON atomic member, apply the masker if semantic type is found.
+ if objectSchema.SemanticType != "" {
+ if m, ok := semanticTypeToMasker[objectSchema.SemanticType]; ok {
+ maskedData, err := applyMaskerToData(data, m)
+ if err != nil {
+ return nil, err
+ }
+ return maskedData, nil
+ }
+ }
+ }
+ return data, nil
+}
+
+func applyMaskerToData(data any, m masker.Masker) (any, error) {
+ switch data := data.(type) {
+ case map[string]any:
+ // Recursively apply the masker to the object.
+ for key, value := range data {
+ maskedValue, err := applyMaskerToData(value, m)
+ if err != nil {
+ return nil, err
+ }
+ data[key] = maskedValue
+ }
+ case []any:
+ // Recursively apply the masker to the array.
+ for i, value := range data {
+ maskedValue, err := applyMaskerToData(value, m)
+ if err != nil {
+ return nil, err
+ }
+ data[i] = maskedValue
+ }
+ default:
+ // Apply the masker to the atomic value.
+ if wrappedValue, ok := getRowValueFromJSONAtomicMember(data); ok {
+ maskedValue := m.Mask(&masker.MaskData{Data: wrappedValue})
+ return getJSONMemberFromRowValue(maskedValue), nil
+ }
+ }
+
+ return data, nil
+}
+
+func getJSONMemberFromRowValue(rowValue *v1pb.RowValue) any {
+ switch rowValue := rowValue.Kind.(type) {
+ // TODO: Handle NULL, VALUE_VALUE, TIMESTAMP_VALUE, TIMESTAMPTZVALUE.
+ case *v1pb.RowValue_BoolValue:
+ return rowValue.BoolValue
+ case *v1pb.RowValue_BytesValue:
+ return string(rowValue.BytesValue)
+ case *v1pb.RowValue_DoubleValue:
+ return rowValue.DoubleValue
+ case *v1pb.RowValue_FloatValue:
+ return rowValue.FloatValue
+ case *v1pb.RowValue_Int32Value:
+ return rowValue.Int32Value
+ case *v1pb.RowValue_StringValue:
+ return rowValue.StringValue
+ case *v1pb.RowValue_Uint32Value:
+ return rowValue.Uint32Value
+ case *v1pb.RowValue_Uint64Value:
+ return rowValue.Uint64Value
+ }
+ return nil
+}
+
+func getRowValueFromJSONAtomicMember(data any) (result *v1pb.RowValue, ok bool) {
+ if data == nil {
+ return &v1pb.RowValue{
+ Kind: &v1pb.RowValue_NullValue{},
+ }, true
+ }
+ switch data := data.(type) {
+ case string:
+ return &v1pb.RowValue{
+ Kind: &v1pb.RowValue_StringValue{StringValue: data},
+ }, true
+ case float64:
+ // https://pkg.go.dev/encoding/json#Unmarshal
+ return &v1pb.RowValue{
+ Kind: &v1pb.RowValue_DoubleValue{DoubleValue: data},
+ }, true
+ case bool:
+ return &v1pb.RowValue{
+ Kind: &v1pb.RowValue_BoolValue{BoolValue: data},
+ }, true
+ }
+ // TODO: Handle NULL.
+ return nil, false
+}
diff --git a/backend/api/v1/catalog_masking_test.go b/backend/api/v1/catalog_masking_test.go
new file mode 100644
index 0000000000..459810e767
--- /dev/null
+++ b/backend/api/v1/catalog_masking_test.go
@@ -0,0 +1,102 @@
+package v1
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/component/masker"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func TestWalkAndMaskJSON(t *testing.T) {
+ type testCase struct {
+ description string
+ input string
+ objectSchema *storepb.ObjectSchema
+ semanticTypeToMasker map[string]masker.Masker
+ want string
+ }
+
+ testCases := []testCase{
+ {
+ description: "mask the outest semantic type",
+ input: `{"name": "John", "ssn": "123-45-6789"}`,
+ objectSchema: &storepb.ObjectSchema{
+ Type: storepb.ObjectSchema_OBJECT,
+ Kind: &storepb.ObjectSchema_StructKind_{
+ StructKind: &storepb.ObjectSchema_StructKind{
+ Properties: map[string]*storepb.ObjectSchema{
+ "ssn": {
+ SemanticType: "PII-SSN",
+ Type: storepb.ObjectSchema_STRING,
+ },
+ },
+ },
+ },
+ },
+ semanticTypeToMasker: map[string]masker.Masker{
+ "PII-SSN": masker.NewFullMasker("******"),
+ },
+ want: `{"name": "John", "ssn": "******"}`,
+ },
+ {
+ description: "mask the inner semantic type",
+ input: `{"name": "John", "information": {"ssn": "123-45-6789"}}`,
+ objectSchema: &storepb.ObjectSchema{
+ Type: storepb.ObjectSchema_OBJECT,
+ Kind: &storepb.ObjectSchema_StructKind_{
+ StructKind: &storepb.ObjectSchema_StructKind{
+ Properties: map[string]*storepb.ObjectSchema{
+ "information": {
+ Type: storepb.ObjectSchema_OBJECT,
+ Kind: &storepb.ObjectSchema_StructKind_{
+ StructKind: &storepb.ObjectSchema_StructKind{
+ Properties: map[string]*storepb.ObjectSchema{
+ "ssn": {
+ Type: storepb.ObjectSchema_STRING,
+ SemanticType: "PII-SSN",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ semanticTypeToMasker: map[string]masker.Masker{
+ "PII-SSN": masker.NewFullMasker("******"),
+ },
+ want: `{"name": "John", "information": {"ssn": "******"}}`,
+ },
+ {
+ description: "Recursive apply the masker to the object",
+ input: `{"name": "John", "information": {"ssn": "123-45-6789"}}`,
+ objectSchema: &storepb.ObjectSchema{
+ Type: storepb.ObjectSchema_OBJECT,
+ SemanticType: "FULL",
+ },
+ semanticTypeToMasker: map[string]masker.Masker{
+ "FULL": masker.NewFullMasker("******"),
+ },
+ want: `{"name": "******", "information": {"ssn": "******"}}`,
+ },
+ }
+
+ for _, tc := range testCases {
+ var input any
+ err := json.Unmarshal([]byte(tc.input), &input)
+ require.NoError(t, err)
+
+ got, err := walkAndMaskJSON(input, tc.objectSchema, tc.semanticTypeToMasker)
+ require.NoError(t, err)
+
+ output, err := json.Marshal(got)
+ require.NoError(t, err)
+
+ require.NoError(t, err)
+ require.JSONEq(t, tc.want, string(output))
+ }
+}
diff --git a/backend/api/v1/database_catalog_service.go b/backend/api/v1/database_catalog_service.go
index a839896acc..55f738a75b 100644
--- a/backend/api/v1/database_catalog_service.go
+++ b/backend/api/v1/database_catalog_service.go
@@ -184,6 +184,7 @@ func convertStoreObjectSchema(objectSchema *storepb.ObjectSchema) *v1pb.ObjectSc
},
}
}
+ o.SemanticType = objectSchema.SemanticType
return o
}
@@ -257,5 +258,6 @@ func convertV1ObjectSchema(objectSchema *v1pb.ObjectSchema) *storepb.ObjectSchem
},
}
}
+ o.SemanticType = objectSchema.SemanticType
return o
}
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index e1265c6828..f98755f59e 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"database/sql"
+ "encoding/json"
"fmt"
"io"
"regexp"
@@ -25,6 +26,7 @@ import (
"github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/dbfactory"
"github.com/bytebase/bytebase/backend/component/iam"
+ "github.com/bytebase/bytebase/backend/component/masker"
"github.com/bytebase/bytebase/backend/component/sheet"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
@@ -513,26 +515,115 @@ func queryRetry(
}
if licenseService.IsFeatureEnabledForInstance(api.FeatureSensitiveData, instance) == nil && !queryContext.Explain {
- masker := NewQueryResultMasker(stores)
- if err := masker.MaskResults(ctx, spans, results, instance, user, action); err != nil {
- return nil, nil, duration, status.Error(codes.Internal, err.Error())
- }
-
- for i, result := range results {
- if i >= len(sensitivePredicateColumns) {
- continue
+ // TODO(zp): Refactor Document Database and RDBMS to use the same masking logic.
+ if instance.Engine == storepb.Engine_COSMOSDB {
+ objectSchema, err := getCosmosDBContainerObjectSchema(ctx, stores, database.InstanceID, database.DatabaseName, queryContext.Container)
+ if err != nil {
+ return nil, nil, duration, status.Error(codes.Internal, err.Error())
}
- if len(sensitivePredicateColumns[i]) == 0 {
- continue
+ if objectSchema != nil {
+ // We store one query result document in one row.
+ for _, result := range results {
+ for _, row := range result.Rows {
+ if len(row.Values) != 1 {
+ continue
+ }
+ value := row.Values[0].GetStringValue()
+ if value == "" {
+ continue
+ }
+ semanticTypeToMaskerMap, err := buildSemanticTypeToMaskerMap(ctx, stores)
+ if err != nil {
+ return nil, nil, duration, status.Error(codes.Internal, err.Error())
+ }
+ // Unmarshal the document.
+ doc := make(map[string]any)
+ if err := json.Unmarshal([]byte(value), &doc); err != nil {
+ return nil, nil, duration, status.Errorf(codes.Internal, "failed to unmarshal document: %v", err)
+ }
+ // Mask the document.
+ maskedDoc, err := walkAndMaskJSON(doc, objectSchema, semanticTypeToMaskerMap)
+ if err != nil {
+ return nil, nil, duration, status.Errorf(codes.Internal, "failed to mask document: %v", err)
+ }
+ // Marshal the masked document.
+ maskedValue, err := json.Marshal(maskedDoc)
+ if err != nil {
+ return nil, nil, duration, status.Errorf(codes.Internal, "failed to marshal masked document: %v", err)
+ }
+ row.Values[0] = &v1pb.RowValue{
+ Kind: &v1pb.RowValue_StringValue{
+ StringValue: string(maskedValue),
+ },
+ }
+ }
+ }
+ }
+ } else {
+ masker := NewQueryResultMasker(stores)
+ if err := masker.MaskResults(ctx, spans, results, instance, user, action); err != nil {
+ return nil, nil, duration, status.Error(codes.Internal, err.Error())
+ }
+
+ for i, result := range results {
+ if i >= len(sensitivePredicateColumns) {
+ continue
+ }
+ if len(sensitivePredicateColumns[i]) == 0 {
+ continue
+ }
+ result.Error = getSensitivePredicateColumnErrorMessages(sensitivePredicateColumns[i])
+ result.Rows = nil
+ result.RowsCount = 0
}
- result.Error = getSensitivePredicateColumnErrorMessages(sensitivePredicateColumns[i])
- result.Rows = nil
- result.RowsCount = 0
}
}
return results, spans, duration, nil
}
+func buildSemanticTypeToMaskerMap(ctx context.Context, stores *store.Store) (map[string]masker.Masker, error) {
+ semanticTypeToMasker := map[string]masker.Masker{
+ "bb.default": masker.NewDefaultFullMasker(),
+ "bb.default-partial": masker.NewDefaultRangeMasker(),
+ }
+ semanticTypesSetting, err := stores.GetSemanticTypesSetting(ctx)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get semantic types setting")
+ }
+ for _, semanticType := range semanticTypesSetting.GetTypes() {
+ masker := getMaskerByMaskingAlgorithmAndLevel(semanticType.GetAlgorithm())
+ semanticTypeToMasker[semanticType.GetId()] = masker
+ }
+
+ return semanticTypeToMasker, nil
+}
+
+func getCosmosDBContainerObjectSchema(ctx context.Context, stores *store.Store, instanceID string, databaseName string, containerName string) (*storepb.ObjectSchema, error) {
+ dbSchema, err := stores.GetDBSchema(ctx, instanceID, databaseName)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get database schema: %q", databaseName)
+ }
+
+ if dbSchema == nil {
+ return nil, nil
+ }
+
+ schemas := dbSchema.GetConfig().GetSchemas()
+ if len(schemas) == 0 {
+ return nil, nil
+ }
+
+ schema := schemas[0]
+ tables := schema.GetTables()
+ for _, table := range tables {
+ if table.GetName() == containerName {
+ return table.GetObjectSchema(), nil
+ }
+ }
+
+ return nil, nil
+}
+
func getSensitivePredicateColumnErrorMessages(sensitiveColumns []base.ColumnResource) string {
var buf bytes.Buffer
_, _ = buf.WriteString("Using sensitive columns in WHERE clause is not allowed: ")