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: branch protection rules in frontend (#8853)
boojack353ab8a07bce
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex f71301076b..afdd7f259c 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -2082,7 +2082,11 @@ func (s *ProjectService) GetSchemaGroup(ctx context.Context, request *v1pb.GetSc// GetProjectProtectionRules gets a project protection rules.func (s *ProjectService) GetProjectProtectionRules(ctx context.Context, request *v1pb.GetProjectProtectionRulesRequest) (*v1pb.ProtectionRules, error) {- projectResourceID, err := common.TrimSuffix(request.Name, common.ProtectionRulesSuffix)+ projectName, err := common.TrimSuffix(request.Name, common.ProtectionRulesSuffix)+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, err.Error())+ }+ projectResourceID, err := common.GetProjectID(projectName)if err != nil {return nil, status.Errorf(codes.InvalidArgument, err.Error())}@@ -2108,7 +2112,11 @@ func (s *ProjectService) UpdateProjectProtectionRules(ctx context.Context, requeif request.ProtectionRules == nil {return nil, status.Errorf(codes.InvalidArgument, "protection rules must be set")}- projectResourceID, err := common.TrimSuffix(request.ProtectionRules.Name, common.ProtectionRulesSuffix)+ projectName, err := common.TrimSuffix(request.ProtectionRules.Name, common.ProtectionRulesSuffix)+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, err.Error())+ }+ projectResourceID, err := common.GetProjectID(projectName)if err != nil {return nil, status.Errorf(codes.InvalidArgument, err.Error())}diff --git a/frontend/src/components/Branch/utils.ts b/frontend/src/components/Branch/utils.tsindex 881cb5b1b2..238c9b3270 100644--- a/frontend/src/components/Branch/utils.ts+++ b/frontend/src/components/Branch/utils.ts@@ -13,3 +13,7 @@ export const validateBranchName = (branchName: string): boolean => {const regex = /^[a-zA-Z][a-zA-Z0-9-_/]+$/;return regex.test(branchName);};++export const wildcardToRegex = (wildcard: string): RegExp => {+ return new RegExp(`^${wildcard.split("*").join(".*")}$`);+};diff --git a/frontend/src/components/Project/CreateProjectBranchProtectionRulePanel.vue b/frontend/src/components/Project/CreateProjectBranchProtectionRulePanel.vuenew file mode 100644index 0000000000..8c58e32030--- /dev/null+++ b/frontend/src/components/Project/CreateProjectBranchProtectionRulePanel.vue@@ -0,0 +1,234 @@+<template>+ <NDrawer+ :show="true"+ width="auto"+ :auto-focus="false"+ @update:show="(show: boolean) => !show && $emit('close')"+ >+ <NDrawerContent+ :title="$t('project.settings.branch-protection-rules.self')"+ :closable="true"+ class="w-[50rem] max-w-[100vw] relative"+ >+ <div>+ <p>+ {{+ $t(+ "project.settings.branch-protection-rules.branch-name-pattern.self"+ )+ }}+ </p>+ <p class="text-sm textinfolabel mb-2">+ {{+ $t(+ "project.settings.branch-protection-rules.branch-name-pattern.description"+ )+ }}+ </p>+ <NInput v-model:value="state.protectionRule.nameFilter" />+ </div>+ <div class="mt-2">+ <p class="text-sm">+ {{+ $t(+ "project.settings.branch-protection-rules.applies-to-n-branches",+ { n: matchedBranchList.length }+ )+ }}+ </p>+ <div+ class="w-full flex flex-row justify-start items-center flex-wrap gap-2 mt-2"+ >+ <NTag+ v-for="branch in matchedBranchList"+ :key="branch.name"+ type="success"+ round+ >+ {{ branch.title }}+ </NTag>+ </div>+ </div>+ <NDivider class="!my-4" />+ <div class="space-y-2">+ <NCheckbox v-model:checked="state.disallowAllRoles">{{+ $t(+ "project.settings.branch-protection-rules.only-allow-specified-roles-to-create-branch"+ )+ }}</NCheckbox>+ <NSelect+ v-if="state.disallowAllRoles"+ v-model:value="state.selectedRoles"+ multiple+ :options="roleOptions"+ />+ </div>+ <template #footer>+ <div class="w-full flex flex-row justify-between items-center">+ <div>+ <DeleteConfirmButton v-if="!isCreating" @confirm="handleDelete" />+ </div>+ <div class="flex items-center justify-end gap-x-2">+ <NButton @click="$emit('close')">{{ $t("common.cancel") }}</NButton>+ <NButton+ type="primary"+ :disabled="!allowConfirm"+ @click="handleConfirm"+ >+ {{ isCreating ? $t("common.add") : $t("common.update") }}+ </NButton>+ </div>+ </div>+ </template>+ </NDrawerContent>+ </NDrawer>+</template>++<script lang="ts" setup>+import { cloneDeep } from "lodash-es";+import {+ NButton,+ NCheckbox,+ NDrawer,+ NDrawerContent,+ NInput,+ NDivider,+ NSelect,+ NTag,+} from "naive-ui";+import { v4 as uuidv4 } from "uuid";+import { computed, reactive, watch } from "vue";+import { useRoleStore, useSchemaDesignList } from "@/store";+import {+ getProjectAndSchemaDesignSheetId,+ projectNamePrefix,+ protectionRulesSuffix,+} from "@/store/modules/v1/common";+import {+ useProjectBranchProtectionRules,+ useProjectProtectionRulesStore,+} from "@/store/modules/v1/projectProtectionRoles";+import { ComposedProject, PresetRoleType } from "@/types";+import {+ ProtectionRule,+ ProtectionRule_Target,+} from "@/types/proto/v1/project_service";+import { displayRoleTitle } from "@/utils";+import { wildcardToRegex } from "../Branch/utils";++const props = defineProps<{+ project: ComposedProject;+ protectionRule?: ProtectionRule;+}>();++interface LocalState {+ protectionRule: ProtectionRule;+ disallowAllRoles: boolean;+ selectedRoles: string[];+}++const emit = defineEmits<{+ (event: "close"): void;+}>();++const { schemaDesignList } = useSchemaDesignList();+const protectionRuleStore = useProjectProtectionRulesStore();+const branchProtectionRules = useProjectBranchProtectionRules(+ props.project.name+);+const state = reactive<LocalState>({+ protectionRule:+ props.protectionRule ||+ ProtectionRule.fromPartial({+ id: uuidv4(),+ target: ProtectionRule_Target.BRANCH,+ }),+ disallowAllRoles:+ !!props.protectionRule &&+ props.protectionRule?.createAllowedRoles.length !== 0,+ selectedRoles: props.protectionRule?.createAllowedRoles || [],+});++const branchList = computed(() => {+ return schemaDesignList.value.filter((branch) => {+ const [projectName] = getProjectAndSchemaDesignSheetId(branch.name);+ return projectNamePrefix + projectName === props.project.name;+ });+});++const matchedBranchList = computed(() => {+ return branchList.value.filter((branch) => {+ return wildcardToRegex(state.protectionRule.nameFilter).test(branch.title);+ });+});++const isCreating = computed(() => {+ return props.protectionRule === undefined;+});++const allowConfirm = computed(() => {+ return state.protectionRule.nameFilter !== "";+});++const roleList = computed(() => {+ const roleList = useRoleStore().roleList;+ return roleList;+});++const roleOptions = computed(() => {+ return roleList.value.map((role) => {+ // Only allow to select roles that are not OWNER.+ const disabled = role.name === PresetRoleType.OWNER;+ return {+ label: displayRoleTitle(role.name),+ value: role.name,+ disabled,+ };+ });+});++watch(+ () => [state.disallowAllRoles],+ () => {+ if (state.disallowAllRoles) {+ if (!state.selectedRoles.includes(PresetRoleType.OWNER)) {+ state.selectedRoles.unshift(PresetRoleType.OWNER);+ }+ }+ }+);++const handleConfirm = async () => {+ if (!allowConfirm.value) {+ return;+ }++ const rules = cloneDeep(branchProtectionRules.value);+ const rule = ProtectionRule.fromPartial({+ ...state.protectionRule,+ // If disallowAllRoles is false, `createAllowedRoles` should be an empty array.+ createAllowedRoles: state.disallowAllRoles ? state.selectedRoles : [],+ });+ if (isCreating.value) {+ rules.push(rule);+ } else {+ const index = rules.findIndex((item) => item.id === rule.id);+ rules[index] = rule;+ }++ await protectionRuleStore.updateProjectProtectionRules({+ name: props.project.name + protectionRulesSuffix,+ rules: rules,+ });+ emit("close");+};++const handleDelete = async () => {+ const rules = cloneDeep(branchProtectionRules.value);+ await protectionRuleStore.updateProjectProtectionRules({+ name: props.project.name + protectionRulesSuffix,+ rules: rules.filter((rule) => rule.id !== state.protectionRule.id),+ });+ emit("close");+};+</script>diff --git a/frontend/src/components/Project/ProjectBranchProtectionRulesSettingPanel.vue b/frontend/src/components/Project/ProjectBranchProtectionRulesSettingPanel.vuenew file mode 100644index 0000000000..a9d3057c1f--- /dev/null+++ b/frontend/src/components/Project/ProjectBranchProtectionRulesSettingPanel.vue@@ -0,0 +1,84 @@+<template>+ <div class="w-full flex flex-col justify-start items-start py-2">+ <div class="w-full flex flex-row justify-between items-center mt-4 mb-4">+ <h3 class="text-lg font-medium leading-7 text-main">+ {{ $t("project.settings.branch-protection-rules.self") }}+ </h3>+ <div>+ <NButton :disabled="!allowEdit" @click="handleCreateRule">{{+ $t("project.settings.branch-protection-rules.add-rule")+ }}</NButton>+ </div>+ </div>+ <div+ v-for="rule in branchProtectionRules"+ :key="rule.id"+ class="w-full flex flex-row justify-between items-center px-3 py-2 border border-b-0 last:border-b"+ >+ <NTag type="success" round>+ {{ rule.nameFilter }}+ </NTag>+ <div class="flex flex-row justify-end items-center">+ <NButton text :disabled="!allowEdit" @click="handleEditRule(rule)">+ <template #icon>+ <PenLine />+ </template>+ </NButton>+ </div>+ </div>+ <div v-if="branchProtectionRules.length === 0" class="w-full">+ <p class="textinfolabel">+ {{+ $t(+ "project.settings.branch-protection-rules.no-protection-rule-configured"+ )+ }}+ </p>+ </div>+ </div>++ <CreateProjectBranchProtectionRulePanel+ v-if="createRulePanelContext.show"+ :project="project"+ :allow-edit="allowEdit"+ :protection-rule="createRulePanelContext.rule"+ @close="createRulePanelContext.show = false"+ />+</template>++<script lang="ts" setup>+import { PenLine } from "lucide-vue-next";+import { NButton, NTag } from "naive-ui";+import { ref } from "vue";+import { useProjectBranchProtectionRules } from "@/store/modules/v1/projectProtectionRoles";+import { ComposedProject } from "@/types";+import { ProtectionRule } from "@/types/proto/v1/project_service";++const props = defineProps<{+ project: ComposedProject;+ allowEdit?: boolean;+}>();++const branchProtectionRules = useProjectBranchProtectionRules(+ props.project.name+);+const createRulePanelContext = ref<{+ show: boolean;+ rule?: ProtectionRule;+}>({+ show: false,+});++const handleCreateRule = () => {+ createRulePanelContext.value = {+ show: true,+ };+};++const handleEditRule = (rule: ProtectionRule) => {+ createRulePanelContext.value = {+ show: true,+ rule: rule,+ };+};+</script>diff --git a/frontend/src/components/Project/ProjectGeneralSettingPanel.vue b/frontend/src/components/Project/ProjectGeneralSettingPanel.vueindex 2dc73811de..bc2ffc37b0 100644--- a/frontend/src/components/Project/ProjectGeneralSettingPanel.vue+++ b/frontend/src/components/Project/ProjectGeneralSettingPanel.vue@@ -1,9 +1,9 @@<template>- <form class="max-w-[60rem] mx-auto space-y-4">+ <form class="max-w-3xl w-full space-y-4 mx-auto"><p class="text-lg font-medium leading-7 text-main">{{ $t("common.general") }}</p>- <div class="flex justify-between">+ <div class="flex justify-start items-start gap-12"><dl class=""><dt class="text-sm font-medium text-control-light">{{ $t("common.name") }} <span class="text-red-600">*</span>diff --git a/frontend/src/components/ProjectSettingPanel.vue b/frontend/src/components/ProjectSettingPanel.vueindex 8cce0ef8f5..02292f86aa 100644--- a/frontend/src/components/ProjectSettingPanel.vue+++ b/frontend/src/components/ProjectSettingPanel.vue@@ -2,6 +2,10 @@<div class="max-w-3xl mx-auto space-y-6 mb-6"><div class="divide-y divide-block-border space-y-6"><ProjectGeneralSettingPanel :project="project" :allow-edit="allowEdit" />+ <ProjectBranchProtectionRulesSettingPanel+ :project="project"+ :allow-edit="allowEdit"+ /><div v-if="isTenantProject" class="pt-6"><ProjectDeploymentConfigPanelid="deployment-config"@@ -10,8 +14,10 @@:allow-edit="allowEdit"/></div>+ <div v-if="isDev" class="pt-4">+ <ProjectArchiveRestoreButton :project="project" />+ </div></div>- <ProjectArchiveRestoreButton :project="project" /></div></template>diff --git a/frontend/src/components/v2/Button/DeleteConfirmButton.vue b/frontend/src/components/v2/Button/DeleteConfirmButton.vuenew file mode 100644index 0000000000..7c7511cc86--- /dev/null+++ b/frontend/src/components/v2/Button/DeleteConfirmButton.vue@@ -0,0 +1,30 @@+<template>+ <NPopconfirm @positive-click="handleDelete">+ <template #trigger>+ <NButton quaternary size="small" style="--n-padding: 0 6px" @click.stop>+ <template #icon>+ <heroicons:trash />+ </template>+ <template #default>+ {{ $t("common.delete") }}+ </template>+ </NButton>+ </template>++ <template #default>+ <div>{{ $t("bbkit.confirm-button.sure-to-delete") }}</div>+ </template>+ </NPopconfirm>+</template>++<script setup lang="ts">+import { NButton, NPopconfirm } from "naive-ui";++const emit = defineEmits<{+ (event: "confirm"): void;+}>();++const handleDelete = async () => {+ emit("confirm");+};+</script>diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 2ca5db3f7a..57f8c86464 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1751,7 +1751,18 @@"schema-change-type": "Schema change type","select-schema-change-type-ddl": "Imperative - Specify the change with any DDL statements.","select-schema-change-type-sdl": "Declarative - Specify the desired schema. Only use CREATE TABLE/INDEX.",- "schema-path-template-sdl-description": "The schema file describes the database's full schema."+ "schema-path-template-sdl-description": "The schema file describes the database's full schema.",+ "branch-protection-rules": {+ "self": "Branch protection rules",+ "add-rule": "Add Rule",+ "branch-name-pattern": {+ "self": "Branch name pattern",+ "description": "Support wildcard such as feature/* or *-stable"+ },+ "applies-to-n-branches": "Applies to {n} branch | Applies to {n} branches",+ "only-allow-specified-roles-to-create-branch": "Only allow specified roles to create branch",+ "no-protection-rule-configured": "No protection rule configured."+ }},"members": {"description": "Project members determine the permission to operate database and issues inside the proejct. Project Owner, Workspace Owner and Workspace DBA all have full project permissions.",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 583df66723..aedde959e8 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1750,7 +1750,18 @@"schema-change-type": "Tipo de cambio de esquema","select-schema-change-type-ddl": "Imperativo: especifique el cambio con cualquier declaración DDL.","select-schema-change-type-sdl": "Declarativo: especifique el esquema deseado. Utilice únicamente CREAR TABLA/ÍNDICE.",- "schema-path-template-sdl-description": "El archivo de esquema describe el esquema completo de la base de datos."+ "schema-path-template-sdl-description": "El archivo de esquema describe el esquema completo de la base de datos.",+ "branch-protection-rules": {+ "self": "Branch protection rules",+ "add-rule": "Añadir regla",+ "branch-name-pattern": {+ "self": "Patrón de nombre de rama",+ "description": "Soporta comodines como feature/* o *-stable"+ },+ "applies-to-n-branches": "Se aplica a {n} ramas",+ "only-allow-specified-roles-to-create-branch": "Sólo permitir roles especificados para crear rama",+ "no-protection-rule-configured": "No hay regla de protección configurada"+ }},"members": {"description": "Los miembros del proyecto determinan el permiso para operar la base de datos y los problemas dentro del proyecto. El propietario del proyecto, el propietario del espacio de trabajo y el DBA del espacio de trabajo tienen permisos completos para el proyecto.",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex c91b6afb2d..5a44c01372 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1746,7 +1746,18 @@"schema-change-type": "Schema 变更类型","select-schema-change-type-ddl": "命令式 - 使用任意的 DDL 语句,描述变更命令。","select-schema-change-type-sdl": "声明式 - 仅使用 CREATE TABLE/INDEX,直接描述最终期望的 Schema。",- "schema-path-template-sdl-description": "Schema 文件描述了完整的数据库结构。"+ "schema-path-template-sdl-description": "Schema 文件描述了完整的数据库结构。",+ "branch-protection-rules": {+ "self": "分支保护规则",+ "add-rule": "添加分支",+ "branch-name-pattern": {+ "self": "分支名称模式",+ "description": "支持通配符,如 feature/* 或 *-stable"+ },+ "applies-to-n-branches": "应用到了 {n} 个分支",+ "only-allow-specified-roles-to-create-branch": "只允许指定角色创建分支",+ "no-protection-rule-configured": "没有配置分支保护规则。"+ }},"members": {"description": "项目成员角色决定了操作项目中的数据库和工单的权限。项目的所有者,工作空间的所有者和 DBA 都具有项目所有的权限。",diff --git a/frontend/src/store/modules/v1/common.ts b/frontend/src/store/modules/v1/common.tsindex b7ec20c7d9..75e2fceb08 100644--- a/frontend/src/store/modules/v1/common.ts+++ b/frontend/src/store/modules/v1/common.ts@@ -17,6 +17,8 @@ export const issueNamePrefix = "issues/";export const secretNamePrefix = "secrets/";export const schemaDesignNamePrefix = "schemaDesigns/";+export const protectionRulesSuffix = "/protectionRules";+export const getNameParentTokens = (name: string,tokenPrefixes: string[]diff --git a/frontend/src/store/modules/v1/projectProtectionRoles.ts b/frontend/src/store/modules/v1/projectProtectionRoles.tsnew file mode 100644index 0000000000..6164af61b8--- /dev/null+++ b/frontend/src/store/modules/v1/projectProtectionRoles.ts@@ -0,0 +1,76 @@+import { defineStore } from "pinia";+import { computed, reactive, watchEffect } from "vue";+import { projectServiceClient } from "@/grpcweb";+import { ResourceId } from "@/types";+import {+ ProtectionRule,+ ProtectionRule_Target,+ ProtectionRules,+} from "@/types/proto/v1/project_service";+import { protectionRulesSuffix } from "./common";++export const useProjectProtectionRulesStore = defineStore(+ "projec_protection_rules",+ () => {+ const protectionRulesMapByName = reactive(+ new Map<ResourceId, ProtectionRule[]>()+ );++ const reset = () => {+ protectionRulesMapByName.clear();+ };++ // Actions+ const fetchProjectProtectionRules = async (projectName: string) => {+ const data = await projectServiceClient.getProjectProtectionRules({+ name: projectName + protectionRulesSuffix,+ });+ protectionRulesMapByName.set(data.name, data.rules);+ return data.rules;+ };+ const getProjectProtectionRules = (projectName: string) => {+ return (+ protectionRulesMapByName.get(projectName + protectionRulesSuffix) ?? []+ );+ };+ const getOrFetchProjectProtectionRules = async (projectName: string) => {+ if (protectionRulesMapByName.has(projectName + protectionRulesSuffix)) {+ return getProjectProtectionRules(projectName);+ }+ return await fetchProjectProtectionRules(projectName);+ };+ const updateProjectProtectionRules = async (+ protectionRules: ProtectionRules+ ) => {+ const data = await projectServiceClient.updateProjectProtectionRules({+ protectionRules,+ });+ protectionRulesMapByName.set(data.name, data.rules);+ return data.rules;+ };++ return {+ reset,+ fetchProjectProtectionRules,+ getProjectProtectionRules,+ getOrFetchProjectProtectionRules,+ updateProjectProtectionRules,+ };+ }+);++export const useProjectBranchProtectionRules = (projectName: string) => {+ const store = useProjectProtectionRulesStore();++ const branchProtectionRules = computed(() => {+ return store+ .getProjectProtectionRules(projectName)+ .filter((rule) => rule.target === ProtectionRule_Target.BRANCH);+ });++ watchEffect(() => {+ store.getOrFetchProjectProtectionRules(projectName);+ });++ return branchProtectionRules;+};