Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support upload classification (#9708)
ecmadaoc355bfd44a44
diff --git a/frontend/src/components/SchemaTemplate/ClassificationTree.vue b/frontend/src/components/SchemaTemplate/ClassificationTree.vuenew file mode 100644index 0000000000..efddfd9c5a--- /dev/null+++ b/frontend/src/components/SchemaTemplate/ClassificationTree.vue@@ -0,0 +1,148 @@+<template>+ <div class="divide-block-border space-y-4 h-full">+ <SearchBox+ v-model:value="state.searchText"+ style="max-width: 100%"+ :placeholder="$t('schema-template.classification.search')"+ />++ <NTree+ ref="treeRef"+ block-line+ style="height: 100%; user-select: none"+ :data="treeData"+ :multiple="false"+ :selectable="true"+ :pattern="state.searchText"+ :show-irrelevant-nodes="false"+ :expand-on-click="true"+ :render-suffix="renderSuffix"+ :render-label="renderLabel"+ :node-props="nodeProps"+ :virtual-scroll="false"+ :theme-overrides="{ nodeHeight: '21px' }"+ />+ </div>+</template>++<script lang="ts" setup>+import { NTree, TreeOption } from "naive-ui";+import { computed, reactive, h } from "vue";+import { DataClassificationSetting_DataClassificationConfig } from "@/types/proto/v1/setting_service";+import { getHighlightHTMLByKeyWords } from "@/utils";+import ClassificationLevelBadge from "./ClassificationLevelBadge.vue";++const props = defineProps<{+ classificationConfig: DataClassificationSetting_DataClassificationConfig;+}>();++const emit = defineEmits<{+ (event: "apply", classificationId: string): void;+}>();++interface LocalState {+ searchText: string;+}++interface TreeNode extends TreeOption {+ key: string;+ label: string;+ levelId?: string;+ children?: TreeNode[];+}++interface ClassificationMap {+ [key: string]: {+ id: string;+ label: string;+ levelId?: string;+ children: ClassificationMap;+ };+}++const state = reactive<LocalState>({+ searchText: "",+});++const nodeProps = ({ option }: { option: TreeOption }) => {+ return {+ onClick(e: MouseEvent) {+ if (!option.isLeaf || !option.key) {+ return;+ }+ emit("apply", option.key as string);+ },+ };+};++const sortClassification = (+ item1: { id: string },+ item2: { id: string }+): number => {+ const n1 = Number(item1.id.split("-").join(""));+ const n2 = Number(item2.id.split("-").join(""));+ return n1 - n2;+};++const treeData = computed((): TreeNode[] => {+ const classifications = Object.values(+ props.classificationConfig.classification+ ).sort(sortClassification);++ const classificationMap: ClassificationMap = {};+ for (const classification of classifications) {+ const ids = classification.id.split("-");+ let tmp = classificationMap;+ for (let i = 0; i < ids.length - 1; i++) {+ tmp = tmp[ids.slice(0, i + 1).join("-")].children;+ if (!tmp) {+ break;+ }+ }+ if (tmp) {+ tmp[classification.id] = {+ id: classification.id,+ label: classification.title,+ levelId: classification.levelId,+ children: {},+ };+ }+ }+ return getTreeNodeList(classificationMap);+});++const getTreeNodeList = (classificationMap: ClassificationMap): TreeNode[] => {+ return Object.values(classificationMap)+ .sort(sortClassification)+ .map((item) => {+ const children = getTreeNodeList(item.children);+ return {+ key: item.id,+ label: `${item.id} ${item.label}`,+ levelId: item.levelId,+ isLeaf: children.length === 0,+ children,+ };+ });+};++const renderSuffix = ({ option }: { option: TreeOption }) => {+ const node = option as any as TreeNode;+ if (!node.levelId) {+ return null;+ }++ return h(ClassificationLevelBadge, {+ showText: false,+ classification: node.key,+ classificationConfig: props.classificationConfig,+ });+};++const renderLabel = ({ option }: { option: TreeOption }) => {+ const node = option as any as TreeNode;+ return h("span", {+ innerHTML: getHighlightHTMLByKeyWords(node.label, state.searchText),+ });+};+</script>diff --git a/frontend/src/components/SchemaTemplate/SelectClassificationDrawer.vue b/frontend/src/components/SchemaTemplate/SelectClassificationDrawer.vueindex c5a7c0e987..83180e063b 100644--- a/frontend/src/components/SchemaTemplate/SelectClassificationDrawer.vue+++ b/frontend/src/components/SchemaTemplate/SelectClassificationDrawer.vue@@ -1,28 +1,10 @@<template><Drawer :show="show" @close="$emit('dismiss')"><DrawerContent :title="$t('schema-template.classification.select')">- <div class="divide-block-border space-y-8 w-[25rem] h-full">- <SearchBox- v-model:value="state.searchText"- style="max-width: 100%"- :placeholder="$t('schema-template.classification.search')"- />-- <NTree- ref="treeRef"- block-line- style="height: 100%; user-select: none"- :data="treeData"- :multiple="false"- :selectable="true"- :pattern="state.searchText"- :show-irrelevant-nodes="false"- :expand-on-click="true"- :render-suffix="renderSuffix"- :render-label="renderLabel"- :node-props="nodeProps"- :virtual-scroll="true"- :theme-overrides="{ nodeHeight: '21px' }"+ <div class="w-[25rem] h-full">+ <ClassificationTree+ :classification-config="classificationConfig"+ @apply="onApply"/></div>@@ -40,14 +22,11 @@</template><script lang="ts" setup>-import { NTree, TreeOption } from "naive-ui";-import { computed, reactive, h } from "vue";+import ClassificationTree from "@/components/SchemaTemplate/ClassificationTree.vue";import { Drawer, DrawerContent } from "@/components/v2";import { DataClassificationSetting_DataClassificationConfig } from "@/types/proto/v1/setting_service";-import { getHighlightHTMLByKeyWords } from "@/utils";-import ClassificationLevelBadge from "./ClassificationLevelBadge.vue";-const props = defineProps<{+defineProps<{show: boolean;classificationConfig: DataClassificationSetting_DataClassificationConfig;}>();@@ -57,110 +36,8 @@ const emit = defineEmits<{(event: "apply", classificationId: string): void;}>();-interface LocalState {- searchText: string;-}--interface TreeNode extends TreeOption {- key: string;- label: string;- levelId?: string;- children?: TreeNode[];-}--interface ClassificationMap {- [key: string]: {- id: string;- label: string;- levelId?: string;- children: ClassificationMap;- };-}--const state = reactive<LocalState>({- searchText: "",-});--const nodeProps = ({ option }: { option: TreeOption }) => {- return {- onClick(e: MouseEvent) {- if (!option.isLeaf || !option.key) {- return;- }- emit("apply", option.key as string);- emit("dismiss");- },- };-};--const sortClassification = (- item1: { id: string },- item2: { id: string }-): number => {- const n1 = Number(item1.id.split("-").join(""));- const n2 = Number(item2.id.split("-").join(""));- return n1 - n2;-};--const treeData = computed((): TreeNode[] => {- const classifications = Object.values(- props.classificationConfig.classification- ).sort(sortClassification);-- const classificationMap: ClassificationMap = {};- for (const classification of classifications) {- const ids = classification.id.split("-");- let tmp = classificationMap;- for (let i = 0; i < ids.length - 1; i++) {- tmp = tmp[ids.slice(0, i + 1).join("-")].children;- if (!tmp) {- break;- }- }- if (tmp) {- tmp[classification.id] = {- id: classification.id,- label: classification.title,- levelId: classification.levelId,- children: {},- };- }- }- return getTreeNodeList(classificationMap);-});--const getTreeNodeList = (classificationMap: ClassificationMap): TreeNode[] => {- return Object.values(classificationMap)- .sort(sortClassification)- .map((item) => {- const children = getTreeNodeList(item.children);- return {- key: item.id,- label: `${item.id} ${item.label}`,- levelId: item.levelId,- isLeaf: children.length === 0,- children,- };- });-};--const renderSuffix = ({ option }: { option: TreeOption }) => {- const node = option as any as TreeNode;- if (!node.levelId) {- return null;- }-- return h(ClassificationLevelBadge, {- showText: false,- classification: node.key,- classificationConfig: props.classificationConfig,- });-};--const renderLabel = ({ option }: { option: TreeOption }) => {- const node = option as any as TreeNode;- return h("span", {- innerHTML: getHighlightHTMLByKeyWords(node.label, state.searchText),- });+const onApply = (classificationId: string) => {+ emit("apply", classificationId);+ emit("dismiss");};</script>diff --git a/frontend/src/components/SensitiveData/ClassificationView.vue b/frontend/src/components/SensitiveData/ClassificationView.vuenew file mode 100644index 0000000000..35797321de--- /dev/null+++ b/frontend/src/components/SensitiveData/ClassificationView.vue@@ -0,0 +1,155 @@+<template>+ <div class="w-full space-y-4">+ <div class="flex items-center justify-end">+ <NButton+ type="primary"+ :disabled="!hasPermission || !hasSensitiveDataFeature"+ @click="onUpload"+ >+ {{ $t("settings.sensitive-data.classification.upload") }}+ </NButton>+ <input+ ref="uploader"+ type="file"+ accept=".json"+ class="sr-only hidden"+ :disabled="!hasPermission || !hasSensitiveDataFeature"+ @input="onFileChange"+ />+ </div>+ <div class="textinfolabel">+ {{ $t("settings.sensitive-data.classification.label") }}+ <span+ class="normal-link cursor-pointer hover:underline"+ @click="state.showExampleModal = true"+ >+ {{ $t("settings.sensitive-data.classification.view-example") }}+ </span>+ </div>+ <NoDataPlaceholder v-if="settingStore.classification.length === 0" />+ <div v-else class="h-full">+ <ClassificationTree+ :classification-config="settingStore.classification[0]"+ />+ </div>+ </div>++ <ClassificationExampleModal+ v-if="state.showExampleModal"+ @dismiss="state.showExampleModal = false"+ />++ <BBAlert+ v-if="state.showOverrideModal"+ :style="'WARN'"+ :ok-text="$t('settings.sensitive-data.classification.override-confirm')"+ :title="$t('settings.sensitive-data.classification.override-title')"+ :description="$t('settings.sensitive-data.classification.override-desc')"+ @ok="upsertSetting"+ @cancel="state.showOverrideModal = false"+ />+</template>++<script lang="ts" setup>+import { v4 as uuidv4 } from "uuid";+import { computed, reactive, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import {+ featureToRef,+ useCurrentUserV1,+ useSettingV1Store,+ pushNotification,+} from "@/store";+import { DataClassificationSetting_DataClassificationConfig } from "@/types/proto/v1/setting_service";+import { hasWorkspacePermissionV1 } from "@/utils";++const uploader = ref<HTMLInputElement | null>(null);++interface LocalState {+ classification?: DataClassificationSetting_DataClassificationConfig;+ showExampleModal: boolean;+ showOverrideModal: boolean;+}++const state = reactive<LocalState>({+ showExampleModal: false,+ showOverrideModal: false,+});+const { t } = useI18n();+const settingStore = useSettingV1Store();+const currentUserV1 = useCurrentUserV1();++watch(+ () => state.classification,+ async () => {+ if (settingStore.classification.length !== 0) {+ state.showOverrideModal = true;+ return;+ }++ await upsertSetting();+ }+);++const upsertSetting = async () => {+ if (!state.classification) {+ return;+ }+ await settingStore.upsertSetting({+ name: "bb.workspace.data-classification",+ value: {+ dataClassificationSettingValue: {+ configs: [state.classification],+ },+ },+ });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("settings.sensitive-data.classification.upload-succeed"),+ });+ state.showOverrideModal = false;+};++const hasPermission = computed(() => {+ return hasWorkspacePermissionV1(+ "bb.permission.workspace.manage-sensitive-data",+ currentUserV1.value.userRole+ );+});+const hasSensitiveDataFeature = featureToRef("bb.feature.sensitive-data");++const onUpload = () => {+ uploader.value?.click();+};++const onFileChange = () => {+ const files: File[] = (uploader.value as any).files;+ if (files.length !== 1) {+ return;+ }+ const file = files[0];++ const fr = new FileReader();+ fr.onload = () => {+ if (!fr.result) {+ return;+ }+ state.classification =+ DataClassificationSetting_DataClassificationConfig.fromPartial({+ ...JSON.parse(fr.result as string),+ id: uuidv4(),+ });+ };+ fr.onerror = () => {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: `Read file error`,+ description: String(fr.error),+ });+ return;+ };+ fr.readAsText(file);+};+</script>diff --git a/frontend/src/components/SensitiveData/components/ClassificationExampleModal.vue b/frontend/src/components/SensitiveData/components/ClassificationExampleModal.vuenew file mode 100644index 0000000000..9b61cf310c--- /dev/null+++ b/frontend/src/components/SensitiveData/components/ClassificationExampleModal.vue@@ -0,0 +1,118 @@+<template>+ <BBModal+ :close-on-esc="true"+ :mask-closable="true"+ :trap-focus="false"+ :title="$t('settings.sensitive-data.classification.json-format-example')"+ class="w-[48rem] max-w-full"+ @close="$emit('dismiss')"+ >+ <div class="my-4 rounded-sm p-4 bg-gray-100 relative">+ <div+ class="absolute top-2 right-2 p-2 rounded bg-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-300 cursor-pointer"+ @click="handleCopy"+ >+ <heroicons-outline:clipboard-document class="w-4 h-4" />+ </div>+ <NConfigProvider :hljs="hljs">+ <NCode language="json" :code="JSON.stringify(example, null, 2)" />+ </NConfigProvider>+ </div>+ </BBModal>+</template>++<script lang="ts" setup>+import { useClipboard } from "@vueuse/core";+import hljs from "highlight.js/lib/core";+import json from "highlight.js/lib/languages/json";+import { NCode, NConfigProvider } from "naive-ui";+import { useI18n } from "vue-i18n";+import { pushNotification } from "@/store";++hljs.registerLanguage("json", json);++defineEmits<{+ (event: "dismiss"): void;+}>();++// TODO: localization.+const example = {+ title: "数据分级分类样例",+ levels: [+ {+ id: "1",+ title: "1级",+ description: "",+ },+ {+ id: "2",+ title: "2级",+ description: "",+ },+ ],+ classification: {+ "1": {+ id: "1",+ title: "个人",+ description: "",+ },+ "1-1": {+ id: "1-1",+ title: "个人自然信息",+ description: "",+ },+ "1-1-1": {+ id: "1-1-1",+ title: "个人基本信息",+ description: "指个人基本情况数据,如个人姓名、性别、国籍、家庭住址等。",+ levelId: "1",+ },+ "1-1-2": {+ id: "1-1-2",+ title: "个人财产信息",+ description: "指个人的财产数据,如个人收入状况、拥有的不动产状况等。",+ levelId: "2",+ },+ "1-2": {+ id: "1-2",+ title: "个人身份信息",+ description: "",+ },+ "1-2-1": {+ id: "1-2-1",+ title: "传统鉴别信息",+ description: "指各类常规个人身份鉴别技术手段所依赖的数据。",+ levelId: "2",+ },+ "2": {+ id: "2",+ title: "单位",+ description: "",+ },+ "2-1": {+ id: "2-1",+ title: "单位基本信息",+ description: "",+ },+ "2-1-1": {+ id: "2-1-1",+ title: "单位基本概况",+ description: "指单位基础概况数据。",+ levelId: "1",+ },+ },+};++const { copy: copyTextToClipboard } = useClipboard();+const { t } = useI18n();++const handleCopy = () => {+ console.log("handleCopy");+ copyTextToClipboard(JSON.stringify(example, null, 2));+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("settings.sensitive-data.classification.copy-succeed"),+ });+};+</script>diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 3456578909..642f2885d5 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -805,6 +805,19 @@"self": "Action","query": "Query","export": "Export"+ },+ "classification": {+ "self": "Data classification",+ "upload": "Upload classification",+ "upload-succeed": "Upload succeed",+ "search": "Search classification",+ "label": "You can upload classification file with JSON format.",+ "view-example": "View example",+ "json-format-example": "Classification JSON format example",+ "copy-succeed": "Copy example succeed",+ "override-title": "Classification data override",+ "override-desc": "Existed classification data will be overridden and affect all projects.",+ "override-confirm": "Still upload"}},"access-control": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex fd4784b101..116971c053 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -804,6 +804,19 @@"self": "Acción","query": "Consulta","export": "Exportar"+ },+ "classification": {+ "self": "Clasificación de datos",+ "upload": "Subir clasificación",+ "upload-succeed": "Subida exitosa",+ "search": "Clasificación de búsqueda",+ "label": "Puede cargar un archivo de clasificación con formato JSON.",+ "view-example": "Ver ejemplo",+ "json-format-example": "Ejemplo de formato JSON de clasificación",+ "copy-succeed": "Copiar ejemplo correctamente",+ "override-title": "Anulación de datos de clasificación",+ "override-desc": "Los datos de clasificación existentes se anularán y afectarán a todos los proyectos.",+ "override-confirm": "Aún subiendo"}},"access-control": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 17f5c5d87d..9de2c69969 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -802,6 +802,19 @@"self": "操作类型","query": "查询","export": "导出"+ },+ "classification": {+ "self": "数据分类分级",+ "upload": "导入分类分级",+ "upload-succeed": "导入成功",+ "search": "搜索分类分级",+ "label": "您可以上传数据分类分级的 JSON 格式文件。",+ "view-example": "查看样例",+ "json-format-example": "分类分级 JSON 格式样例",+ "copy-succeed": "样例已复制",+ "override-title": "覆盖分类分级数据",+ "override-desc": "已有的分类分级数据将会被覆盖,涉及到的项目都会受到影响。",+ "override-confirm": "继续导入"}},"access-control": {diff --git a/frontend/src/views/SettingWorkspaceSensitiveData.vue b/frontend/src/views/SettingWorkspaceSensitiveData.vueindex d23d2d4e3a..4a59a39c5b 100644--- a/frontend/src/views/SettingWorkspaceSensitiveData.vue+++ b/frontend/src/views/SettingWorkspaceSensitiveData.vue@@ -29,6 +29,12 @@><MaskingAlgorithmsView /></NTabPane>+ <NTabPane+ name="classification"+ :tab="$t('settings.sensitive-data.classification.self')"+ >+ <ClassificationView />+ </NTabPane></NTabs></div></template>@@ -49,6 +55,7 @@ const dataMaskingTabList = ["global-masking-rule","semantic-types","masking-algorithms",+ "classification",] as const;type DataMaskingTab = typeof dataMaskingTabList[number];const isDataMaskingTab = (tab: any): tab is DataMaskingTab =>@@ -58,8 +65,10 @@ interface LocalState {selectedTab: DataMaskingTab;}+const defaultTab: DataMaskingTab = "global-masking-rule";+const state = reactive<LocalState>({- selectedTab: "global-masking-rule",+ selectedTab: defaultTab,});const hasSensitiveDataFeature = featureToRef("bb.feature.sensitive-data");const router = useRouter();@@ -72,7 +81,7 @@ watch(if (isDataMaskingTab(tab)) {state.selectedTab = tab;} else {- state.selectedTab = "global-masking-rule";+ state.selectedTab = defaultTab;}},{