Skip to content

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

chore: support configure masking and exception policy (#7922)

ecmadao92b095c2f2d0
diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.go
index a36e9d0e38..ea89f30af7 100644
--- a/backend/api/v1/org_policy_service.go
+++ b/backend/api/v1/org_policy_service.go
@@ -498,9 +498,6 @@ func validatePolicyPayload(policyType api.PolicyType, policy *v1pb.Policy) error
if rule.Id == "" {
return status.Errorf(codes.InvalidArgument, "masking rule must have ID set")
}
- if rule.MaskingLevel == v1pb.MaskingLevel_MASKING_LEVEL_UNSPECIFIED {
- return status.Errorf(codes.InvalidArgument, "masking rule must have masking level set")
- }
if _, err := common.ValidateMaskingRuleCELExpr(rule.Condition.Expression); err != nil {
return status.Errorf(codes.InvalidArgument, "invalid masking rule expression: %v", err)
}
diff --git a/frontend/src/bbkit/BBTable/BBTable.vue b/frontend/src/bbkit/BBTable/BBTable.vue
index ad9bd3819e..9949a11914 100644
--- a/frontend/src/bbkit/BBTable/BBTable.vue
+++ b/frontend/src/bbkit/BBTable/BBTable.vue
@@ -61,7 +61,7 @@
}
"
>
- <slot name="body" :row-data="item" />
+ <slot name="body" :row-data="item" :section="i" :row="j" />
</tr>
</template>
<template v-else>
@@ -79,21 +79,31 @@
</template>
<template v-else>
<tbody class="bg-normal divide-y divide-block-border">
- <tr
- v-for="(item, index) in dataSource"
- :key="index"
- :class="rowClickable ? 'cursor-pointer hover:bg-gray-200' : ''"
- @click.stop="
- (e) => {
- if (rowClickable) {
- $emit('click-row', 0, index, e);
+ <template v-if="dataSource.length > 0">
+ <tr
+ v-for="(item, index) in dataSource"
+ :key="index"
+ :class="rowClickable ? 'cursor-pointer hover:bg-gray-200' : ''"
+ @click.stop="
+ (e) => {
+ if (rowClickable) {
+ $emit('click-row', 0, index, e);
+ }
}
- }
- "
- >
- <slot name="body" :row-data="item" />
- </tr></tbody
- ></template>
+ "
+ >
+ <slot name="body" :row-data="item" :row="index" />
+ </tr>
+ </template>
+ <template v-else>
+ <tr v-if="showPlaceholder">
+ <td :colspan="columnList.length" class="text-center text-gray-400">
+ <slot name="placeholder">-</slot>
+ </td>
+ </tr>
+ </template>
+ </tbody>
+ </template>
<slot name="footer" />
</table>
</template>
diff --git a/frontend/src/components/ColumnTable.vue b/frontend/src/components/ColumnTable.vue
index 2190ec7161..080a9c5be9 100644
--- a/frontend/src/components/ColumnTable.vue
+++ b/frontend/src/components/ColumnTable.vue
@@ -8,50 +8,37 @@
v-bind="$attrs"
>
<template #body="{ rowData: column }: { rowData: ColumnMetadata }">
- <BBTableCell
- v-if="showSensitiveColumn"
- :left-padding="4"
- class="w-[1%] text-center"
- >
- <!-- width: 1% means as narrow as possible -->
- <div class="flex items-center justify-center">
- <FeatureBadge
- feature="bb.feature.sensitive-data"
- custom-class="mr-2"
- :instance="database.instanceEntity"
- />
- <input
- type="checkbox"
- class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
- :disabled="!allowAdmin"
- :checked="isSensitiveColumn(column)"
- @input="
- toggleSensitiveColumn(
- column,
- ($event.target as HTMLInputElement).checked,
- $event
- )
- "
- />
- </div>
- </BBTableCell>
- <BBTableCell class="w-10" :left-padding="showSensitiveColumn ? 2 : 4">
+ <BBTableCell class="bb-grid-cell">
{{ column.name }}
</BBTableCell>
- <BBTableCell v-if="showClassificationColumn" class="w-14">
- {{ getColumnClassification(column.classification)?.title }}
- <ClassificationLevelBadge
- :level-id="getColumnClassification(column.classification)?.levelId"
- :classification-config="classificationConfig"
- />
+ <BBTableCell v-if="showSensitiveColumn" class="bb-grid-cell">
+ <div class="flex items-center">
+ {{ getMaskingLevelText(column) }}
+ <button
+ v-if="allowAdmin"
+ class="w-5 h-5 p-0.5 hover:bg-gray-300 rounded cursor-pointer"
+ @click.prevent="openSensitiveDrawer(column)"
+ >
+ <heroicons-outline:pencil class="w-4 h-4" />
+ </button>
+ </div>
+ </BBTableCell>
+ <BBTableCell v-if="showClassificationColumn" class="bb-grid-cell">
+ <div class="flex items-center">
+ {{ getColumnClassification(column.classification)?.title ?? "N/A" }}
+ <ClassificationLevelBadge
+ :level-id="getColumnClassification(column.classification)?.levelId"
+ :classification-config="classificationConfig"
+ />
+ </div>
</BBTableCell>
- <BBTableCell class="w-5">
+ <BBTableCell class="bb-grid-cell">
{{ column.type }}
</BBTableCell>
- <BBTableCell class="w-6">
+ <BBTableCell class="bb-grid-cell">
{{ column.default }}
</BBTableCell>
- <BBTableCell class="w-4">
+ <BBTableCell class="bb-grid-cell">
{{ column.nullable }}
</BBTableCell>
<BBTableCell
@@ -60,17 +47,17 @@
engine !== Engine.CLICKHOUSE &&
engine !== Engine.SNOWFLAKE
"
- class="w-6"
+ class="bb-grid-cell"
>
{{ column.characterSet }}
</BBTableCell>
<BBTableCell
v-if="engine !== Engine.CLICKHOUSE && engine !== Engine.SNOWFLAKE"
- class="w-8"
+ class="bb-grid-cell"
>
{{ column.collation }}
</BBTableCell>
- <BBTableCell class="w-16">
+ <BBTableCell class="bb-grid-cell">
{{ column.userComment }}
</BBTableCell>
</template>
@@ -82,24 +69,36 @@
:open="state.showFeatureModal"
@cancel="state.showFeatureModal = false"
/>
+
+ <SensitiveColumnDrawer
+ :show="!!state.activeColumn"
+ :column="{
+ maskData: getColumnMasking(state.activeColumn ?? {} as ColumnMetadata),
+ database: props.database,
+ }"
+ @dismiss="state.activeColumn = undefined"
+ />
</template>
<script lang="ts" setup>
-import { cloneDeep } from "lodash-es";
import { computed, PropType, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { BBTableColumn } from "@/bbkit/types";
import { useCurrentUserV1, useSubscriptionV1Store } from "@/store";
-import { usePolicyV1Store } from "@/store/modules/v1/policy";
import { ComposedDatabase } from "@/types";
import { ColumnMetadata, TableMetadata } from "@/types/proto/store/database";
-import { Engine, MaskingLevel } from "@/types/proto/v1/common";
-import { PolicyType, MaskData } from "@/types/proto/v1/org_policy_service";
+import {
+ Engine,
+ MaskingLevel,
+ maskingLevelToJSON,
+} from "@/types/proto/v1/common";
+import { MaskData } from "@/types/proto/v1/org_policy_service";
import { DataClassificationSetting_DataClassificationConfig } from "@/types/proto/v1/setting_service";
import { hasWorkspacePermissionV1 } from "@/utils";
type LocalState = {
showFeatureModal: boolean;
+ activeColumn?: ColumnMetadata;
};
const props = defineProps({
@@ -211,10 +210,8 @@ const NORMAL_COLUMN_LIST = computed(() => {
},
];
if (showSensitiveColumn.value) {
- columnList.unshift({
- title: t("database.sensitive"),
- center: true,
- nowrap: true,
+ columnList.splice(1, 0, {
+ title: t("settings.sensitive-data.masking-level.self"),
});
}
if (showClassificationColumn.value) {
@@ -246,10 +243,8 @@ const POSTGRES_COLUMN_LIST = computed(() => {
},
];
if (showSensitiveColumn.value) {
- columnList.unshift({
- title: t("database.sensitive"),
- center: true,
- nowrap: true,
+ columnList.splice(1, 0, {
+ title: t("settings.sensitive-data.masking-level.self"),
});
}
if (showClassificationColumn.value) {
@@ -289,62 +284,31 @@ const columnNameList = computed(() => {
}
});
-const isSensitiveColumn = (column: ColumnMetadata) => {
+const getColumnMasking = (column: ColumnMetadata): MaskData => {
return (
- props.maskDataList.findIndex((sensitiveData) => {
+ props.maskDataList.find((sensitiveData) => {
return (
sensitiveData.table === props.table.name &&
- sensitiveData.column === column.name
+ sensitiveData.column === column.name &&
+ sensitiveData.schema === props.schema
);
- }) >= 0
+ }) ?? {
+ schema: props.schema,
+ table: props.table.name,
+ column: column.name,
+ semanticCategoryId: "",
+ maskingLevel: MaskingLevel.MASKING_LEVEL_UNSPECIFIED,
+ }
);
};
-const toggleSensitiveColumn = (
- column: ColumnMetadata,
- on: boolean,
- e: Event
-) => {
+const openSensitiveDrawer = (column: ColumnMetadata) => {
if (!hasSensitiveDataFeature.value || instanceMissingLicense.value) {
state.showFeatureModal = true;
-
- // Revert UI states
- e.preventDefault();
- e.stopPropagation();
- (e.target as HTMLInputElement).checked = !on;
return;
}
- const index = props.maskDataList.findIndex((sensitiveData) => {
- return (
- sensitiveData.table === props.table.name &&
- sensitiveData.column === column.name
- );
- });
- const maskDataList = cloneDeep(props.maskDataList);
- if (on && index < 0) {
- // Turn on sensitive
- maskDataList.push({
- schema: props.schema,
- table: props.table.name,
- column: column.name,
- semanticCategoryId: "",
- maskingLevel: MaskingLevel.FULL,
- });
- } else if (!on && index >= 0) {
- maskDataList.splice(index, 1);
- }
-
- usePolicyV1Store().upsertPolicy({
- parentPath: props.database.name,
- policy: {
- type: PolicyType.MASKING,
- maskingPolicy: {
- maskData: maskDataList,
- },
- },
- updateMask: ["payload"],
- });
+ state.activeColumn = column;
};
const getColumnClassification = (classificationId: string) => {
@@ -353,4 +317,10 @@ const getColumnClassification = (classificationId: string) => {
}
return props.classificationConfig.classification[classificationId];
};
+
+const getMaskingLevelText = (column: ColumnMetadata) => {
+ const masking = getColumnMasking(column);
+ const level = maskingLevelToJSON(masking.maskingLevel);
+ return t(`settings.sensitive-data.masking-level.${level.toLowerCase()}`);
+};
</script>
diff --git a/frontend/src/components/SensitiveData/GlobalMaskingRule.vue b/frontend/src/components/SensitiveData/GlobalMaskingRule.vue
index 7861c85e28..ea18bb5c9a 100644
--- a/frontend/src/components/SensitiveData/GlobalMaskingRule.vue
+++ b/frontend/src/components/SensitiveData/GlobalMaskingRule.vue
@@ -203,7 +203,7 @@ const onConfirm = (rule: MaskingRulePolicy_MaskingRule) => {
mode: "EDIT",
rule,
};
- // TODO: call backend api
+ // TODO(ed): call backend api
pushNotification({
module: "bytebase",
style: "SUCCESS",
diff --git a/frontend/src/components/SensitiveData/GrantAccessDrawer.vue b/frontend/src/components/SensitiveData/GrantAccessDrawer.vue
new file mode 100644
index 0000000000..146c65ef00
--- /dev/null
+++ b/frontend/src/components/SensitiveData/GrantAccessDrawer.vue
@@ -0,0 +1,260 @@
+<template>
+ <Drawer :show="show" @close="onDismiss">
+ <DrawerContent :title="$t('settings.sensitive-data.grant-access')">
+ <div class="divide-block-border space-y-8 w-[60rem] h-full">
+ <SensitiveColumnTable
+ :row-clickable="false"
+ :show-operation="false"
+ :row-selectable="false"
+ :column-list="columnList"
+ :checked-column-index-list="[]"
+ />
+
+ <div class="w-full">
+ <p class="mb-2">{{ $t("settings.sensitive-data.action.self") }}</p>
+ <div class="flex space-x-5">
+ <BBCheckbox
+ v-for="action in ACTIONS"
+ :key="action"
+ :title="
+ $t(
+ `settings.sensitive-data.action.${maskingExceptionPolicy_MaskingException_ActionToJSON(
+ action
+ ).toLowerCase()}`
+ )
+ "
+ :value="state.supportActions.has(action)"
+ @toggle="toggleAction(action, $event)"
+ />
+ </div>
+ </div>
+
+ <div class="w-full">
+ <p class="mb-2">
+ {{ $t("settings.sensitive-data.masking-level.self") }}
+ </p>
+ <MaskingLevelRadioGroup
+ :disabled="false"
+ :level-list="MASKING_LEVELS"
+ :selected="state.maskingLevel"
+ @update="state.maskingLevel = $event"
+ />
+ </div>
+
+ <div class="w-full">
+ <p class="mb-2">{{ $t("common.expiration") }}</p>
+ <NDatePicker
+ v-model:value="state.expirationTimestamp"
+ style="width: 100%"
+ type="datetime"
+ :is-date-disabled="(date: number) => date < Date.now()"
+ clearable
+ />
+ <span v-if="!state.expirationTimestamp" class="textinfolabel">{{
+ $t("settings.sensitive-data.never-expires")
+ }}</span>
+ </div>
+
+ <div class="w-full">
+ <p class="mb-2">
+ {{ $t("common.user") }}
+ </p>
+ <UserSelect
+ v-model:users="state.userUidList"
+ style="width: 100%"
+ :multiple="true"
+ :include-all="false"
+ />
+ </div>
+ </div>
+
+ <template #footer>
+ <div class="w-full flex justify-between items-center">
+ <div class="w-full flex justify-end items-center gap-x-3">
+ <NButton @click.prevent="onDismiss">
+ {{ $t("common.cancel") }}
+ </NButton>
+ <NButton
+ :disabled="submitDisabled || state.processing"
+ type="primary"
+ @click.prevent="onSubmit"
+ >
+ {{ $t("common.confirm") }}
+ </NButton>
+ </div>
+ </div>
+ </template>
+ </DrawerContent>
+ </Drawer>
+</template>
+
+<script lang="ts" setup>
+import { groupBy, uniq } from "lodash-es";
+import { NButton, NDatePicker } from "naive-ui";
+import { computed, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+import { Drawer, DrawerContent } from "@/components/v2";
+import { usePolicyV1Store, useUserStore, pushNotification } from "@/store";
+import { ComposedProject } from "@/types";
+import { Expr } from "@/types/proto/google/type/expr";
+import { MaskingLevel } from "@/types/proto/v1/common";
+import {
+ Policy,
+ PolicyType,
+ PolicyResourceType,
+ MaskingExceptionPolicy_MaskingException,
+ MaskingExceptionPolicy_MaskingException_Action,
+ maskingExceptionPolicy_MaskingException_ActionToJSON,
+} from "@/types/proto/v1/org_policy_service";
+import { SensitiveColumn } from "./types";
+import { getExpressionsForSensitiveColumn } from "./utils";
+
+const props = defineProps<{
+ show: boolean;
+ columnList: SensitiveColumn[];
+}>();
+
+const emit = defineEmits(["dismiss"]);
+
+interface LocalState {
+ userUidList: string[];
+ expirationTimestamp?: number;
+ maskingLevel: MaskingLevel;
+ processing: boolean;
+ supportActions: Set<MaskingExceptionPolicy_MaskingException_Action>;
+}
+
+const ACTIONS = [
+ MaskingExceptionPolicy_MaskingException_Action.EXPORT,
+ MaskingExceptionPolicy_MaskingException_Action.QUERY,
+];
+const MASKING_LEVELS = [MaskingLevel.PARTIAL, MaskingLevel.NONE];
+
+const state = reactive<LocalState>({
+ userUidList: [],
+ maskingLevel: MaskingLevel.PARTIAL,
+ processing: false,
+ supportActions: new Set(ACTIONS),
+});
+
+const policyStore = usePolicyV1Store();
+const userStore = useUserStore();
+const { t } = useI18n();
+
+const resetState = () => {
+ state.expirationTimestamp = undefined;
+ state.maskingLevel = MaskingLevel.PARTIAL;
+ state.supportActions = new Set(ACTIONS);
+ state.userUidList = [];
+};
+
+const onDismiss = () => {
+ emit("dismiss");
+ resetState();
+};
+
+const submitDisabled = computed(() => {
+ if (state.userUidList.length === 0) {
+ return true;
+ }
+ if (state.supportActions.size === 0) {
+ return true;
+ }
+ return false;
+});
+
+const onSubmit = async () => {
+ state.processing = true;
+
+ const groupByProject = groupBy(
+ props.columnList,
+ (item) => item.database.project
+ );
+ try {
+ for (const [project, columnList] of Object.entries(groupByProject)) {
+ if (columnList.length === 0) {
+ continue;
+ }
+ const pendingUpdate = await getPendingUpdatePolicy(
+ columnList[0].database.projectEntity,
+ columnList
+ );
+ await policyStore.upsertPolicy({
+ parentPath: project,
+ policy: pendingUpdate,
+ updateMask: ["payload"],
+ });
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.created"),
+ });
+ onDismiss();
+ } finally {
+ state.processing = false;
+ }
+};
+
+const getPendingUpdatePolicy = async (
+ project: ComposedProject,
+ columnList: SensitiveColumn[]
+): Promise<Partial<Policy>> => {
+ const maskingExceptions: MaskingExceptionPolicy_MaskingException[] = [];
+ const members = uniq(
+ state.userUidList
+ .map((id) => userStore.getUserById(id))
+ .filter((u) => u)
+ .map((user) => `user:${user?.email}`)
+ );
+
+ for (const column of columnList) {
+ const expressions = getExpressionsForSensitiveColumn(column);
+ if (state.expirationTimestamp) {
+ expressions.push(
+ `request.time < timestamp("${new Date(
+ state.expirationTimestamp
+ ).toISOString()}")`
+ );
+ }
+
+ for (const action of state.supportActions.values()) {
+ for (const member of members) {
+ maskingExceptions.push({
+ member,
+ action,
+ maskingLevel: state.maskingLevel,
+ condition: Expr.fromPartial({
+ expression: expressions.join(" && "),
+ }),
+ });
+ }
+ }
+ }
+
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: project.name,
+ policyType: PolicyType.MASKING_EXCEPTION,
+ });
+ const existed = policy?.maskingExceptionPolicy?.maskingExceptions ?? [];
+ return {
+ type: PolicyType.MASKING_EXCEPTION,
+ resourceType: PolicyResourceType.PROJECT,
+ resourceUid: project.uid,
+ maskingExceptionPolicy: {
+ maskingExceptions: [...existed, ...maskingExceptions],
+ },
+ };
+};
+
+const toggleAction = (
+ action: MaskingExceptionPolicy_MaskingException_Action,
+ check: boolean
+) => {
+ if (check) {
+ state.supportActions.add(action);
+ } else {
+ state.supportActions.delete(action);
+ }
+};
+</script>
diff --git a/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue b/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
new file mode 100644
index 0000000000..44951a5f76
--- /dev/null
+++ b/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
@@ -0,0 +1,527 @@
+<template>
+ <Drawer :show="show" @close="$emit('dismiss')">
+ <DrawerContent
+ :title="
+ $t('settings.sensitive-data.column-detail.masking-setting-for-column', {
+ column: column.maskData.column,
+ })
+ "
+ >
+ <div class="divide-block-border divide-y space-y-8 w-[50rem] h-full">
+ <div class="space-y-6">
+ <div class="w-full">
+ <h1 class="mb-2 font-semibold">
+ {{ $t("settings.sensitive-data.masking-level.self") }}
+ </h1>
+ <MaskingLevelRadioGroup
+ :disabled="!hasPermission"
+ :level-list="MASKING_LEVELS"
+ :selected="state.maskingLevel"
+ @update="state.maskingLevel = $event"
+ />
+ </div>
+ <div class="w-full">
+ <h1 class="mb-2 font-semibold">
+ {{ $t("settings.sensitive-data.algorithms.self") }}
+ </h1>
+ <div class="flex flex-col">
+ <span class="textlabel">
+ {{ $t("settings.sensitive-data.algorithms.default") }}
+ </span>
+ <span class="textinfolabel">
+ {{ $t("settings.sensitive-data.algorithms.default-desc") }}
+ </span>
+ </div>
+ </div>
+ </div>
+ <div class="pt-8 space-y-5">
+ <div class="flex justify-between">
+ <div>
+ <h1 class="font-semibold">
+ {{
+ $t("settings.sensitive-data.column-detail.access-user-list")
+ }}
+ </h1>
+ <span class="textinfolabel">{{
+ $t(
+ "settings.sensitive-data.column-detail.access-user-list-desc"
+ )
+ }}</span>
+ </div>
+ <NButton
+ type="primary"
+ :disabled="!hasPermission"
+ @click="state.showGrantAccessDrawer = true"
+ >
+ {{ $t("settings.sensitive-data.grant-access") }}
+ </NButton>
+ </div>
+ <BBTable
+ ref="tableRef"
+ :column-list="tableHeaderList"
+ :data-source="accessUserList"
+ :show-header="true"
+ :left-bordered="true"
+ :right-bordered="true"
+ :top-bordered="true"
+ :bottom-bordered="true"
+ :compact-section="true"
+ :row-clickable="false"
+ >
+ <template
+ #body="{
+ rowData: item,
+ row,
+ }: {
+ rowData: AccessUser,
+ row: number,
+ }"
+ >
+ <BBTableCell class="bb-grid-cell">
+ <div class="flex items-center space-x-2">
+ <UserAvatar size="SMALL" :user="item.user" />
+ <div class="flex flex-col">
+ <router-link
+ :to="`/u/${extractUserUID(item.user.name)}`"
+ class="normal-link"
+ >
+ {{ item.user.title }}
+ </router-link>
+ <span class="textinfolabel">
+ {{ item.user.email }}
+ </span>
+ </div>
+ </div>
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <BBCheckbox
+ :value="
+ item.supportActions.has(
+ MaskingExceptionPolicy_MaskingException_Action.EXPORT
+ )
+ "
+ @toggle="(checked: boolean) => onUpdate(row, (item) => toggleAction(item, MaskingExceptionPolicy_MaskingException_Action.EXPORT, checked))"
+ />
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <BBCheckbox
+ :value="
+ item.supportActions.has(
+ MaskingExceptionPolicy_MaskingException_Action.QUERY
+ )
+ "
+ @toggle="(checked: boolean) => onUpdate(row, (item) => toggleAction(item, MaskingExceptionPolicy_MaskingException_Action.QUERY, checked))"
+ />
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <MaskingLevelDropdown
+ :disabled="!hasPermission"
+ :selected="item.maskingLevel"
+ :level-list="[MaskingLevel.PARTIAL, MaskingLevel.NONE]"
+ @update="(level: MaskingLevel) => onUpdate(row, (item) => item.maskingLevel = level)"
+ />
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <NDatePicker
+ :value="item.expirationTimestamp"
+ style="width: 100%"
+ type="datetime"
+ :is-date-disabled="(date: number) => date < Date.now()"
+ clearable
+ @update:value="(val: number | undefined) => onUpdate(row, (item) => item.expirationTimestamp = val)"
+ />
+ </BBTableCell>
+ <BBTableCell v-if="hasPermission" class="bb-grid-cell">
+ <NPopconfirm @positive-click="onRemove(row)">
+ <template #trigger>
+ <button
+ class="w-5 h-5 p-0.5 hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
+ @click.stop=""
+ >
+ <heroicons-outline:trash class="w-4 h-4" />
+ </button>
+ </template>
+
+ <div class="whitespace-nowrap">
+ {{
+ $t(
+ "settings.sensitive-data.column-detail.remove-user-permission"
+ )
+ }}
+ </div>
+ </NPopconfirm>
+ </BBTableCell>
+ </template>
+ </BBTable>
+ </div>
+ </div>
+
+ <template #footer>
+ <div class="w-full flex justify-between items-center">
+ <div class="w-full flex justify-end items-center gap-x-3">
+ <NButton @click.prevent="$emit('dismiss')">
+ {{ $t("common.cancel") }}
+ </NButton>
+ <NButton
+ :disabled="
+ !hasPermission ||
+ (!state.dirty && !maskingPolicyChanged) ||
+ state.processing
+ "
+ type="primary"
+ @click.prevent="onSubmit"
+ >
+ {{ $t("common.confirm") }}
+ </NButton>
+ </div>
+ </div>
+ </template>
+ </DrawerContent>
+
+ <GrantAccessDrawer
+ :show="state.showGrantAccessDrawer"
+ :column-list="[props.column]"
+ @dismiss="state.showGrantAccessDrawer = false"
+ />
+ </Drawer>
+</template>
+
+<script lang="ts" setup>
+import { NButton, NDatePicker, NPopconfirm } from "naive-ui";
+import { computed, reactive, watch, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import type { BBTableColumn } from "@/bbkit/types";
+import { Drawer, DrawerContent } from "@/components/v2";
+import {
+ usePolicyV1Store,
+ usePolicyByParentAndType,
+ useUserStore,
+ pushNotification,
+ useCurrentUserV1,
+} from "@/store";
+import { getUserId } from "@/store/modules/v1/common";
+import { unknownUser } from "@/types";
+import { Expr } from "@/types/proto/google/type/expr";
+import { User } from "@/types/proto/v1/auth_service";
+import { MaskingLevel, maskingLevelToJSON } from "@/types/proto/v1/common";
+import {
+ Policy,
+ PolicyType,
+ PolicyResourceType,
+ MaskingExceptionPolicy_MaskingException,
+ MaskingExceptionPolicy_MaskingException_Action,
+} from "@/types/proto/v1/org_policy_service";
+import { hasWorkspacePermissionV1, extractUserUID } from "@/utils";
+import { SensitiveColumn } from "./types";
+import { getMaskDataIdentifier, isCurrentColumnException } from "./utils";
+
+interface AccessUser {
+ user: User;
+ supportActions: Set<MaskingExceptionPolicy_MaskingException_Action>;
+ maskingLevel: MaskingLevel;
+ expirationTimestamp?: number;
+ rawExpression: string;
+}
+
+interface LocalState {
+ dirty: boolean;
+ processing: boolean;
+ maskingLevel: MaskingLevel;
+ showGrantAccessDrawer: boolean;
+}
+
+const props = defineProps<{
+ show: boolean;
+ column: SensitiveColumn;
+}>();
+
+const emit = defineEmits(["dismiss"]);
+
+const state = reactive<LocalState>({
+ dirty: false,
+ processing: false,
+ maskingLevel: props.column.maskData.maskingLevel,
+ showGrantAccessDrawer: false,
+});
+
+const MASKING_LEVELS = [
+ MaskingLevel.MASKING_LEVEL_UNSPECIFIED,
+ MaskingLevel.FULL,
+ MaskingLevel.PARTIAL,
+ MaskingLevel.NONE,
+];
+
+const { t } = useI18n();
+const userStore = useUserStore();
+const currentUserV1 = useCurrentUserV1();
+const accessUserList = ref<AccessUser[]>([]);
+const policyStore = usePolicyV1Store();
+
+const policy = usePolicyByParentAndType(
+ computed(() => ({
+ parentPath: props.column.database.project,
+ policyType: PolicyType.MASKING_EXCEPTION,
+ }))
+);
+
+const hasPermission = computed(() => {
+ return hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-sensitive-data",
+ currentUserV1.value.userRole
+ );
+});
+
+const expirationTimeRegex = /request.time < timestamp\("(.+)?"\)/;
+
+const getAccessUsers = (
+ exception: MaskingExceptionPolicy_MaskingException
+): AccessUser => {
+ let expirationTimestamp: number | undefined;
+ const expression = exception.condition?.expression ?? "";
+ const matches = expirationTimeRegex.exec(expression);
+ if (matches) {
+ expirationTimestamp = new Date(matches[1]).getTime();
+ }
+
+ const user = userStore.getUserByIdentifier(exception.member) ?? unknownUser();
+ return {
+ user,
+ maskingLevel: exception.maskingLevel,
+ expirationTimestamp,
+ supportActions: new Set([exception.action]),
+ rawExpression: exception.condition?.expression ?? "",
+ };
+};
+
+const getExceptionIdentifier = (
+ exception: MaskingExceptionPolicy_MaskingException
+): string => {
+ const res: string[] = [
+ `level:"${maskingLevelToJSON(exception.maskingLevel)}"`,
+ ];
+ const expression = exception.condition?.expression ?? "";
+ const matches = expirationTimeRegex.exec(expression);
+ if (matches) {
+ res.push(matches[0]);
+ }
+ return res.join(" && ");
+};
+
+const updateAccessUserList = (policy: Policy | undefined) => {
+ if (!policy || !policy.maskingExceptionPolicy) {
+ return [];
+ }
+
+ // Exec data merge, we will merge data with same expiration time and level.
+ // For example, the exception list and merge exec should be:
+ // - 1. user1, action:export, level:FULL, expires at 2023-09-03
+ // - 2. user1, action:export, level:FULL, expires at 2023-09-04
+ // - 3. user1, action:export, level:PARTIAL, expires at 2023-09-04
+ // - 4. user1, action:query, level:PARTIAL, expires at 2023-09-04
+ // - 5. user1, action:query, level:FULL, expires at 2023-09-03
+ // After the merge we should get:
+ // - 1 & 5 is merged: user1, action:export+action, level:FULL, expires at 2023-09-03
+ // - 2 cannot merge: user1, action:export, level:FULL, expires at 2023-09-04
+ // - 3 & 4 is merged: user1, action:export+action, level:PARTIAL, expires at 2023-09-04
+ const userMap = new Map<string, AccessUser>();
+ for (const exception of policy.maskingExceptionPolicy.maskingExceptions) {
+ if (!isCurrentColumnException(exception, props.column)) {
+ continue;
+ }
+ const identifier = getExceptionIdentifier(exception);
+ const item = getAccessUsers(exception);
+ const id = `${item.user.name}:${identifier}`;
+ const target = userMap.get(id) ?? item;
+ if (userMap.has(id)) {
+ for (const action of item.supportActions) {
+ target.supportActions.add(action);
+ }
+ }
+ userMap.set(id, target);
+ }
+
+ accessUserList.value = [...userMap.values()].sort(
+ (u1, u2) => getUserId(u1.user.name) - getUserId(u2.user.name)
+ );
+};
+
+watch(
+ () => [props.show, policy.value],
+ () => {
+ if (props.show) {
+ state.maskingLevel = props.column.maskData.maskingLevel;
+ }
+ if (props.show && policy.value) {
+ updateAccessUserList(policy.value);
+ }
+ },
+ {
+ immediate: true,
+ deep: true,
+ }
+);
+
+const tableHeaderList = computed(() => {
+ const list: BBTableColumn[] = [
+ {
+ title: t("common.user"),
+ },
+ {
+ title: t("settings.sensitive-data.action.export"),
+ },
+ {
+ title: t("settings.sensitive-data.action.query"),
+ },
+ {
+ title: t("settings.sensitive-data.masking-level.self"),
+ },
+ {
+ title: t("common.expiration"),
+ },
+ ];
+ if (hasPermission.value) {
+ // operation.
+ list.push({
+ title: "",
+ });
+ }
+ return list;
+});
+
+const onRemove = (index: number) => {
+ accessUserList.value.splice(index, 1);
+ state.dirty = true;
+};
+
+const toggleAction = (
+ item: AccessUser,
+ action: MaskingExceptionPolicy_MaskingException_Action,
+ checked: boolean
+) => {
+ if (checked) {
+ item.supportActions.add(action);
+ } else {
+ item.supportActions.delete(action);
+ }
+};
+
+const maskingPolicyChanged = computed(() => {
+ return state.maskingLevel !== props.column.maskData.maskingLevel;
+});
+
+const onUpdate = (index: number, callback: (item: AccessUser) => void) => {
+ const item = accessUserList.value[index];
+ if (!item) {
+ return;
+ }
+ callback(item);
+ state.dirty = true;
+};
+
+const onSubmit = async () => {
+ state.processing = true;
+
+ try {
+ if (maskingPolicyChanged.value) {
+ await upsertMaskingPolicy();
+ }
+ if (state.dirty) {
+ await updateExceptionPolicy();
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ emit("dismiss");
+ } finally {
+ state.processing = false;
+ }
+};
+
+const upsertMaskingPolicy = async () => {
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: props.column.database.name,
+ policyType: PolicyType.MASKING,
+ });
+
+ const maskData = policy?.maskingPolicy?.maskData ?? [];
+ const existedIndex = maskData.findIndex(
+ (data) =>
+ getMaskDataIdentifier(data) ===
+ getMaskDataIdentifier(props.column.maskData)
+ );
+ if (existedIndex < 0) {
+ maskData.push({
+ ...props.column.maskData,
+ maskingLevel: state.maskingLevel,
+ });
+ } else {
+ maskData[existedIndex] = {
+ ...props.column.maskData,
+ maskingLevel: state.maskingLevel,
+ };
+ }
+
+ const upsert: Partial<Policy> = {
+ type: PolicyType.MASKING,
+ resourceType: PolicyResourceType.DATABASE,
+ resourceUid: props.column.database.uid,
+ maskingPolicy: {
+ maskData,
+ },
+ };
+
+ await policyStore.upsertPolicy({
+ parentPath: props.column.database.name,
+ policy: upsert,
+ updateMask: ["payload"],
+ });
+};
+
+const updateExceptionPolicy = async () => {
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: props.column.database.project,
+ policyType: PolicyType.MASKING_EXCEPTION,
+ });
+ if (!policy) {
+ return;
+ }
+
+ const exceptions = (
+ policy.maskingExceptionPolicy?.maskingExceptions ?? []
+ ).filter((exception) => !isCurrentColumnException(exception, props.column));
+
+ for (const accessUser of accessUserList.value) {
+ const expressions = accessUser.rawExpression.split(" && ");
+ const index = expressions.findIndex((exp) =>
+ exp.startsWith("request.time")
+ );
+ if (index >= 0) {
+ if (!accessUser.expirationTimestamp) {
+ expressions.splice(index, 1);
+ } else {
+ expressions[index] = `request.time < timestamp("${new Date(
+ accessUser.expirationTimestamp
+ ).toISOString()}")`;
+ }
+ }
+ for (const action of accessUser.supportActions) {
+ exceptions.push({
+ maskingLevel: accessUser.maskingLevel,
+ action,
+ member: `user:${accessUser.user.email}`,
+ condition: Expr.fromPartial({
+ expression: expressions.join(" && "),
+ }),
+ });
+ }
+ }
+
+ policy.maskingExceptionPolicy = {
+ ...(policy.maskingExceptionPolicy ?? {}),
+ maskingExceptions: exceptions,
+ };
+ await policyStore.updatePolicy(["payload"], policy);
+};
+</script>
diff --git a/frontend/src/components/SensitiveData/SensitiveColumnList.vue b/frontend/src/components/SensitiveData/SensitiveColumnList.vue
deleted file mode 100644
index 662253d155..0000000000
--- a/frontend/src/components/SensitiveData/SensitiveColumnList.vue
+++ /dev/null
@@ -1,292 +0,0 @@
-<template>
- <div class="w-full mt-4 space-y-4">
- <EnvironmentTabFilter
- :environment="state.environment"
- :include-all="true"
- @update:environment="state.environment = $event"
- />
-
- <div class="textinfolabel">
- {{ $t("settings.sensitive-data.description") }}
- </div>
-
- <BBGrid
- v-if="hasSensitiveDataFeature"
- :column-list="COLUMN_LIST"
- :data-source="filteredColumnList"
- class="border"
- @click-row="clickRow"
- >
- <template #item="{ item }: { item: SensitiveColumn }">
- <div class="bb-grid-cell">
- {{ getMaskingLevelText(item.maskData.maskingLevel) }}
- </div>
- <div class="bb-grid-cell">
- {{ item.maskData.column }}
- </div>
- <div class="bb-grid-cell">
- {{
- item.maskData.schema
- ? `${item.maskData.schema}.${item.maskData.table}`
- : item.maskData.table
- }}
- </div>
- <div class="bb-grid-cell">
- <DatabaseV1Name :database="item.database" :link="false" />
- </div>
- <div class="bb-grid-cell gap-x-1">
- <InstanceV1Name
- :instance="item.database.instanceEntity"
- :link="false"
- />
- </div>
- <div class="bb-grid-cell">
- <EnvironmentV1Name
- :environment="item.database.effectiveEnvironmentEntity"
- :link="false"
- />
- </div>
- <div class="bb-grid-cell">
- <ProjectV1Name :project="item.database.projectEntity" :link="false" />
- </div>
- <div class="bb-grid-cell justify-center !px-2">
- <NPopconfirm @positive-click="removeSensitiveColumn(item)">
- <template #trigger>
- <button
- :disabled="!allowAdmin"
- class="w-5 h-5 p-0.5 bg-white hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
- @click.stop=""
- >
- <heroicons-outline:trash />
- </button>
- </template>
-
- <div class="whitespace-nowrap">
- {{ $t("settings.sensitive-data.remove-sensitive-column-tips") }}
- </div>
- </NPopconfirm>
- </div>
- </template>
- </BBGrid>
-
- <template v-else>
- <BBGrid :column-list="COLUMN_LIST" :data-source="[]" class="border" />
- <div class="w-full h-full flex flex-col items-center justify-center">
- <img
- src="../../assets/illustration/no-data.webp"
- class="max-h-[30vh]"
- />
- </div>
- </template>
- </div>
-
- <FeatureModal
- feature="bb.feature.sensitive-data"
- :open="state.showFeatureModal"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { uniq } from "lodash-es";
-import { NPopconfirm } from "naive-ui";
-import { computed, reactive, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import { BBGrid, type BBGridColumn } from "@/bbkit";
-import {
- DatabaseV1Name,
- EnvironmentV1Name,
- InstanceV1Name,
- ProjectV1Name,
-} from "@/components/v2";
-import { featureToRef, useCurrentUserV1, useDatabaseV1Store } from "@/store";
-import {
- usePolicyListByResourceTypeAndPolicyType,
- usePolicyV1Store,
-} from "@/store/modules/v1/policy";
-import { ComposedDatabase, UNKNOWN_ENVIRONMENT_NAME } from "@/types";
-import { MaskingLevel, maskingLevelToJSON } from "@/types/proto/v1/common";
-import {
- PolicyType,
- MaskData,
- PolicyResourceType,
-} from "@/types/proto/v1/org_policy_service";
-import { databaseV1Slug, hasWorkspacePermissionV1 } from "@/utils";
-
-type SensitiveColumn = {
- database: ComposedDatabase;
- maskData: MaskData;
-};
-
-interface LocalState {
- environment: string;
- showFeatureModal: boolean;
- isLoading: boolean;
- sensitiveColumnList: SensitiveColumn[];
-}
-
-const { t } = useI18n();
-const router = useRouter();
-const state = reactive<LocalState>({
- showFeatureModal: false,
- isLoading: false,
- sensitiveColumnList: [],
- environment: UNKNOWN_ENVIRONMENT_NAME,
-});
-const databaseStore = useDatabaseV1Store();
-const hasSensitiveDataFeature = featureToRef("bb.feature.sensitive-data");
-
-const currentUserV1 = useCurrentUserV1();
-const allowAdmin = computed(() => {
- return hasWorkspacePermissionV1(
- "bb.permission.workspace.manage-sensitive-data",
- currentUserV1.value.userRole
- );
-});
-
-const policyList = usePolicyListByResourceTypeAndPolicyType({
- resourceType: PolicyResourceType.DATABASE,
- policyType: PolicyType.MASKING,
- showDeleted: false,
-});
-
-const updateList = async () => {
- state.isLoading = true;
- const distinctDatabaseIdList = uniq(
- policyList.value.map((policy) => policy.resourceUid)
- );
- // Fetch or get all needed databases
- await Promise.all(
- distinctDatabaseIdList.map((databaseId) =>
- databaseStore.getOrFetchDatabaseByUID(databaseId)
- )
- );
-
- const sensitiveColumnList: SensitiveColumn[] = [];
- for (let i = 0; i < policyList.value.length; i++) {
- const policy = policyList.value[i];
- if (!policy.maskingPolicy) {
- continue;
- }
-
- const databaseId = policy.resourceUid;
- const database = await databaseStore.getOrFetchDatabaseByUID(databaseId);
-
- for (const maskData of policy.maskingPolicy.maskData) {
- sensitiveColumnList.push({ database, maskData });
- }
- }
- state.sensitiveColumnList = sensitiveColumnList;
- state.isLoading = false;
-};
-
-watch(policyList, updateList, { immediate: true });
-
-const removeSensitiveColumn = (sensitiveColumn: SensitiveColumn) => {
- if (!hasSensitiveDataFeature.value) {
- state.showFeatureModal = true;
- return;
- }
-
- const { table, column } = sensitiveColumn.maskData;
- const policy = policyList.value.find(
- (policy) => policy.resourceUid == sensitiveColumn.database.uid
- );
- if (!policy) return;
- const maskData = policy.maskingPolicy?.maskData;
- if (!maskData) return;
-
- const index = maskData.findIndex(
- (sensitiveData) =>
- sensitiveData.table === table && sensitiveData.column === column
- );
- if (index >= 0) {
- // mutate the list and the item directly
- // so we don't need to re-fetch the whole list.
- maskData.splice(index, 1);
-
- usePolicyV1Store().updatePolicy(["payload"], {
- name: policy.name,
- type: PolicyType.MASKING,
- resourceType: PolicyResourceType.DATABASE,
- maskingPolicy: {
- maskData,
- },
- });
- }
- updateList();
-};
-
-const COLUMN_LIST = computed((): BBGridColumn[] => [
- {
- title: t("settings.sensitive-data.masking-level.self"),
- width: "minmax(auto, 1fr)",
- },
- {
- title: t("database.column"),
- width: "minmax(auto, 1fr)",
- },
- {
- title: t("common.table"),
- width: "minmax(auto, 1fr)",
- },
- {
- title: t("common.database"),
- width: "minmax(auto, 1fr)",
- },
- {
- title: t("common.instance"),
- width: "minmax(auto, 1fr)",
- },
- {
- title: t("common.environment"),
- width: "minmax(auto, 1fr)",
- },
- {
- title: t("common.project"),
- width: "minmax(auto, 1fr)",
- },
- {
- title: t("common.operation"),
- width: "minmax(auto, 6rem)",
- class: "justify-center !px-2",
- },
-]);
-
-const clickRow = (
- item: SensitiveColumn,
- section: number,
- row: number,
- e: MouseEvent
-) => {
- let url = `/db/${databaseV1Slug(item.database)}?table=${item.maskData.table}`;
- if (item.maskData.schema != "") {
- url += `&schema=${item.maskData.schema}`;
- }
- if (e.ctrlKey || e.metaKey) {
- window.open(url, "_blank");
- } else {
- router.push(url);
- }
-};
-
-const filteredColumnList = computed(() => {
- return state.sensitiveColumnList.filter((column) => {
- if (state.environment === UNKNOWN_ENVIRONMENT_NAME) {
- return true;
- }
- return (
- column.database.effectiveEnvironmentEntity.name === state.environment
- );
- });
-});
-
-const getMaskingLevelText = (maskingLevel: MaskingLevel) => {
- let level = maskingLevelToJSON(maskingLevel);
- if (maskingLevel === MaskingLevel.MASKING_LEVEL_UNSPECIFIED) {
- level = maskingLevelToJSON(MaskingLevel.FULL);
- }
- return t(`settings.sensitive-data.masking-level.${level.toLowerCase()}`);
-};
-</script>
diff --git a/frontend/src/components/SensitiveData/SensitiveColumnView.vue b/frontend/src/components/SensitiveData/SensitiveColumnView.vue
new file mode 100644
index 0000000000..ef3f7ba8f7
--- /dev/null
+++ b/frontend/src/components/SensitiveData/SensitiveColumnView.vue
@@ -0,0 +1,278 @@
+<template>
+ <div class="w-full mt-4 space-y-4">
+ <div class="flex justify-between">
+ <EnvironmentTabFilter
+ :environment="state.environment"
+ :include-all="true"
+ @update:environment="state.environment = $event"
+ />
+ <NButton
+ type="primary"
+ :disabled="
+ state.pendingGrantAccessColumnIndex.length === 0 || !hasPermission
+ "
+ @click="state.showGrantAccessDrawer = true"
+ >
+ {{ $t("settings.sensitive-data.grant-access") }}
+ </NButton>
+ </div>
+
+ <div class="textinfolabel">
+ {{ $t("settings.sensitive-data.description") }}
+ </div>
+
+ <SensitiveColumnTable
+ v-if="hasSensitiveDataFeature"
+ :row-clickable="true"
+ :row-selectable="true"
+ :show-operation="hasPermission && hasSensitiveDataFeature"
+ :column-list="filteredColumnList"
+ :checked-column-index-list="state.pendingGrantAccessColumnIndex"
+ @click="onRowClick"
+ @checked:update="state.pendingGrantAccessColumnIndex = $event"
+ />
+
+ <template v-else>
+ <div class="w-full h-full flex flex-col items-center justify-center">
+ <img
+ src="../../assets/illustration/no-data.webp"
+ class="max-h-[30vh]"
+ />
+ </div>
+ </template>
+ </div>
+
+ <FeatureModal
+ feature="bb.feature.sensitive-data"
+ :open="state.showFeatureModal"
+ @cancel="state.showFeatureModal = false"
+ />
+
+ <GrantAccessDrawer
+ :show="
+ state.showGrantAccessDrawer &&
+ state.pendingGrantAccessColumnIndex.length > 0
+ "
+ :column-list="
+ state.pendingGrantAccessColumnIndex.map((i) => filteredColumnList[i])
+ "
+ @dismiss="
+ () => {
+ state.showGrantAccessDrawer = false;
+ state.pendingGrantAccessColumnIndex = [];
+ }
+ "
+ />
+
+ <SensitiveColumnDrawer
+ v-if="filteredColumnList.length > 0"
+ :show="
+ state.showSensitiveColumnDrawer &&
+ state.pendingGrantAccessColumnIndex.length === 1
+ "
+ :column="
+ filteredColumnList[state.pendingGrantAccessColumnIndex[0]] ??
+ filteredColumnList[0]
+ "
+ @dismiss="
+ () => {
+ state.showSensitiveColumnDrawer = false;
+ state.pendingGrantAccessColumnIndex = [];
+ }
+ "
+ />
+</template>
+
+<script lang="ts" setup>
+import { uniq } from "lodash-es";
+import { computed, reactive, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { useRouter } from "vue-router";
+import {
+ usePolicyListByResourceTypeAndPolicyType,
+ featureToRef,
+ useDatabaseV1Store,
+ useCurrentUserV1,
+ pushNotification,
+ usePolicyV1Store,
+} from "@/store";
+import { UNKNOWN_ENVIRONMENT_NAME } from "@/types";
+import {
+ PolicyType,
+ PolicyResourceType,
+} from "@/types/proto/v1/org_policy_service";
+import { databaseV1Slug, hasWorkspacePermissionV1 } from "@/utils";
+import { SensitiveColumn } from "./types";
+import { getMaskDataIdentifier, isCurrentColumnException } from "./utils";
+
+interface LocalState {
+ environment: string;
+ showFeatureModal: boolean;
+ isLoading: boolean;
+ sensitiveColumnList: SensitiveColumn[];
+ pendingGrantAccessColumnIndex: number[];
+ showGrantAccessDrawer: boolean;
+ showSensitiveColumnDrawer: boolean;
+}
+
+const { t } = useI18n();
+const router = useRouter();
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+ isLoading: false,
+ sensitiveColumnList: [],
+ environment: UNKNOWN_ENVIRONMENT_NAME,
+ pendingGrantAccessColumnIndex: [],
+ showGrantAccessDrawer: false,
+ showSensitiveColumnDrawer: false,
+});
+const databaseStore = useDatabaseV1Store();
+const hasSensitiveDataFeature = featureToRef("bb.feature.sensitive-data");
+const policyStore = usePolicyV1Store();
+
+const policyList = usePolicyListByResourceTypeAndPolicyType({
+ resourceType: PolicyResourceType.DATABASE,
+ policyType: PolicyType.MASKING,
+ showDeleted: false,
+});
+
+const currentUserV1 = useCurrentUserV1();
+const hasPermission = computed(() => {
+ return hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-sensitive-data",
+ currentUserV1.value.userRole
+ );
+});
+
+const updateList = async () => {
+ state.isLoading = true;
+ const distinctDatabaseIdList = uniq(
+ policyList.value.map((policy) => policy.resourceUid)
+ );
+ // Fetch or get all needed databases
+ await Promise.all(
+ distinctDatabaseIdList.map((databaseId) =>
+ databaseStore.getOrFetchDatabaseByUID(databaseId)
+ )
+ );
+
+ const sensitiveColumnList: SensitiveColumn[] = [];
+ for (let i = 0; i < policyList.value.length; i++) {
+ const policy = policyList.value[i];
+ if (!policy.maskingPolicy) {
+ continue;
+ }
+
+ const databaseId = policy.resourceUid;
+ const database = await databaseStore.getOrFetchDatabaseByUID(databaseId);
+
+ for (const maskData of policy.maskingPolicy.maskData) {
+ sensitiveColumnList.push({ database, maskData });
+ }
+ }
+ state.sensitiveColumnList = sensitiveColumnList;
+ state.isLoading = false;
+};
+
+watch(policyList, updateList, { immediate: true, deep: true });
+
+const removeSensitiveColumn = async (sensitiveColumn: SensitiveColumn) => {
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: sensitiveColumn.database.name,
+ policyType: PolicyType.MASKING,
+ });
+ if (!policy) return;
+
+ const maskData = policy.maskingPolicy?.maskData;
+ if (!maskData) return;
+
+ const index = maskData.findIndex(
+ (sensitiveData) =>
+ getMaskDataIdentifier(sensitiveData) ===
+ getMaskDataIdentifier(sensitiveColumn.maskData)
+ );
+ if (index >= 0) {
+ // mutate the list and the item directly
+ // so we don't need to re-fetch the whole list.
+ maskData.splice(index, 1);
+
+ await policyStore.updatePolicy(["payload"], {
+ name: policy.name,
+ type: PolicyType.MASKING,
+ resourceType: PolicyResourceType.DATABASE,
+ maskingPolicy: {
+ maskData,
+ },
+ });
+ await removeMaskingExceptions(sensitiveColumn);
+ }
+};
+
+const removeMaskingExceptions = async (sensitiveColumn: SensitiveColumn) => {
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: sensitiveColumn.database.project,
+ policyType: PolicyType.MASKING_EXCEPTION,
+ });
+ if (!policy) {
+ return;
+ }
+
+ const exceptions = (
+ policy.maskingExceptionPolicy?.maskingExceptions ?? []
+ ).filter(
+ (exception) => !isCurrentColumnException(exception, sensitiveColumn)
+ );
+
+ policy.maskingExceptionPolicy = {
+ ...(policy.maskingExceptionPolicy ?? {}),
+ maskingExceptions: exceptions,
+ };
+ await policyStore.updatePolicy(["payload"], policy);
+};
+
+const onColumnRemove = async (column: SensitiveColumn) => {
+ await removeSensitiveColumn(column);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+};
+
+const onRowClick = async (
+ item: SensitiveColumn,
+ row: number,
+ action: "VIEW" | "DELETE" | "EDIT"
+) => {
+ switch (action) {
+ case "VIEW": {
+ let url = `/db/${databaseV1Slug(item.database)}?table=${
+ item.maskData.table
+ }`;
+ if (item.maskData.schema != "") {
+ url += `&schema=${item.maskData.schema}`;
+ }
+ router.push(url);
+ break;
+ }
+ case "DELETE":
+ await onColumnRemove(item);
+ break;
+ case "EDIT":
+ state.pendingGrantAccessColumnIndex = [row];
+ state.showSensitiveColumnDrawer = true;
+ break;
+ }
+};
+
+const filteredColumnList = computed(() => {
+ return state.sensitiveColumnList.filter((column) => {
+ if (state.environment === UNKNOWN_ENVIRONMENT_NAME) {
+ return true;
+ }
+ return (
+ column.database.effectiveEnvironmentEntity.name === state.environment
+ );
+ });
+});
+</script>
diff --git a/frontend/src/components/SensitiveData/components/MaskingLevelDropdown.vue b/frontend/src/components/SensitiveData/components/MaskingLevelDropdown.vue
new file mode 100644
index 0000000000..1600c11851
--- /dev/null
+++ b/frontend/src/components/SensitiveData/components/MaskingLevelDropdown.vue
@@ -0,0 +1,53 @@
+<template>
+ <NDropdown
+ trigger="click"
+ :options="options"
+ :disabled="disabled"
+ @select="$emit('update', $event)"
+ >
+ <div class="flex items-center">
+ {{
+ $t(
+ `settings.sensitive-data.masking-level.${maskingLevelToJSON(
+ selected
+ ).toLowerCase()}`
+ )
+ }}
+ <button
+ class="w-5 h-5 p-0.5 hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
+ >
+ <heroicons-solid:chevron-up-down class="w-4 h-auto text-gray-400" />
+ </button>
+ </div>
+ </NDropdown>
+</template>
+
+<script lang="ts" setup>
+import { type DropdownOption, NDropdown } from "naive-ui";
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { MaskingLevel, maskingLevelToJSON } from "@/types/proto/v1/common";
+
+const props = defineProps<{
+ disabled: boolean;
+ selected: MaskingLevel;
+ levelList: MaskingLevel[];
+}>();
+
+defineEmits<{
+ (event: "update", level: MaskingLevel): void;
+}>();
+
+const { t } = useI18n();
+
+const options = computed((): DropdownOption[] => {
+ return props.levelList.map((level) => ({
+ label: t(
+ `settings.sensitive-data.masking-level.${maskingLevelToJSON(
+ level
+ ).toLowerCase()}`
+ ),
+ key: level,
+ }));
+});
+</script>
diff --git a/frontend/src/components/SensitiveData/components/MaskingLevelRadioGroup.vue b/frontend/src/components/SensitiveData/components/MaskingLevelRadioGroup.vue
new file mode 100644
index 0000000000..33f9310eaa
--- /dev/null
+++ b/frontend/src/components/SensitiveData/components/MaskingLevelRadioGroup.vue
@@ -0,0 +1,47 @@
+<template>
+ <div class="flex space-x-5">
+ <label
+ v-for="maskLevel in levelList"
+ :key="maskLevel"
+ class="radio space-x-2"
+ :class="disabled && 'cursor-not-allowed'"
+ >
+ <input
+ :disabled="disabled"
+ :checked="selected === maskLevel"
+ :name="maskingLevelToJSON(maskLevel)"
+ type="radio"
+ class="btn"
+ :value="maskLevel"
+ @input="
+ () => {
+ $emit('update', maskLevel);
+ }
+ "
+ />
+ <span class="text-sm font-medium text-main whitespace-nowrap">
+ {{
+ $t(
+ `settings.sensitive-data.masking-level.${maskingLevelToJSON(
+ maskLevel
+ ).toLowerCase()}`
+ )
+ }}
+ </span>
+ </label>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { MaskingLevel, maskingLevelToJSON } from "@/types/proto/v1/common";
+
+defineProps<{
+ disabled: boolean;
+ selected: MaskingLevel;
+ levelList: MaskingLevel[];
+}>();
+
+defineEmits<{
+ (event: "update", level: MaskingLevel): void;
+}>();
+</script>
diff --git a/frontend/src/components/SensitiveData/MaskingRuleConfig.vue b/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
similarity index 100%
rename from frontend/src/components/SensitiveData/MaskingRuleConfig.vue
rename to frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
diff --git a/frontend/src/components/SensitiveData/components/SensitiveColumnTable.vue b/frontend/src/components/SensitiveData/components/SensitiveColumnTable.vue
new file mode 100644
index 0000000000..12759e54eb
--- /dev/null
+++ b/frontend/src/components/SensitiveData/components/SensitiveColumnTable.vue
@@ -0,0 +1,244 @@
+<template>
+ <BBTable
+ ref="tableRef"
+ :column-list="tableHeaderList"
+ :data-source="columnList"
+ :show-header="true"
+ :custom-header="true"
+ :left-bordered="true"
+ :right-bordered="true"
+ :top-bordered="true"
+ :bottom-bordered="true"
+ :compact-section="true"
+ :row-clickable="rowClickable"
+ @click-row="clickTableRow"
+ >
+ <template #header>
+ <th
+ v-for="(column, index) in tableHeaderList"
+ :key="index"
+ scope="col"
+ class="pl-2 py-2 text-left text-xs font-medium text-gray-500 tracking-wider capitalize"
+ :class="[column.center && 'text-center pr-2']"
+ >
+ <template v-if="index === 0 && rowSelectable">
+ <input
+ v-if="columnList.length > 0"
+ type="checkbox"
+ class="ml-2 h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
+ :checked="allSelectionState.checked"
+ :indeterminate="allSelectionState.indeterminate"
+ :disabled="false"
+ @input="selectAll(($event.target as HTMLInputElement).checked)"
+ />
+ </template>
+ <template v-else>{{ $t(column.title) }}</template>
+ </th>
+ </template>
+ <template
+ #body="{ rowData: item, row }: { rowData: SensitiveColumn, row: number }"
+ >
+ <BBTableCell v-if="rowSelectable" class="w-[1%]">
+ <!-- width: 1% means as narrow as possible -->
+ <input
+ type="checkbox"
+ class="ml-2 h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
+ :checked="checkedColumnIndex.has(row)"
+ @click.stop=""
+ @input="
+ toggleColumnChecked(
+ row,
+ ($event.target as HTMLInputElement).checked,
+ $event
+ )
+ "
+ />
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ {{ getMaskingLevelText(item.maskData.maskingLevel) }}
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ {{ item.maskData.column }}
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ {{
+ item.maskData.schema
+ ? `${item.maskData.schema}.${item.maskData.table}`
+ : item.maskData.table
+ }}
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <DatabaseV1Name :database="item.database" :link="false" />
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <InstanceV1Name
+ :instance="item.database.instanceEntity"
+ :link="false"
+ />
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <EnvironmentV1Name
+ :environment="item.database.effectiveEnvironmentEntity"
+ :link="false"
+ />
+ </BBTableCell>
+ <BBTableCell class="bb-grid-cell">
+ <ProjectV1Name :project="item.database.projectEntity" :link="false" />
+ </BBTableCell>
+ <BBTableCell
+ v-if="showOperation"
+ class="bb-grid-cell justify-center !px-2 space-x-2"
+ >
+ <button
+ class="w-5 h-5 p-0.5 hover:bg-gray-300 rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
+ @click.stop="$emit('click', item, row, 'EDIT')"
+ >
+ <heroicons-outline:pencil class="w-4 h-4" />
+ </button>
+ <NPopconfirm @positive-click="$emit('click', item, row, 'DELETE')">
+ <template #trigger>
+ <button
+ class="w-5 h-5 p-0.5 hover:bg-gray-300 rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
+ @click.stop=""
+ >
+ <heroicons-outline:trash class="w-4 h-4" />
+ </button>
+ </template>
+
+ <div class="whitespace-nowrap">
+ {{ $t("settings.sensitive-data.remove-sensitive-column-tips") }}
+ </div>
+ </NPopconfirm>
+ </BBTableCell>
+ </template>
+ </BBTable>
+</template>
+
+<script lang="ts" setup>
+import { NPopconfirm } from "naive-ui";
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import type { BBTableColumn } from "@/bbkit/types";
+import {
+ DatabaseV1Name,
+ EnvironmentV1Name,
+ InstanceV1Name,
+ ProjectV1Name,
+} from "@/components/v2";
+import { MaskingLevel, maskingLevelToJSON } from "@/types/proto/v1/common";
+import { SensitiveColumn } from "../types";
+
+const props = defineProps<{
+ showOperation: boolean;
+ rowClickable: boolean;
+ rowSelectable: boolean;
+ columnList: SensitiveColumn[];
+ checkedColumnIndexList: number[];
+}>();
+
+const emit = defineEmits<{
+ (
+ event: "click",
+ item: SensitiveColumn,
+ row: number,
+ action: "VIEW" | "DELETE" | "EDIT" | "SELECT"
+ ): void;
+ (event: "checked:update", list: number[]): void;
+}>();
+
+const { t } = useI18n();
+const checkedColumnIndex = ref<Set<number>>(
+ new Set(props.checkedColumnIndexList)
+);
+
+watch(
+ () => props.columnList,
+ () => (checkedColumnIndex.value = new Set()),
+ { deep: true }
+);
+watch(
+ () => props.checkedColumnIndexList,
+ (val) => (checkedColumnIndex.value = new Set(val)),
+ { deep: true }
+);
+
+const getMaskingLevelText = (maskingLevel: MaskingLevel) => {
+ const level = maskingLevelToJSON(maskingLevel);
+ return t(`settings.sensitive-data.masking-level.${level.toLowerCase()}`);
+};
+
+const toggleColumnChecked = (index: number, on: boolean, e: Event) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ if (on) {
+ checkedColumnIndex.value.add(index);
+ } else {
+ checkedColumnIndex.value.delete(index);
+ }
+
+ emit("checked:update", [...checkedColumnIndex.value]);
+};
+
+const tableHeaderList = computed(() => {
+ const list: BBTableColumn[] = [
+ {
+ title: t("settings.sensitive-data.masking-level.self"),
+ },
+ {
+ title: t("database.column"),
+ },
+ {
+ title: t("common.table"),
+ },
+ {
+ title: t("common.database"),
+ },
+ {
+ title: t("common.instance"),
+ },
+ {
+ title: t("common.environment"),
+ },
+ {
+ title: t("common.project"),
+ },
+ ];
+ if (props.showOperation) {
+ list.push({
+ title: t("common.operation"),
+ });
+ }
+ if (props.rowSelectable) {
+ list.unshift({
+ title: "",
+ });
+ }
+ return list;
+});
+
+const allSelectionState = computed(() => {
+ const checked = checkedColumnIndex.value.size === props.columnList.length;
+ const indeterminate =
+ !checked &&
+ props.columnList.some((_, i) => checkedColumnIndex.value.has(i));
+
+ return {
+ checked,
+ indeterminate,
+ };
+});
+
+const selectAll = (check: boolean): void => {
+ if (!check) {
+ checkedColumnIndex.value = new Set([]);
+ } else {
+ checkedColumnIndex.value = new Set(props.columnList.map((_, i) => i));
+ }
+ emit("checked:update", [...checkedColumnIndex.value]);
+};
+
+const clickTableRow = function (_: number, row: number) {
+ emit("click", props.columnList[row], row, "VIEW");
+};
+</script>
diff --git a/frontend/src/components/SensitiveData/components/utils.ts b/frontend/src/components/SensitiveData/components/utils.ts
new file mode 100644
index 0000000000..233e7eb78c
--- /dev/null
+++ b/frontend/src/components/SensitiveData/components/utils.ts
@@ -0,0 +1,83 @@
+import { uniq } from "lodash-es";
+import type { SelectOption } from "naive-ui";
+import {
+ Factor,
+ Operator,
+ EqualityOperatorList,
+ CollectionOperatorList,
+} from "@/plugins/cel";
+import {
+ useEnvironmentV1Store,
+ useInstanceV1List,
+ useProjectV1ListByCurrentUser,
+} from "@/store";
+import {
+ extractEnvironmentResourceName,
+ extractInstanceResourceName,
+ extractProjectResourceName,
+} from "@/utils";
+
+export const factorList: Factor[] = [
+ "environment_id", // using `environment.resource_id`
+ "project_id", // using `project.resource_id`
+ "instance_id", // using `instance.resource_id`
+ "database_name",
+ "table_name",
+];
+
+const getEnvironmentIdOptions = () => {
+ const environmentList = useEnvironmentV1Store().getEnvironmentList();
+ return environmentList.map<SelectOption>((env) => {
+ return {
+ label: env.title,
+ value: extractEnvironmentResourceName(env.name),
+ };
+ });
+};
+
+const getInstanceIdOptions = () => {
+ const { instanceList } = useInstanceV1List(false);
+ return instanceList.value.map<SelectOption>((ins) => {
+ return {
+ label: ins.title,
+ value: extractInstanceResourceName(ins.name),
+ };
+ });
+};
+
+const getProjectIdOptions = () => {
+ const { projectList } = useProjectV1ListByCurrentUser();
+ return projectList.value.map<SelectOption>((proj) => ({
+ label: proj.title,
+ value: extractProjectResourceName(proj.name),
+ }));
+};
+
+export const getFactorOptionsMap = () => {
+ return factorList.reduce((map, factor) => {
+ let options: SelectOption[] = [];
+ switch (factor) {
+ case "environment_id":
+ options = getEnvironmentIdOptions();
+ break;
+ case "instance_id":
+ options = getInstanceIdOptions();
+ break;
+ case "project_id":
+ options = getProjectIdOptions();
+ break;
+ }
+ map.set(factor, options);
+ return map;
+ }, new Map<Factor, SelectOption[]>());
+};
+
+export const factorSupportDropdown: Factor[] = [
+ "environment_id",
+ "instance_id",
+ "project_id",
+];
+
+export const factorOperatorOverrideMap = new Map<Factor, Operator[]>([
+ ["project_id", uniq([...EqualityOperatorList, ...CollectionOperatorList])],
+]);
diff --git a/frontend/src/components/SensitiveData/index.ts b/frontend/src/components/SensitiveData/index.ts
index 8805a73f55..5268b2fe4c 100644
--- a/frontend/src/components/SensitiveData/index.ts
+++ b/frontend/src/components/SensitiveData/index.ts
@@ -1,4 +1,4 @@
import GlobalMaskingRule from "./GlobalMaskingRule.vue";
-import SensitiveColumnList from "./SensitiveColumnList.vue";
+import SensitiveColumnView from "./SensitiveColumnView.vue";
-export { SensitiveColumnList, GlobalMaskingRule };
+export { SensitiveColumnView, GlobalMaskingRule };
diff --git a/frontend/src/components/SensitiveData/types.ts b/frontend/src/components/SensitiveData/types.ts
new file mode 100644
index 0000000000..4424d9d744
--- /dev/null
+++ b/frontend/src/components/SensitiveData/types.ts
@@ -0,0 +1,7 @@
+import { ComposedDatabase } from "@/types";
+import { MaskData } from "@/types/proto/v1/org_policy_service";
+
+export interface SensitiveColumn {
+ database: ComposedDatabase;
+ maskData: MaskData;
+}
diff --git a/frontend/src/components/SensitiveData/utils.ts b/frontend/src/components/SensitiveData/utils.ts
index 233e7eb78c..1a265c01f6 100644
--- a/frontend/src/components/SensitiveData/utils.ts
+++ b/frontend/src/components/SensitiveData/utils.ts
@@ -1,83 +1,43 @@
-import { uniq } from "lodash-es";
-import type { SelectOption } from "naive-ui";
import {
- Factor,
- Operator,
- EqualityOperatorList,
- CollectionOperatorList,
-} from "@/plugins/cel";
-import {
- useEnvironmentV1Store,
- useInstanceV1List,
- useProjectV1ListByCurrentUser,
-} from "@/store";
-import {
- extractEnvironmentResourceName,
- extractInstanceResourceName,
- extractProjectResourceName,
-} from "@/utils";
-
-export const factorList: Factor[] = [
- "environment_id", // using `environment.resource_id`
- "project_id", // using `project.resource_id`
- "instance_id", // using `instance.resource_id`
- "database_name",
- "table_name",
-];
-
-const getEnvironmentIdOptions = () => {
- const environmentList = useEnvironmentV1Store().getEnvironmentList();
- return environmentList.map<SelectOption>((env) => {
- return {
- label: env.title,
- value: extractEnvironmentResourceName(env.name),
- };
- });
-};
+ MaskData,
+ MaskingExceptionPolicy_MaskingException,
+} from "@/types/proto/v1/org_policy_service";
+import { extractInstanceResourceName } from "@/utils";
+import { SensitiveColumn } from "./types";
-const getInstanceIdOptions = () => {
- const { instanceList } = useInstanceV1List(false);
- return instanceList.value.map<SelectOption>((ins) => {
- return {
- label: ins.title,
- value: extractInstanceResourceName(ins.name),
- };
- });
+export const getMaskDataIdentifier = (maskData: MaskData): string => {
+ return `${maskData.schema}.${maskData.table}.${maskData.column}`;
};
-const getProjectIdOptions = () => {
- const { projectList } = useProjectV1ListByCurrentUser();
- return projectList.value.map<SelectOption>((proj) => ({
- label: proj.title,
- value: extractProjectResourceName(proj.name),
- }));
-};
-
-export const getFactorOptionsMap = () => {
- return factorList.reduce((map, factor) => {
- let options: SelectOption[] = [];
- switch (factor) {
- case "environment_id":
- options = getEnvironmentIdOptions();
- break;
- case "instance_id":
- options = getInstanceIdOptions();
- break;
- case "project_id":
- options = getProjectIdOptions();
- break;
+export const isCurrentColumnException = (
+ exception: MaskingExceptionPolicy_MaskingException,
+ sensitiveColumn: SensitiveColumn
+): boolean => {
+ const expression = exception.condition?.expression ?? "";
+ const matches = getExpressionsForSensitiveColumn(sensitiveColumn);
+ for (const match of matches) {
+ if (!expression.includes(match)) {
+ return false;
}
- map.set(factor, options);
- return map;
- }, new Map<Factor, SelectOption[]>());
+ }
+ return true;
};
-export const factorSupportDropdown: Factor[] = [
- "environment_id",
- "instance_id",
- "project_id",
-];
-
-export const factorOperatorOverrideMap = new Map<Factor, Operator[]>([
- ["project_id", uniq([...EqualityOperatorList, ...CollectionOperatorList])],
-]);
+export const getExpressionsForSensitiveColumn = (
+ sensitiveColumn: SensitiveColumn
+): string[] => {
+ const expressions = [
+ `resource.database_name == "${sensitiveColumn.database.databaseName}"`,
+ `resource.instance_id == "${extractInstanceResourceName(
+ sensitiveColumn.database.instanceEntity.name
+ )}"`,
+ `resource.table_name == "${sensitiveColumn.maskData.table}"`,
+ `resource.column_name == "${sensitiveColumn.maskData.column}"`,
+ ];
+ if (sensitiveColumn.maskData.schema) {
+ expressions.push(
+ `resource.schema_name == "${sensitiveColumn.maskData.schema}"`
+ );
+ }
+ return expressions;
+};
diff --git a/frontend/src/components/TableDetailDrawer.vue b/frontend/src/components/TableDetailDrawer.vue
index aeb676b7c0..682cbca0e8 100644
--- a/frontend/src/components/TableDetailDrawer.vue
+++ b/frontend/src/components/TableDetailDrawer.vue
@@ -1,19 +1,9 @@
<template>
- <NDrawer
- :show="true"
- width="auto"
- :auto-focus="false"
- :close-on-esc="true"
- @update:show="(show: boolean) => !show && emit('dismiss')"
- >
- <NDrawerContent
- class="w-[calc(100vw-256px)]"
- :title="$t('database.table-detail')"
- :closable="true"
- >
+ <Drawer :show="show" @close="$emit('dismiss')">
+ <DrawerContent :title="$t('database.table-detail')">
<div
v-if="table"
- class="flex-1 overflow-auto focus:outline-none"
+ class="flex-1 overflow-auto focus:outline-none w-[calc(100vw-256px)]"
tabindex="0"
>
<main class="flex-1 relative pb-8 overflow-y-auto">
@@ -191,15 +181,19 @@
</div>
</main>
</div>
- </NDrawerContent>
- </NDrawer>
+ </DrawerContent>
+ </Drawer>
</template>
<script lang="ts" setup>
-import { NDrawer, NDrawerContent } from "naive-ui";
-import { computed, onMounted, ref } from "vue";
+import { computed, watch, ref } from "vue";
import { useRouter } from "vue-router";
-import { DatabaseV1Name, InstanceV1Name } from "@/components/v2";
+import {
+ DatabaseV1Name,
+ InstanceV1Name,
+ Drawer,
+ DrawerContent,
+} from "@/components/v2";
import {
useCurrentUserV1,
useDatabaseV1Store,
@@ -222,13 +216,14 @@ import { SQLEditorButtonV1 } from "./DatabaseDetail";
import IndexTable from "./IndexTable.vue";
const props = defineProps<{
+ show: boolean;
// Format: /databases/:databaseName
databaseName: string;
schemaName: string;
tableName: string;
}>();
-const emit = defineEmits(["dismiss"]);
+defineEmits(["dismiss"]);
const router = useRouter();
const databaseV1Store = useDatabaseV1Store();
@@ -284,18 +279,26 @@ const getTableName = (tableName: string) => {
return tableName;
};
-onMounted(() => {
- const schemaList = dbSchemaStore.getSchemaList(database.value.name);
- const schema = schemaList.find((schema) => schema.name === props.schemaName);
- if (schema) {
- table.value = schema.tables.find((table) => table.name === props.tableName);
- }
- if (!table.value) {
- router.replace({
- name: "error.404",
- });
+watch(
+ () => props.tableName,
+ (tableName) => {
+ if (!tableName) {
+ return;
+ }
+ const schemaList = dbSchemaStore.getSchemaList(database.value.name);
+ const schema = schemaList.find(
+ (schema) => schema.name === props.schemaName
+ );
+ if (schema) {
+ table.value = schema.tables.find((table) => table.name === tableName);
+ }
+ if (!table.value) {
+ router.replace({
+ name: "error.404",
+ });
+ }
}
-});
+);
const sensitiveDataPolicy = usePolicyByParentAndType(
computed(() => ({
diff --git a/frontend/src/components/TableTable.vue b/frontend/src/components/TableTable.vue
index 8c92a6adf3..736a40077f 100644
--- a/frontend/src/components/TableTable.vue
+++ b/frontend/src/components/TableTable.vue
@@ -58,10 +58,10 @@
</BBTable>
<TableDetailDrawer
- v-if="state.selectedTableName"
+ :show="!!state.selectedTableName"
:database-name="database.name"
:schema-name="schemaName"
- :table-name="state.selectedTableName"
+ :table-name="state.selectedTableName ?? ''"
@dismiss="state.selectedTableName = undefined"
/>
</template>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index c1106a47b3..ff7acf5ad6 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -620,12 +620,32 @@
"global-masking-rule": "Global Masking Rule",
"data-feature": "Data Feature",
"add-rule": "Add rule",
+ "grant-access": "Grant Access",
+ "never-expires": "Never expires",
+ "column-detail": {
+ "masking-setting-for-column": "Masking Setting for \"{column}\"",
+ "access-user-list": "Access User List",
+ "access-user-list-desc": "Users granted to access de-masked data.",
+ "remove-user-permission": "Remove user permission?",
+ "remove-sensitive-warning": "The will expose the column."
+ },
+ "algorithms": {
+ "self": "Masking Algorithm",
+ "default": "Default",
+ "default-desc": "Use *** as data mask"
+ },
"masking-level": {
"self": "Masking Level",
"selet-level": "Select level",
+ "masking_level_unspecified": "Follow global masking rules",
"none": "None",
"partial": "Partial",
"full": "Full"
+ },
+ "action": {
+ "self": "Action",
+ "query": "Query",
+ "export": "Export"
}
},
"access-control": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index b839cba872..cd5f3060a9 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -619,12 +619,32 @@
"global-masking-rule": "Regla de enmascaramiento global",
"data-feature": "Característica de datos",
"add-rule": "Agregar regla",
+ "grant-access": "Autorizará el acceso",
+ "never-expires": "Nunca expira",
+ "column-detail": {
+ "masking-setting-for-column": "Configuración de enmascaramiento para \"{columna}\"",
+ "access-user-list": "Acceder a la lista de usuarios",
+ "access-user-list-desc": "Usuarios autorizados a acceder a datos desenmascarados.",
+ "remove-user-permission": "¿Quitar el permiso del usuario?",
+ "remove-sensitive-warning": "Expondrá la columna."
+ },
+ "algorithms": {
+ "self": "Algoritmo de enmascaramiento",
+ "default": "Por defecto",
+ "default-desc": "Utilice *** como máscara de datos"
+ },
"masking-level": {
"self": "Nivel de enmascaramiento",
"selet-level": "Selecciona el nivel",
+ "masking_level_unspecified": "Siga las reglas globales de enmascaramiento",
"none": "Ninguna",
"partial": "Parcial",
"full": "Llena"
+ },
+ "action": {
+ "self": "Acción",
+ "query": "Consulta",
+ "export": "Exportar"
}
},
"access-control": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index f8c29fbb09..86bb372c6d 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -618,11 +618,31 @@
"global-masking-rule": "全局脱敏规则",
"data-feature": "数据特征",
"add-rule": "添加规则",
+ "grant-access": "授权访问",
+ "never-expires": "无过期时间",
+ "column-detail": {
+ "masking-setting-for-column": "\"{column}\" 脱敏设置",
+ "access-user-list": "用户访问列表",
+ "access-user-list-desc": "被授权的用户可以访问非脱敏的原始数据。",
+ "remove-user-permission": "删除该用户权限?",
+ "remove-sensitive-warning": "该数据会被设置为明文,不再脱敏。"
+ },
+ "algorithms": {
+ "self": "脱敏算法",
+ "default": "默认",
+ "default-desc": "使用 *** 为数据遮挡"
+ },
"masking-level": {
"self": "脱敏程度",
+ "masking_level_unspecified": "遵循全局配置",
"none": "明文",
"partial": "半脱敏",
"full": "全脱敏"
+ },
+ "action": {
+ "self": "操作类型",
+ "query": "查询",
+ "export": "导出"
}
},
"access-control": {
diff --git a/frontend/src/plugins/cel/types/factor.ts b/frontend/src/plugins/cel/types/factor.ts
index 7b2712769d..381dc9c15c 100644
--- a/frontend/src/plugins/cel/types/factor.ts
+++ b/frontend/src/plugins/cel/types/factor.ts
@@ -36,6 +36,9 @@ export const StringFactorList = [
"resource.instance_id", // using `instance.resourceId`
"resource.database_name",
"resource.table_name",
+ // Masking
+ "resource.column_name",
+ "resource.schema_name",
] as const;
export type StringFactor = typeof StringFactorList[number];
diff --git a/frontend/src/views/SettingWorkspaceSensitiveData.vue b/frontend/src/views/SettingWorkspaceSensitiveData.vue
index d84fac47bb..425ae1cdf7 100644
--- a/frontend/src/views/SettingWorkspaceSensitiveData.vue
+++ b/frontend/src/views/SettingWorkspaceSensitiveData.vue
@@ -15,14 +15,14 @@
>
<div class="mt-5">
<BBTabPanel :active="state.selectedIndex === 0">
- <SensitiveColumnList />
+ <SensitiveColumnView />
</BBTabPanel>
<BBTabPanel :active="state.selectedIndex === 1">
<GlobalMaskingRule />
</BBTabPanel>
</div>
</BBTab>
- <SensitiveColumnList v-else />
+ <SensitiveColumnView v-else />
</div>
</template>
@@ -32,7 +32,7 @@ import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import type { BBTabItem } from "@/bbkit/types";
import {
- SensitiveColumnList,
+ SensitiveColumnView,
GlobalMaskingRule,
} from "@/components/SensitiveData";
import { featureToRef } from "@/store";