Skip to content

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

chore: allow select any databases or tables for masking exception (#14166)

ecmadao48097599dcf4
diff --git a/backend/api/v1/masking_evaluator.go b/backend/api/v1/masking_evaluator.go
index 944a169f09..d81be331cc 100644
--- a/backend/api/v1/masking_evaluator.go
+++ b/backend/api/v1/masking_evaluator.go
@@ -8,6 +8,7 @@ import (
"github.com/google/cel-go/cel"
"github.com/pkg/errors"
+ "google.golang.org/genproto/googleapis/type/expr"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/store"
@@ -234,7 +235,7 @@ func (m *maskingLevelEvaluator) evaluateMaskingLevelOfColumn(databaseMessage *st
"time": time.Now(),
},
}
- hit, err := evaluateMaskingExceptionPolicyCondition(filteredMaskingException.Condition.Expression, maskingExceptionAttributes)
+ hit, err := evaluateMaskingExceptionPolicyCondition(filteredMaskingException.Condition, maskingExceptionAttributes)
if err != nil {
return storepb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED, errors.Wrapf(err, "failed to evaluate masking exception policy condition")
}
@@ -266,8 +267,9 @@ func getClassificationLevelOfColumn(columnClassificationID string, classificatio
return *classification.LevelId
}
-func evaluateMaskingExceptionPolicyCondition(expression string, attributes map[string]any) (bool, error) {
- if expression == "" {
+func evaluateMaskingExceptionPolicyCondition(expression *expr.Expr, attributes map[string]any) (bool, error) {
+ // nil expression means allow to access all databases
+ if expression == nil || expression.Expression == "" {
return true, nil
}
maskingExceptionPolicyEnv, err := cel.NewEnv(
@@ -277,7 +279,7 @@ func evaluateMaskingExceptionPolicyCondition(expression string, attributes map[s
if err != nil {
return false, errors.Wrapf(err, "failed to create CEL environment for masking exception policy")
}
- ast, issues := maskingExceptionPolicyEnv.Compile(expression)
+ ast, issues := maskingExceptionPolicyEnv.Compile(expression.Expression)
if issues != nil && issues.Err() != nil {
return false, errors.Wrapf(issues.Err(), "failed to get the ast of CEL program for masking exception policy")
}
diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.go
index 82b744d673..08defc7c1c 100644
--- a/backend/api/v1/org_policy_service.go
+++ b/backend/api/v1/org_policy_service.go
@@ -525,7 +525,7 @@ func validatePolicyPayload(policyType api.PolicyType, policy *v1pb.Policy) error
if exception.MaskingLevel == v1pb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED {
return status.Errorf(codes.InvalidArgument, "masking exception must have masking level set")
}
- if _, err := common.ValidateMaskingExceptionCELExpr(exception.Condition.Expression); err != nil {
+ if _, err := common.ValidateMaskingExceptionCELExpr(exception.Condition); err != nil {
return status.Error(codes.InvalidArgument, fmt.Sprintf("invalid masking exception expression: %v", err))
}
if err := validateMember(exception.Member); err != nil {
diff --git a/backend/common/cel.go b/backend/common/cel.go
index 7f601ed611..d55b30a6cd 100644
--- a/backend/common/cel.go
+++ b/backend/common/cel.go
@@ -156,30 +156,20 @@ func ValidateMaskingRuleCELExpr(expr string) (cel.Program, error) {
}
// ValidateMaskingExceptionCELExpr validates masking exception expr.
-func ValidateMaskingExceptionCELExpr(expr string) (cel.Program, error) {
- e, err := cel.NewEnv(
- MaskingExceptionPolicyCELAttributes...,
- )
- if err != nil {
- return nil, status.Error(codes.Internal, err.Error())
- }
- ast, issues := e.Compile(expr)
- if issues != nil && issues.Err() != nil {
- return nil, status.Error(codes.InvalidArgument, issues.Err().Error())
- }
- prog, err := e.Program(ast)
- if err != nil {
- return nil, status.Error(codes.InvalidArgument, err.Error())
- }
- return prog, nil
+func ValidateMaskingExceptionCELExpr(expression *expr.Expr) (cel.Program, error) {
+ return validateCELExpr(expression, MaskingExceptionPolicyCELAttributes)
}
func ValidateProjectMemberCELExpr(expression *expr.Expr) (cel.Program, error) {
+ return validateCELExpr(expression, IAMPolicyConditionCELAttributes)
+}
+
+func validateCELExpr(expression *expr.Expr, conditionCELAttributes []cel.EnvOption) (cel.Program, error) {
if expression == nil || expression.Expression == "" {
return nil, nil
}
e, err := cel.NewEnv(
- IAMPolicyConditionCELAttributes...,
+ conditionCELAttributes...,
)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
diff --git a/frontend/src/components/SensitiveData/GrantAccessDrawer.vue b/frontend/src/components/SensitiveData/GrantAccessDrawer.vue
index 06a9159ac3..e05207532f 100644
--- a/frontend/src/components/SensitiveData/GrantAccessDrawer.vue
+++ b/frontend/src/components/SensitiveData/GrantAccessDrawer.vue
@@ -15,8 +15,6 @@
:project-name="projectName"
:required-feature="'bb.feature.sensitive-data'"
:include-cloumn="true"
- :allow-select-all="false"
- :disabled="true"
/>
</div>
@@ -122,7 +120,10 @@ import {
} from "@/types/proto/v1/org_policy_service";
import MaskingLevelRadioGroup from "./components/MaskingLevelRadioGroup.vue";
import type { SensitiveColumn } from "./types";
-import { getExpressionsForDatabaseResource } from "./utils";
+import {
+ getExpressionsForDatabaseResource,
+ convertSensitiveColumnToDatabaseResource,
+} from "./utils";
const props = defineProps<{
columnList: SensitiveColumn[];
@@ -151,12 +152,9 @@ const state = reactive<LocalState>({
maskingLevel: MaskingLevel.PARTIAL,
processing: false,
supportActions: new Set(ACTIONS),
- databaseResources: props.columnList.map((col) => ({
- databaseName: col.database.name,
- schema: col.maskData.schema,
- table: col.maskData.table,
- column: col.maskData.column,
- })),
+ databaseResources: props.columnList.map(
+ convertSensitiveColumnToDatabaseResource
+ ),
});
const policyStore = usePolicyV1Store();
@@ -167,6 +165,8 @@ const resetState = () => {
state.maskingLevel = MaskingLevel.PARTIAL;
state.supportActions = new Set(ACTIONS);
state.memberList = [];
+ state.databaseResources = undefined;
+ state.processing = false;
};
const onDismiss = () => {
@@ -233,7 +233,8 @@ const getPendingUpdatePolicy = async (
action,
maskingLevel: state.maskingLevel,
condition: Expr.fromPartial({
- expression: expressions.join(" && "),
+ expression:
+ expressions.length > 0 ? expressions.join(" && ") : undefined,
}),
});
} else {
diff --git a/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue b/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
index a72fe800b0..5b4511e76e 100644
--- a/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
+++ b/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
@@ -124,126 +124,16 @@
{{ $t("settings.sensitive-data.grant-access") }}
</NButton>
</div>
- <BBGrid
- :column-list="gridColumnList"
- :data-source="accessUserList"
- :row-clickable="false"
- class="border compact"
- >
- <template #item="{ item, row }: AccessUserRow">
- <div v-if="item.type === 'user'" class="bb-grid-cell gap-x-2">
- <UserAvatar size="SMALL" :user="item.user" />
- <div class="flex flex-col">
- <router-link
- :to="{
- name: WORKSPACE_ROUTE_USER_PROFILE,
- params: {
- principalEmail: item.user!.email,
- },
- }"
- class="normal-link"
- >
- {{ item.user!.title }}
- </router-link>
- <span class="textinfolabel">
- {{ item.user!.email }}
- </span>
- </div>
- </div>
- <div v-else class="bb-grid-cell gap-x-1">
- <GroupNameCell :group="item.group!" />
- </div>
- <div class="bb-grid-cell">
- <NCheckbox
- :checked="
- item.supportActions.has(
- MaskingExceptionPolicy_MaskingException_Action.EXPORT
- )
- "
- :disabled="!hasPermission || state.processing"
- @update-checked="
- onAccessControlUpdate(row, (item) =>
- toggleAction(
- item,
- MaskingExceptionPolicy_MaskingException_Action.EXPORT,
- $event
- )
- )
- "
- />
- </div>
- <div class="bb-grid-cell">
- <NCheckbox
- :checked="
- item.supportActions.has(
- MaskingExceptionPolicy_MaskingException_Action.QUERY
- )
- "
- :disabled="!hasPermission || state.processing"
- @update:checked="
- onAccessControlUpdate(row, (item) =>
- toggleAction(
- item,
- MaskingExceptionPolicy_MaskingException_Action.QUERY,
- $event
- )
- )
- "
- />
- </div>
- <div class="bb-grid-cell">
- <MaskingLevelDropdown
- :disabled="!hasPermission || state.processing"
- :level="item.maskingLevel"
- :level-list="[MaskingLevel.PARTIAL, MaskingLevel.NONE]"
- @update:level="
- onAccessControlUpdate(
- row,
- (item) => (item.maskingLevel = $event)
- )
- "
- />
- </div>
- <div class="bb-grid-cell">
- <NDatePicker
- :value="item.expirationTimestamp"
- style="width: 100%"
- type="datetime"
- :is-date-disabled="(date: number) => date < Date.now()"
- clearable
- :disabled="!hasPermission || state.processing"
- @update:value="
- (val: number | undefined) =>
- onAccessControlUpdate(
- row,
- (item) => (item.expirationTimestamp = val)
- )
- "
- />
- </div>
- <div v-if="hasPermission" class="bb-grid-cell">
- <NPopconfirm @positive-click="onRemove(row)">
- <template #trigger>
- <MiniActionButton
- tag="div"
- :disabled="!hasPermission || state.processing"
- @click.stop=""
- >
- <TrashIcon class="w-4 h-4" />
- </MiniActionButton>
- </template>
-
- <div class="whitespace-nowrap">
- {{
- $t(
- "settings.sensitive-data.column-detail.remove-user-permission"
- )
- }}
- </div>
- </NPopconfirm>
- </div>
- </template>
- </BBGrid>
+ <NDataTable
+ size="small"
+ :columns="accessUserTableColumns"
+ :data="accessUserList"
+ :row-key="(row: AccessUser) => row.key"
+ :bordered="true"
+ :striped="true"
+ :max-height="'calc(100vh - 15rem)'"
+ virtual-scroll
+ />
</div>
</div>
@@ -267,11 +157,12 @@
/>
</template>
-<script lang="ts" setup>
+<script lang="tsx" setup>
import { computedAsync } from "@vueuse/core";
import { orderBy } from "lodash-es";
import { TrashIcon } from "lucide-vue-next";
-import type { SelectOption } from "naive-ui";
+import { NDataTable } from "naive-ui";
+import type { SelectOption, DataTableColumn } from "naive-ui";
import {
NSelect,
NButton,
@@ -281,8 +172,7 @@ import {
} from "naive-ui";
import { computed, reactive, watch, ref } from "vue";
import { useI18n } from "vue-i18n";
-import { BBGrid } from "@/bbkit";
-import type { BBGridColumn, BBGridRow } from "@/bbkit/types";
+import { RouterLink } from "vue-router";
import { useSemanticType } from "@/components/SensitiveData/useSemanticType";
import GroupNameCell from "@/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue";
import { Drawer, DrawerContent, MiniActionButton } from "@/components/v2";
@@ -326,6 +216,7 @@ import { getMaskDataIdentifier, isCurrentColumnException } from "./utils";
interface AccessUser {
type: "user" | "group";
+ key: string;
group?: Group;
user?: User;
supportActions: Set<MaskingExceptionPolicy_MaskingException_Action>;
@@ -334,8 +225,6 @@ interface AccessUser {
rawExpression: string;
}
-type AccessUserRow = BBGridRow<AccessUser>;
-
interface LocalState {
dirty: boolean;
processing: boolean;
@@ -414,6 +303,7 @@ const getAccessUsers = (
const access: AccessUser = {
type: "user",
+ key: exception.member,
maskingLevel: exception.maskingLevel,
expirationTimestamp,
supportActions: new Set([exception.action]),
@@ -446,14 +336,11 @@ const getMemberBinding = (access: AccessUser): string => {
const getExceptionIdentifier = (
exception: MaskingExceptionPolicy_MaskingException
): string => {
+ const expression = exception.condition?.expression ?? "";
const res: string[] = [
`level:"${maskingLevelToJSON(exception.maskingLevel)}"`,
+ expression,
];
- const expression = exception.condition?.expression ?? "";
- const matches = expirationTimeRegex.exec(expression);
- if (matches) {
- res.push(matches[0]);
- }
return res.join(" && ");
};
@@ -484,6 +371,7 @@ const updateAccessUserList = (policy: Policy | undefined) => {
continue;
}
const id = `${getMemberBinding(item)}:${identifier}`;
+ item.key = id;
const target = memberMap.get(id) ?? item;
if (memberMap.has(id)) {
for (const action of item.supportActions) {
@@ -510,6 +398,183 @@ const updateAccessUserList = (policy: Policy | undefined) => {
);
};
+const accessUserTableColumns = computed(
+ (): DataTableColumn<AccessUser & { hide?: boolean }>[] => {
+ return [
+ {
+ type: "expand",
+ expandable: (_: AccessUser) => true,
+ renderExpand: (item: AccessUser) => {
+ const expressions = item.rawExpression.split(" && ");
+ if (
+ expressions.length === 0 ||
+ (expressions.length === 1 &&
+ expressions[0].startsWith("request.time"))
+ ) {
+ expressions.push("all databases");
+ }
+
+ return (
+ <ul class="list-disc pl-6 textinfolabel">
+ {expressions.map((expression, i) => (
+ <li key={`${item.key}.${i}`}>{expression}</li>
+ ))}
+ </ul>
+ );
+ },
+ },
+ {
+ key: "member",
+ title: t("common.members"),
+ resizable: true,
+ render: (item: AccessUser) => {
+ if (item.type === "group") {
+ return <GroupNameCell group={item.group!} />;
+ }
+
+ return (
+ <div class="flex items-center gap-x-2">
+ <UserAvatar size="SMALL" user={item.user} />
+ <div class="flex flex-col">
+ <RouterLink
+ to={{
+ name: WORKSPACE_ROUTE_USER_PROFILE,
+ params: {
+ principalEmail: item.user!.email,
+ },
+ }}
+ class="normal-link"
+ >
+ {item.user!.title}
+ </RouterLink>
+ <span class="textinfolabel">{item.user!.email}</span>
+ </div>
+ </div>
+ );
+ },
+ },
+ {
+ key: "export",
+ title: t("settings.sensitive-data.action.export"),
+ width: "5rem",
+ render: (item: AccessUser, row: number) => {
+ return (
+ <NCheckbox
+ checked={item.supportActions.has(
+ MaskingExceptionPolicy_MaskingException_Action.EXPORT
+ )}
+ disabled={!hasPermission.value || state.processing}
+ onUpdateChecked={(e) =>
+ onAccessControlUpdate(row, (item) =>
+ toggleAction(
+ item,
+ MaskingExceptionPolicy_MaskingException_Action.EXPORT,
+ e
+ )
+ )
+ }
+ />
+ );
+ },
+ },
+ {
+ key: "query",
+ title: t("settings.sensitive-data.action.query"),
+ width: "5rem",
+ render: (item: AccessUser, row: number) => {
+ return (
+ <NCheckbox
+ checked={item.supportActions.has(
+ MaskingExceptionPolicy_MaskingException_Action.QUERY
+ )}
+ disabled={!hasPermission.value || state.processing}
+ onUpdate:checked={(e) =>
+ onAccessControlUpdate(row, (item) =>
+ toggleAction(
+ item,
+ MaskingExceptionPolicy_MaskingException_Action.QUERY,
+ e
+ )
+ )
+ }
+ />
+ );
+ },
+ },
+ {
+ key: "level",
+ title: t("settings.sensitive-data.masking-level.self"),
+ render: (item: AccessUser, row: number) => {
+ return (
+ <MaskingLevelDropdown
+ disabled={!hasPermission.value || state.processing}
+ level={item.maskingLevel}
+ levelList={[MaskingLevel.PARTIAL, MaskingLevel.NONE]}
+ onUpdate:level={(e) =>
+ onAccessControlUpdate(row, (item) => (item.maskingLevel = e))
+ }
+ />
+ );
+ },
+ },
+ {
+ key: "expire",
+ title: t("common.expiration"),
+ render: (item: AccessUser, row: number) => {
+ return (
+ <NDatePicker
+ value={item.expirationTimestamp}
+ style={"width: 100%"}
+ type={"datetime"}
+ isDateDisabled={(date: number) => date < Date.now()}
+ clearable={true}
+ disabled={!hasPermission.value || state.processing}
+ onUpdate:value={(val: number | undefined) =>
+ onAccessControlUpdate(
+ row,
+ (item) => (item.expirationTimestamp = val)
+ )
+ }
+ />
+ );
+ },
+ },
+ {
+ key: "operation",
+ title: "",
+ hide: !hasPermission.value,
+ width: "4rem",
+ render: (_: AccessUser, row: number) => {
+ return (
+ <NPopconfirm onPositiveClick={() => onRemove(row)}>
+ {{
+ trigger: () => {
+ return (
+ <MiniActionButton
+ disabled={!hasPermission.value || state.processing}
+ >
+ {{
+ default: () => <TrashIcon class="w-4 h-4" />,
+ }}
+ </MiniActionButton>
+ );
+ },
+ default: () => (
+ <div class="whitespace-nowrap">
+ {t(
+ "settings.sensitive-data.column-detail.remove-user-permission"
+ )}
+ </div>
+ ),
+ }}
+ </NPopconfirm>
+ );
+ },
+ },
+ ].filter((column) => !column.hide) as DataTableColumn<AccessUser>[];
+ }
+);
+
watch(
() => [props.show, policy.value],
() => {
@@ -530,39 +595,6 @@ watch(
}
);
-const gridColumnList = computed(() => {
- const columns: BBGridColumn[] = [
- {
- title: t("common.members"),
- width: "minmax(min-content, auto)",
- },
- {
- title: t("settings.sensitive-data.action.export"),
- width: "minmax(min-content, auto)",
- },
- {
- title: t("settings.sensitive-data.action.query"),
- width: "minmax(min-content, auto)",
- },
- {
- title: t("settings.sensitive-data.masking-level.self"),
- width: "minmax(min-content, auto)",
- },
- {
- title: t("common.expiration"),
- width: "minmax(min-content, auto)",
- },
- ];
- if (hasPermission.value) {
- // operation.
- columns.push({
- title: "",
- width: "minmax(min-content, auto)",
- });
- }
- return columns;
-});
-
const onRemove = async (index: number) => {
accessUserList.value.splice(index, 1);
state.dirty = true;
diff --git a/frontend/src/components/SensitiveData/components/MaskingLevelDropdown.vue b/frontend/src/components/SensitiveData/components/MaskingLevelDropdown.vue
index 3ab2e13120..7af93331da 100644
--- a/frontend/src/components/SensitiveData/components/MaskingLevelDropdown.vue
+++ b/frontend/src/components/SensitiveData/components/MaskingLevelDropdown.vue
@@ -2,6 +2,7 @@
<NSelect
:value="level"
:options="options"
+ :disabled="disabled"
@update:value="$emit('update:level', $event)"
/>
</template>
@@ -15,6 +16,7 @@ import type { MaskingLevel } from "@/types/proto/v1/common";
import { maskingLevelToJSON } from "@/types/proto/v1/common";
const props = defineProps<{
+ disabled?: boolean;
level: MaskingLevel;
levelList: MaskingLevel[];
}>();
diff --git a/frontend/src/components/SensitiveData/utils.ts b/frontend/src/components/SensitiveData/utils.ts
index 094430844a..970b4db596 100644
--- a/frontend/src/components/SensitiveData/utils.ts
+++ b/frontend/src/components/SensitiveData/utils.ts
@@ -10,23 +10,32 @@ export const getMaskDataIdentifier = (maskData: MaskData): string => {
return `${maskData.schema}.${maskData.table}.${maskData.column}`;
};
+export const convertSensitiveColumnToDatabaseResource = (
+ sensitiveColumn: SensitiveColumn
+): DatabaseResource => ({
+ databaseName: sensitiveColumn.database.name,
+ schema: sensitiveColumn.maskData.schema,
+ table: sensitiveColumn.maskData.table,
+ column: sensitiveColumn.maskData.column,
+});
+
export const isCurrentColumnException = (
exception: MaskingExceptionPolicy_MaskingException,
sensitiveColumn: SensitiveColumn
): boolean => {
const expression = exception.condition?.expression ?? "";
- const matches = getExpressionsForDatabaseResource({
- databaseName: sensitiveColumn.database.name,
- schema: sensitiveColumn.maskData.schema,
- table: sensitiveColumn.maskData.table,
- column: sensitiveColumn.maskData.column,
- });
- for (const match of matches) {
- if (!expression.includes(match)) {
- return false;
- }
+ if (!expression) {
+ // no expression means can access all databases.
+ return true;
}
- return true;
+ const databaseExpression = expression
+ .split(" && ")
+ .filter((expr) => !expr.startsWith("request.time"))
+ .join(" && ");
+ const matches = getExpressionsForDatabaseResource(
+ convertSensitiveColumnToDatabaseResource(sensitiveColumn)
+ );
+ return matches.join(" && ").includes(databaseExpression);
};
export const getExpressionsForDatabaseResource = (
@@ -36,8 +45,8 @@ export const getExpressionsForDatabaseResource = (
databaseResource.databaseName
);
const expressions = [
- `resource.database_name == "${resourceName.databaseName}"`,
`resource.instance_id == "${resourceName.instanceName}"`,
+ `resource.database_name == "${resourceName.databaseName}"`,
];
if (databaseResource.schema) {
expressions.push(`resource.schema_name == "${databaseResource.schema}"`);
diff --git a/frontend/src/components/v2/Button/MiniActionButton.vue b/frontend/src/components/v2/Button/MiniActionButton.vue
index ce0700edb2..9e87948fb2 100644
--- a/frontend/src/components/v2/Button/MiniActionButton.vue
+++ b/frontend/src/components/v2/Button/MiniActionButton.vue
@@ -1,5 +1,5 @@
<template>
- <NButton quaternary size="tiny" style="--n-padding: 4px">
+ <NButton quaternary size="tiny" style="--n-padding: 4px" :disabled="disabled">
<template #icon>
<slot />
</template>
@@ -11,4 +11,8 @@
<script setup lang="ts">
import { NButton } from "naive-ui";
+
+defineProps<{
+ disabled?: boolean;
+}>();
</script>
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index b657259dd0..23616a342e 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3818,4 +3818,4 @@
"setup": {
"self": "设置"
}
-}
+}
\ No newline at end of file
diff --git a/frontend/src/types/member.ts b/frontend/src/types/member.ts
index c02f04a2a9..187eb44f57 100644
--- a/frontend/src/types/member.ts
+++ b/frontend/src/types/member.ts
@@ -1,5 +1,6 @@
// IAM related resource definition.
export interface DatabaseResource {
+ // the database full name
databaseName: string;
schema?: string;
table?: string;