Skip to content

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

feat: support raw expression in cel editor (#13119)

boojack8a60dc07f436
diff --git a/backend/common/cel.go b/backend/common/cel.go
index 3f3b3330c1..5c539180b0 100644
--- a/backend/common/cel.go
+++ b/backend/common/cel.go
@@ -123,15 +123,15 @@ func ValidateGroupCELExpr(expr string) (cel.Program, error) {
cel.Variable("resource", cel.MapType(cel.StringType, cel.AnyType)),
)
if err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
+ return nil, err
}
ast, issues := e.Compile(expr)
if issues != nil && issues.Err() != nil {
- return nil, status.Errorf(codes.InvalidArgument, issues.Err().Error())
+ return nil, issues.Err()
}
prog, err := e.Program(ast)
if err != nil {
- return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ return nil, err
}
return prog, nil
}
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskForm.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskForm.vue
index 64f67c935e..d1eb0697f9 100644
--- a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskForm.vue
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskForm.vue
@@ -201,7 +201,7 @@ const handleUpsert = async () => {
const expressions = await batchConvertParsedExprToCELString([
ParsedExpr.fromPartial({
- expr: buildCELExpr(state.value.expr),
+ expr: await buildCELExpr(state.value.expr),
}),
]);
risk.condition = Expr.fromPartial({
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RuleTemplateTable.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RuleTemplateTable.vue
index bab50dd5fe..0c976e19b9 100644
--- a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RuleTemplateTable.vue
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RuleTemplateTable.vue
@@ -137,7 +137,7 @@ const applyTemplate = async (template: RuleTemplate) => {
const { mode } = dialog.value!;
const expressions = await batchConvertParsedExprToCELString([
ParsedExpr.fromJSON({
- expr: buildCELExpr(expr),
+ expr: await buildCELExpr(expr),
}),
]);
const overrides: Partial<Risk> = {
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/template.ts b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/template.ts
index 95c5027a9a..b83163cbd0 100644
--- a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/template.ts
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/template.ts
@@ -1,7 +1,7 @@
import { first, last } from "lodash-es";
import { computed } from "vue";
import type { ConditionGroupExpr } from "@/plugins/cel";
-import { wrapAsGroup } from "@/plugins/cel";
+import { ExprType, wrapAsGroup } from "@/plugins/cel";
import { t, te } from "@/plugins/i18n";
import { useEnvironmentV1List } from "@/store";
import { PresetRiskLevel } from "@/types";
@@ -46,6 +46,7 @@ export const useRuleTemplates = () => {
templates.push({
key: "environment-prod-high",
expr: wrapAsGroup({
+ type: ExprType.Condition,
operator: "_==_",
args: [
"environment_id",
@@ -61,6 +62,7 @@ export const useRuleTemplates = () => {
templates.push({
key: "environment-dev-low",
expr: wrapAsGroup({
+ type: ExprType.Condition,
operator: "_==_",
args: [
"environment_id",
@@ -77,9 +79,11 @@ export const useRuleTemplates = () => {
templates.push({
key: "dml-in-environment-prod-10k-rows-high",
expr: wrapAsGroup({
+ type: ExprType.ConditionGroup,
operator: "_&&_",
args: [
{
+ type: ExprType.Condition,
operator: "_==_",
args: [
"environment_id",
@@ -87,10 +91,12 @@ export const useRuleTemplates = () => {
],
},
{
+ type: ExprType.Condition,
operator: "_>_",
args: ["affected_rows", 10000],
},
{
+ type: ExprType.Condition,
operator: "@in",
args: ["sql_type", ["UPDATE", "DELETE"]],
},
@@ -107,6 +113,7 @@ export const useRuleTemplates = () => {
templates.push({
key: "create-database-in-environment-prod-moderate",
expr: wrapAsGroup({
+ type: ExprType.Condition,
operator: "_==_",
args: [
"environment_id",
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
index 86bf6e8564..e7ffa5c2e4 100644
--- a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
@@ -32,10 +32,17 @@
<ExprEditor
:expr="state.expr"
:allow-admin="true"
+ :enable-raw-expression="true"
:factor-list="FactorList"
:factor-support-dropdown="factorSupportDropdown"
:factor-options-map="DatabaseGroupFactorOptionsMap(project)"
/>
+ <p
+ v-if="matchingError"
+ class="mt-2 text-sm border border-red-600 px-2 py-1 rounded-lg bg-red-50 text-red-600"
+ >
+ {{ matchingError }}
+ </p>
</div>
<div class="col-span-2">
<MatchedDatabaseView
@@ -68,13 +75,21 @@
import { useDebounceFn } from "@vueuse/core";
import { cloneDeep } from "lodash-es";
import { NCheckbox, NInput, NDivider } from "naive-ui";
-import { Status } from "nice-grpc-web";
+import { ClientError, Status } from "nice-grpc-web";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import ExprEditor from "@/components/ExprEditor";
import type { ConditionGroupExpr } from "@/plugins/cel";
-import { emptySimpleExpr, wrapAsGroup } from "@/plugins/cel";
-import { useDBGroupStore, useSubscriptionV1Store } from "@/store";
+import {
+ emptySimpleExpr,
+ validateSimpleExpr,
+ wrapAsGroup,
+} from "@/plugins/cel";
+import {
+ useDatabaseV1ListByProject,
+ useDBGroupStore,
+ useSubscriptionV1Store,
+} from "@/store";
import {
databaseGroupNamePrefix,
getProjectNameAndDatabaseGroupName,
@@ -119,6 +134,7 @@ const state = reactive<LocalState>({
expr: wrapAsGroup(emptySimpleExpr()),
multitenancy: false,
});
+const { databaseList } = useDatabaseV1ListByProject(props.project.name);
const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();
const isCreating = computed(() => props.databaseGroup === undefined);
@@ -182,17 +198,32 @@ const validateResourceId = async (
return [];
};
+const matchingError = ref<string | undefined>(undefined);
const matchedDatabaseList = ref<ComposedDatabase[]>([]);
const unmatchedDatabaseList = ref<ComposedDatabase[]>([]);
const updateDatabaseMatchingState = useDebounceFn(async () => {
+ if (!validateSimpleExpr(state.expr)) {
+ matchingError.value = undefined;
+ matchedDatabaseList.value = [];
+ unmatchedDatabaseList.value = databaseList.value;
+ return;
+ }
+
state.isRequesting = true;
- const result = await dbGroupStore.fetchDatabaseGroupMatchList({
- projectName: props.project.name,
- expr: state.expr,
- });
+ try {
+ const result = await dbGroupStore.fetchDatabaseGroupMatchList({
+ projectName: props.project.name,
+ expr: state.expr,
+ });
- matchedDatabaseList.value = result.matchedDatabaseList;
- unmatchedDatabaseList.value = result.unmatchedDatabaseList;
+ matchingError.value = undefined;
+ matchedDatabaseList.value = result.matchedDatabaseList;
+ unmatchedDatabaseList.value = result.unmatchedDatabaseList;
+ } catch (error) {
+ matchingError.value = (error as ClientError).details;
+ matchedDatabaseList.value = [];
+ unmatchedDatabaseList.value = databaseList.value;
+ }
state.isRequesting = false;
}, 500);
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
index 1895f61c55..bd3467c52a 100644
--- a/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
@@ -17,12 +17,14 @@
/>
<template #footer>
<div class="w-full flex justify-between items-center">
- <NButton v-if="showDeleteButton" text @click="doDelete">
- <template #icon>
- <Trash2Icon class="w-4 h-auto" />
- </template>
- {{ $t("common.delete") }}
- </NButton>
+ <div>
+ <NButton v-if="showDeleteButton" text @click="doDelete">
+ <template #icon>
+ <Trash2Icon class="w-4 h-auto" />
+ </template>
+ {{ $t("common.delete") }}
+ </NButton>
+ </div>
<div class="flex flex-row justify-end items-center gap-x-2">
<NButton @click="$emit('close')">{{ $t("common.cancel") }}</NButton>
<NButton
@@ -40,21 +42,24 @@
</template>
<script lang="ts" setup>
+import { head } from "lodash-es";
import { Trash2Icon } from "lucide-vue-next";
import { NButton, useDialog } from "naive-ui";
-import type { ClientError } from "nice-grpc-common";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { Drawer, DrawerContent } from "@/components/v2";
-import { buildCELExpr } from "@/plugins/cel/logic";
+import { buildCELExpr, validateSimpleExpr } from "@/plugins/cel/logic";
import {
PROJECT_V1_ROUTE_DATABASE_GROUPS,
PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
} from "@/router/dashboard/projectV1";
import { pushNotification, useDBGroupStore } from "@/store";
import type { ComposedDatabaseGroup, ComposedProject } from "@/types";
-import { ParsedExpr } from "@/types/proto/google/api/expr/v1alpha1/syntax";
+import {
+ ParsedExpr,
+ Expr as CELExpr,
+} from "@/types/proto/google/api/expr/v1alpha1/syntax";
import { Expr } from "@/types/proto/google/type/expr";
import type { DatabaseGroup } from "@/types/proto/v1/database_group_service";
import { batchConvertParsedExprToCELString } from "@/utils";
@@ -88,18 +93,18 @@ const title = computed(() => {
const allowConfirm = computed(() => {
if (!formRef.value) {
- return true;
- }
-
- if (!isCreating.value) {
- return true;
+ return false;
}
- const formState = formRef.value.getFormState();
+ const formState = formRef.value?.getFormState();
if (formState.existMatchedUnactivateInstance) {
return false;
}
- return formState.resourceId && formState.placeholder;
+ return (
+ formState.resourceId &&
+ formState.placeholder &&
+ validateSimpleExpr(formState.expr)
+ );
});
const showDeleteButton = computed(() => {
@@ -140,62 +145,70 @@ const doDelete = () => {
const doConfirm = async () => {
const formState = formRef.value?.getFormState();
- if (!formState) {
+ if (!formState || !allowConfirm.value) {
return;
}
+ let celExpr: CELExpr | undefined = undefined;
try {
- if (isCreating.value) {
- const celStrings = await batchConvertParsedExprToCELString([
- ParsedExpr.fromJSON({
- expr: buildCELExpr(formState.expr),
- }),
- ]);
- const resourceId = formState.resourceId;
- await dbGroupStore.createDatabaseGroup({
- projectName: props.project.name,
- databaseGroup: {
- name: `${props.project.name}/databaseGroups/${resourceId}`,
- databasePlaceholder: formState.placeholder,
- databaseExpr: Expr.fromJSON({
- expression: celStrings[0] || "true",
- }),
- multitenancy: formState.multitenancy,
- },
- databaseGroupId: resourceId,
- });
- emit("created", resourceId);
- } else {
- const celStrings = await batchConvertParsedExprToCELString([
- ParsedExpr.fromJSON({
- expr: buildCELExpr(formState.expr),
- }),
- ]);
- await dbGroupStore.updateDatabaseGroup({
- ...props.databaseGroup!,
- databasePlaceholder: formState.placeholder,
- databaseExpr: Expr.fromJSON({
- expression: celStrings[0] || "true",
- }),
- multitenancy: formState.multitenancy,
- });
- }
-
+ celExpr = await buildCELExpr(formState.expr);
+ } catch (error) {
pushNotification({
module: "bytebase",
- style: "SUCCESS",
- title: isCreating.value ? t("common.created") : t("common.updated"),
+ style: "CRITICAL",
+ title: `CEL expression error occurred`,
+ description: (error as Error).message,
});
- emit("close");
- } catch (error) {
- console.error(error);
+ return;
+ }
+
+ const celStrings = await batchConvertParsedExprToCELString([
+ ParsedExpr.fromJSON({
+ expr: celExpr,
+ }),
+ ]);
+ const celString = head(celStrings);
+ if (!celString) {
pushNotification({
module: "bytebase",
style: "CRITICAL",
- title: `Request error occurred`,
- description: (error as ClientError).details,
+ title: `CEL expression error occurred`,
+ description: "CEL expression is empty",
});
return;
}
+
+ if (isCreating.value) {
+ const resourceId = formState.resourceId;
+ await dbGroupStore.createDatabaseGroup({
+ projectName: props.project.name,
+ databaseGroup: {
+ name: `${props.project.name}/databaseGroups/${resourceId}`,
+ databasePlaceholder: formState.placeholder,
+ databaseExpr: Expr.fromPartial({
+ expression: celString,
+ }),
+ multitenancy: formState.multitenancy,
+ },
+ databaseGroupId: resourceId,
+ });
+ emit("created", resourceId);
+ } else {
+ await dbGroupStore.updateDatabaseGroup({
+ ...props.databaseGroup!,
+ databasePlaceholder: formState.placeholder,
+ databaseExpr: Expr.fromPartial({
+ expression: celString,
+ }),
+ multitenancy: formState.multitenancy,
+ });
+ }
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: isCreating.value ? t("common.created") : t("common.updated"),
+ });
+ emit("close");
};
</script>
diff --git a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue
index 80b207d67e..941a04616d 100644
--- a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue
+++ b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue
@@ -3,28 +3,18 @@
<span class="text-base mr-2">{{ $t("common.databases") }}</span>
<BBSpin v-if="loading" class="opacity-60" />
</div>
- <div
- class="w-full border rounded min-h-[20rem] max-h-[24rem] overflow-y-auto"
+
+ <NCollapse
+ class="border p-2 rounded-lg"
+ :expanded-names="collapseExpandedNames"
+ @update:expanded-names="onExpandedNamesChange"
>
- <div
- class="sticky top-0 z-[1] w-full flex flex-row justify-between items-center px-2 py-1 bg-gray-100 border-b cursor-pointer"
- @click="state.showMatchedDatabaseList = !state.showMatchedDatabaseList"
+ <NCollapseItem
+ :title="$t('database-group.matched-database')"
+ :disabled="matchedDatabaseList.length === 0"
+ name="matched"
>
- <div class="text-sm font-medium">
- <span>{{ $t("database-group.matched-database") }}</span>
- <span class="ml-1 text-gray-400"
- >({{ matchedDatabaseList.length }})</span
- >
- </div>
- <button class="opacity-60">
- <heroicons-outline:chevron-right
- v-if="!state.showMatchedDatabaseList"
- class="w-5 h-auto"
- />
- <heroicons-outline:chevron-down v-else class="w-5 h-auto" />
- </button>
- </div>
- <div v-show="state.showMatchedDatabaseList" class="w-full">
+ <template #header-extra>{{ matchedDatabaseList.length }}</template>
<NVirtualList
class="w-full py-1 max-h-[12rem]"
:item-size="28"
@@ -56,28 +46,13 @@
</div>
</template>
</NVirtualList>
- </div>
- <div
- class="sticky top-7 z-[1] w-full flex flex-row justify-between items-center px-2 py-1 bg-gray-100 border-y cursor-pointer"
- @click="
- state.showUnmatchedDatabaseList = !state.showUnmatchedDatabaseList
- "
+ </NCollapseItem>
+ <NCollapseItem
+ :title="$t('database-group.unmatched-database')"
+ :disabled="unmatchedDatabaseList.length === 0"
+ name="unmatched"
>
- <div class="text-sm font-medium">
- <span>{{ $t("database-group.unmatched-database") }}</span>
- <span class="ml-1 text-gray-400"
- >({{ unmatchedDatabaseList.length }})</span
- >
- </div>
- <button class="opacity-60">
- <heroicons-outline:chevron-right
- v-if="!state.showUnmatchedDatabaseList"
- class="w-5 h-auto"
- />
- <heroicons-outline:chevron-down v-else class="w-5 h-auto" />
- </button>
- </div>
- <div v-show="state.showUnmatchedDatabaseList" class="w-full">
+ <template #header-extra>{{ unmatchedDatabaseList.length }}</template>
<NVirtualList
class="w-full py-1 max-h-[12rem]"
:item-size="28"
@@ -109,32 +84,44 @@
</div>
</template>
</NVirtualList>
- </div>
- </div>
+ </NCollapseItem>
+ </NCollapse>
</template>
<script lang="ts" setup>
-import { NEllipsis, NVirtualList } from "naive-ui";
-import { reactive } from "vue";
+import { NEllipsis, NVirtualList, NCollapse, NCollapseItem } from "naive-ui";
+import { ref, watch } from "vue";
import { BBSpin } from "@/bbkit";
import type { ComposedDatabase } from "@/types";
-import { InstanceV1EngineIcon } from "../v2";
import { FeatureBadge } from "../FeatureGuard";
+import { InstanceV1EngineIcon } from "../v2";
-interface LocalState {
- showMatchedDatabaseList: boolean;
- showUnmatchedDatabaseList: boolean;
-}
-
-defineProps<{
+const props = defineProps<{
matchedDatabaseList: ComposedDatabase[];
unmatchedDatabaseList: ComposedDatabase[];
loading?: boolean;
hideTitle?: boolean;
}>();
-const state = reactive<LocalState>({
- showMatchedDatabaseList: true,
- showUnmatchedDatabaseList: true,
-});
+const collapseExpandedNames = ref<string[]>([]);
+
+const onExpandedNamesChange = (expandedNames: string[]) => {
+ collapseExpandedNames.value = expandedNames;
+};
+
+watch(
+ () => props.matchedDatabaseList.length,
+ () => {
+ collapseExpandedNames.value = [];
+ if (props.matchedDatabaseList.length > 0) {
+ collapseExpandedNames.value.push("matched");
+ }
+ if (props.unmatchedDatabaseList.length > 0) {
+ collapseExpandedNames.value.push("unmatched");
+ }
+ },
+ {
+ immediate: true,
+ }
+);
</script>
diff --git a/frontend/src/components/ExprEditor/Condition.vue b/frontend/src/components/ExprEditor/Condition.vue
index 2b5a7dc440..282f4e784c 100644
--- a/frontend/src/components/ExprEditor/Condition.vue
+++ b/frontend/src/components/ExprEditor/Condition.vue
@@ -1,9 +1,7 @@
<!-- eslint-disable vue/no-mutating-props -->
<template>
- <NInputGroup
- class="bb-risk-expr-editor-condition w-full flex items-center overflow-x-hidden"
- >
+ <NInputGroup class="w-full flex items-center overflow-x-hidden">
<FactorSelect :expr="expr" />
<OperatorSelect :expr="expr" />
diff --git a/frontend/src/components/ExprEditor/ConditionGroup.vue b/frontend/src/components/ExprEditor/ConditionGroup.vue
index 41da6f40de..d6f04e3010 100644
--- a/frontend/src/components/ExprEditor/ConditionGroup.vue
+++ b/frontend/src/components/ExprEditor/ConditionGroup.vue
@@ -74,6 +74,12 @@
@remove="removeCondition(operand)"
@update="$emit('update')"
/>
+ <RawString
+ v-if="enableRawExpression && isRawStringExpr(operand)"
+ :expr="operand"
+ @remove="removeRawString(operand)"
+ @update="$emit('update')"
+ />
</div>
</div>
@@ -84,9 +90,17 @@
/></template>
<span class="text-gray-500">{{ $t("cel.condition.add") }}</span>
</NButton>
+ <NButton size="small" quaternary @click="addRawString">
+ <template #icon
+ ><heroicons:plus class="w-4 h-4 text-gray-500"
+ /></template>
+ <span class="text-gray-500">{{
+ $t("cel.condition.add-raw-expression")
+ }}</span>
+ </NButton>
</div>
- <div v-if="root && allowAdmin" class="space-x-1 pt-3">
+ <div v-if="root && allowAdmin" class="space-x-1">
<NButton size="small" quaternary @click="addCondition">
<template #icon><heroicons:plus class="w-4 h-4" /></template>
<span>{{ $t("cel.condition.add") }}</span>
@@ -103,6 +117,10 @@
</div>
</NTooltip>
</NButton>
+ <NButton size="small" quaternary @click="addRawString">
+ <template #icon><heroicons:plus class="w-4 h-4" /></template>
+ <span>{{ $t("cel.condition.add-raw-expression") }}</span>
+ </NButton>
</div>
</div>
</template>
@@ -118,8 +136,12 @@ import {
LogicalOperatorList,
isConditionGroupExpr,
isConditionExpr,
+ isRawStringExpr,
+ ExprType,
+ type RawStringExpr,
} from "@/plugins/cel";
import Condition from "./Condition.vue";
+import RawString from "./RawString.vue";
import { getOperatorListByFactor } from "./components/common";
import { useExprEditorContext } from "./context";
@@ -134,7 +156,8 @@ const emit = defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin, factorList, factorOperatorOverrideMap } = context;
+const { allowAdmin, enableRawExpression, factorList, factorOperatorOverrideMap } =
+ context;
const operator = computed({
get() {
@@ -165,14 +188,24 @@ const addCondition = () => {
);
args.value.push({
+ type: ExprType.Condition,
operator: operators[0] ?? "",
args: [factor, ""],
} as any);
emit("update");
};
+const addRawString = () => {
+ args.value.push({
+ type: ExprType.RawString,
+ content: "",
+ } as any);
+ emit("update");
+};
+
const addConditionGroup = () => {
args.value.push({
+ type: ExprType.ConditionGroup,
operator: LogicalOperatorList[0],
args: [],
});
@@ -194,4 +227,12 @@ const removeConditionGroup = (group: ConditionGroupExpr) => {
emit("update");
}
};
+
+const removeRawString = (rawString: RawStringExpr) => {
+ const index = args.value.indexOf(rawString);
+ if (index >= 0) {
+ args.value.splice(index, 1);
+ emit("update");
+ }
+};
</script>
diff --git a/frontend/src/components/ExprEditor/ExprEditor.vue b/frontend/src/components/ExprEditor/ExprEditor.vue
index 86bc236971..cd1501211a 100644
--- a/frontend/src/components/ExprEditor/ExprEditor.vue
+++ b/frontend/src/components/ExprEditor/ExprEditor.vue
@@ -15,6 +15,7 @@ const props = withDefaults(
defineProps<{
expr: ConditionGroupExpr;
allowAdmin?: boolean;
+ enableRawExpression?: boolean;
factorList: Factor[];
factorSupportDropdown?: Factor[];
factorOptionsMap?: Map<Factor, SelectOption[]>;
@@ -22,6 +23,7 @@ const props = withDefaults(
}>(),
{
allowAdmin: false,
+ enableRawExpression: false,
factorOperatorOverrideMap: undefined,
factorSupportDropdown: () => [],
factorOptionsMap: () => new Map(),
@@ -34,6 +36,7 @@ defineEmits<{
provideExprEditorContext({
allowAdmin: toRef(props, "allowAdmin"),
+ enableRawExpression: toRef(props, "enableRawExpression"),
factorList: toRef(props, "factorList"),
factorSupportDropdown: toRef(props, "factorSupportDropdown"),
factorOptionsMap: toRef(props, "factorOptionsMap"),
diff --git a/frontend/src/components/ExprEditor/RawString.vue b/frontend/src/components/ExprEditor/RawString.vue
new file mode 100644
index 0000000000..102e75f1b9
--- /dev/null
+++ b/frontend/src/components/ExprEditor/RawString.vue
@@ -0,0 +1,50 @@
+<!-- eslint-disable vue/no-mutating-props -->
+
+<template>
+ <NInputGroup class="w-full flex items-start overflow-x-hidden">
+ <NInput
+ v-model:value="expr.content"
+ type="textarea"
+ :autosize="{ minRows: 2, maxRows: 4 }"
+ placeholder="Enter raw CEL expression"
+ size="small"
+ />
+
+ <NButton
+ v-if="allowAdmin"
+ size="small"
+ type="default"
+ :style="'flex-shrink: 0;padding-left: 0;padding-right: 0;--n-width: 28px;--n-color: white;'"
+ @click="$emit('remove')"
+ >
+ <heroicons:trash class="w-3.5 h-3.5" />
+ </NButton>
+ </NInputGroup>
+</template>
+
+<script lang="ts" setup>
+import { NButton, NInput, NInputGroup } from "naive-ui";
+import { watch } from "vue";
+import { type RawStringExpr } from "@/plugins/cel";
+import { useExprEditorContext } from "./context";
+
+const props = defineProps<{
+ expr: RawStringExpr;
+}>();
+
+const emit = defineEmits<{
+ (event: "remove"): void;
+ (event: "update"): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+
+watch(
+ () => props.expr,
+ () => {
+ emit("update");
+ },
+ { deep: true }
+);
+</script>
diff --git a/frontend/src/components/ExprEditor/context.ts b/frontend/src/components/ExprEditor/context.ts
index 4941f401d4..a413ee7c3b 100644
--- a/frontend/src/components/ExprEditor/context.ts
+++ b/frontend/src/components/ExprEditor/context.ts
@@ -4,6 +4,7 @@ import type { Factor, Operator } from "@/plugins/cel";
export type ExprEditorContext = {
allowAdmin: Ref<boolean>;
+ enableRawExpression: Ref<boolean>;
factorList: Ref<Factor[]>;
factorSupportDropdown: Ref<Factor[]>;
factorOptionsMap: Ref<Map<Factor, SelectOption[]>>;
diff --git a/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue b/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
index f4dc415175..1f60374daf 100644
--- a/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
+++ b/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
@@ -193,7 +193,7 @@ const isValid = computed(() => {
const onConfirm = async () => {
const expressions = await batchConvertParsedExprToCELString([
ParsedExpr.fromJSON({
- expr: buildCELExpr(state.expr),
+ expr: await buildCELExpr(state.expr),
}),
]);
emit("confirm", {
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 814481da2e..8a8a128ed1 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -3493,6 +3493,7 @@
"description-tips": "A condition is a rule that can be configured via an expression. For example, the condition \"Environment is prod\" will match issues executed in the \"prod\" environment.",
"add": "Add condition",
"add-group": "Add condition group",
+ "add-raw-expression": "Add raw expression",
"group": {
"or": {
"description": "Any of the following are true..."
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 47ece4ff5c..a33995298b 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -3493,6 +3493,7 @@
"description-tips": "Una condición es una regla que se puede configurar mediante una expresión. Por ejemplo, la condición \"Entorno es prod\" coincidirá con las incidencias ejecutadas en el entorno \"prod\".",
"add": "Agregar condición",
"add-group": "Agregar grupo de condiciones",
+ "add-raw-expression": "Agregar expresión cruda",
"group": {
"or": {
"description": "Cualquiera de los siguientes es verdadero..."
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 529d07b575..6b04e57542 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -3493,6 +3493,7 @@
"description-tips": "条件は、式を通じて設定されるルールです。たとえば、「環境は本番」という条件は、「本番」環境で実行されたチケットと一致します。",
"add": "条件を追加する",
"add-group": "条件グループの追加",
+ "add-raw-expression": "生の表現を追加する",
"group": {
"or": {
"description": "次のいずれかが当てはまります…"
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 58b90cbe79..d317d2ea23 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3493,6 +3493,7 @@
"description-tips": "条件是通过表达式配置的规则。例如:条件「环境 为 prod」将会匹配在「prod」环境中执行的工单。",
"add": "添加条件",
"add-group": "添加条件组",
+ "add-raw-expression": "添加 Raw 表达式",
"group": {
"or": {
"description": "以下任一为真…"
diff --git a/frontend/src/plugins/cel/logic/build.ts b/frontend/src/plugins/cel/logic/build.ts
index ee32506f6e..b9421b3955 100644
--- a/frontend/src/plugins/cel/logic/build.ts
+++ b/frontend/src/plugins/cel/logic/build.ts
@@ -1,3 +1,5 @@
+import { head } from "lodash-es";
+import { celServiceClient } from "@/grpcweb";
import { Expr as CELExpr } from "@/types/proto/google/api/expr/v1alpha1/syntax";
import type { ConditionExpr, ConditionGroupExpr, SimpleExpr } from "../types";
import {
@@ -7,6 +9,8 @@ import {
isConditionGroupExpr,
isCompareExpr,
isStringExpr,
+ ExprType,
+ isRawStringExpr,
} from "../types";
const seq = {
@@ -17,10 +21,34 @@ const seq = {
};
// Build CEL expr according to simple expr
-export const buildCELExpr = (expr: SimpleExpr): CELExpr | undefined => {
- const convert = (expr: ConditionGroupExpr | ConditionExpr): CELExpr => {
+export const buildCELExpr = async (
+ expr: SimpleExpr
+): Promise<CELExpr | undefined> => {
+ const convert = async (expr: SimpleExpr): Promise<CELExpr | undefined> => {
if (isConditionGroupExpr(expr)) return convertGroup(expr);
if (isConditionExpr(expr)) return convertCondition(expr);
+ if (isRawStringExpr(expr)) {
+ if (!expr.content) {
+ return undefined;
+ }
+ const celExpr = head(
+ (
+ await celServiceClient.batchParse(
+ {
+ expressions: [expr.content],
+ },
+ {
+ silent: true,
+ }
+ )
+ ).expressions
+ )?.expr;
+ if (celExpr) {
+ return celExpr;
+ } else {
+ return undefined;
+ }
+ }
throw new Error(`unexpected type "${String(expr)}"`);
};
const convertCondition = (condition: ConditionExpr): CELExpr => {
@@ -64,29 +92,36 @@ export const buildCELExpr = (expr: SimpleExpr): CELExpr | undefined => {
}
throw new Error(`unsupported condition '${JSON.stringify(condition)}'`);
};
- const convertGroup = (group: ConditionGroupExpr): CELExpr => {
+ const convertGroup = async (
+ group: ConditionGroupExpr
+ ): Promise<CELExpr | undefined> => {
const { operator, args } = group;
+ if (args.length === 0) {
+ return undefined;
+ }
if (args.length === 1) {
// A dangled Logical Group should be extracted as single condition
- return convert(args[0]);
+ return await convert(args[0]);
}
const [left, ...rest] = args;
- const _args = [
- convert(left),
- convertGroup({
- operator,
- args: rest,
- }),
- ];
- // return createCallExpr(operator, args);
- return wrapCallExpr(operator, _args);
+ return wrapCallExpr(
+ operator,
+ [
+ await convert(left),
+ await convertGroup({
+ type: ExprType.ConditionGroup,
+ operator,
+ args: rest,
+ }),
+ ].filter(Boolean) as CELExpr[]
+ );
};
seq.id = 1;
try {
- return convert(expr);
+ return await convert(expr);
} catch (err) {
- console.debug(err);
+ console.error(err);
return undefined;
}
};
diff --git a/frontend/src/plugins/cel/logic/resolve.ts b/frontend/src/plugins/cel/logic/resolve.ts
index 77c78d81fd..c4cded4f21 100644
--- a/frontend/src/plugins/cel/logic/resolve.ts
+++ b/frontend/src/plugins/cel/logic/resolve.ts
@@ -8,12 +8,12 @@ import type {
EqualityOperator,
SimpleExpr,
CollectionExpr,
- ConditionExpr,
ConditionGroupExpr,
CompareExpr,
EqualityExpr,
StringExpr,
LogicalOperator,
+ RawStringExpr,
} from "../types";
import {
isEqualityOperator,
@@ -26,7 +26,9 @@ import {
isStringFactor,
isTimestampFactor,
isNegativeOperator,
+ ExprType,
} from "../types";
+import stringifyExpr from "./stringify";
// For simplify UI implementation, the "root" condition need to be a group.
export const wrapAsGroup = (
@@ -35,6 +37,7 @@ export const wrapAsGroup = (
): ConditionGroupExpr => {
if (isConditionGroupExpr(expr)) return expr;
return {
+ type: ExprType.ConditionGroup,
operator,
args: [expr],
};
@@ -42,52 +45,59 @@ export const wrapAsGroup = (
// Convert common expr to simple expr
export const resolveCELExpr = (expr: CELExpr): SimpleExpr => {
- const dfs = (
- expr: CELExpr,
- negative: boolean = false
- ): ConditionGroupExpr | ConditionExpr => {
+ const dfs = (expr: CELExpr, negative: boolean = false): SimpleExpr => {
const { callExpr } = expr;
if (!callExpr) {
- return emptySimpleExpr();
- // throw new Error(`unsupported expr "${JSON.stringify(expr)}"`);
+ // If no callExpr, we treat it as a raw string.
+ return resolveRawStringExpr(expr);
}
- const { args } = callExpr;
- const operator = callExpr.function as Operator;
- if (isLogicalOperator(operator)) {
- const group: ConditionGroupExpr = {
- operator,
- args: [],
- };
- const [left, right] = args;
- const sub = (subTree: CELExpr, expand: boolean) => {
- const subExpr = dfs(subTree);
- if (expand && subExpr.operator === operator) {
- group.args.push(...subExpr.args);
- } else {
- group.args.push(subExpr);
- }
- };
- sub(left, true);
- sub(right, false);
- return group;
+ try {
+ const { args } = callExpr;
+ const operator = callExpr.function as Operator;
+ if (isLogicalOperator(operator)) {
+ const group: ConditionGroupExpr = {
+ type: ExprType.ConditionGroup,
+ operator,
+ args: [],
+ };
+ const [left, right] = args;
+ const sub = (subTree: CELExpr, expand: boolean) => {
+ const subExpr = dfs(subTree);
+ if (
+ expand &&
+ isConditionGroupExpr(subExpr) &&
+ subExpr.operator === operator
+ ) {
+ group.args.push(...subExpr.args);
+ } else {
+ group.args.push(subExpr);
+ }
+ };
+ sub(left, true);
+ sub(right, false);
+ return group;
+ }
+ if (isNegativeOperator(operator)) {
+ return dfs(args[0], true);
+ }
+ if (isEqualityOperator(operator)) {
+ return resolveEqualityExpr(expr);
+ }
+ if (isCompareOperator(operator)) {
+ return resolveCompareExpr(expr);
+ }
+ if (isStringOperator(operator)) {
+ return resolveStringExpr(expr);
+ }
+ if (isCollectionOperator(operator)) {
+ return resolveCollectionExpr(expr, negative);
+ }
+ throw new Error(`unsupported expr "${JSON.stringify(expr)}"`);
+ } catch (error) {
+ // Any error occurs, we treat it as a raw string.
+ return resolveRawStringExpr(expr);
}
- if (isNegativeOperator(operator)) {
- return dfs(args[0], true);
- }
- if (isEqualityOperator(operator)) {
- return resolveEqualityExpr(expr);
- }
- if (isCompareOperator(operator)) {
- return resolveCompareExpr(expr);
- }
- if (isStringOperator(operator)) {
- return resolveStringExpr(expr);
- }
- if (isCollectionOperator(operator)) {
- return resolveCollectionExpr(expr, negative);
- }
- throw new Error(`unsupported expr "${JSON.stringify(expr)}"`);
};
return dfs(expr);
};
@@ -98,12 +108,14 @@ const resolveEqualityExpr = (expr: CELExpr): EqualityExpr => {
const factor = getFactorName(factorExpr);
if (isNumberFactor(factor)) {
return {
+ type: ExprType.Condition,
operator,
args: [factor, valueExpr.constExpr!.int64Value!.toNumber() ?? 0],
};
}
if (isStringFactor(factor)) {
return {
+ type: ExprType.Condition,
operator,
args: [factor, valueExpr.constExpr!.stringValue! ?? ""],
};
@@ -117,12 +129,14 @@ const resolveCompareExpr = (expr: CELExpr): CompareExpr => {
const factor = getFactorName(factorExpr);
if (isNumberFactor(factor)) {
return {
+ type: ExprType.Condition,
operator,
args: [factor, valueExpr.constExpr!.int64Value!.toNumber()],
};
}
if (isTimestampFactor(factor)) {
return {
+ type: ExprType.Condition,
operator,
args: [
factor,
@@ -138,6 +152,7 @@ const resolveStringExpr = (expr: CELExpr): StringExpr => {
const factor = getFactorName(expr.callExpr!.target!);
const value = expr.callExpr!.args[0];
return {
+ type: ExprType.Condition,
operator,
args: [factor as StringFactor, value.constExpr!.stringValue!],
};
@@ -156,6 +171,7 @@ const resolveCollectionExpr = (
if (isNumberFactor(factor)) {
return {
+ type: ExprType.Condition,
operator,
args: [
factor,
@@ -167,6 +183,7 @@ const resolveCollectionExpr = (
}
if (isStringFactor(factor)) {
return {
+ type: ExprType.Condition,
operator,
args: [
factor,
@@ -179,10 +196,18 @@ const resolveCollectionExpr = (
throw new Error(`cannot resolve expr ${JSON.stringify(expr)}`);
};
+const resolveRawStringExpr = (expr: CELExpr): RawStringExpr => {
+ return {
+ type: ExprType.RawString,
+ content: stringifyExpr(expr),
+ };
+};
+
export const emptySimpleExpr = (
operator: LogicalOperator = "_&&_"
): ConditionGroupExpr => {
return {
+ type: ExprType.ConditionGroup,
operator: operator,
args: [],
};
diff --git a/frontend/src/plugins/cel/logic/stringify.ts b/frontend/src/plugins/cel/logic/stringify.ts
new file mode 100644
index 0000000000..e4be2e4c1b
--- /dev/null
+++ b/frontend/src/plugins/cel/logic/stringify.ts
@@ -0,0 +1,88 @@
+import type {
+ Constant,
+ Expr,
+} from "@/types/proto/google/api/expr/v1alpha1/syntax";
+
+function stringifyExpr(expr: Expr): string {
+ if (expr.constExpr) {
+ return stringifyConstant(expr.constExpr);
+ } else if (expr.identExpr) {
+ return expr.identExpr.name;
+ } else if (expr.selectExpr) {
+ // Check if testOnly flag is used to denote a 'has' operation.
+ if (expr.selectExpr.testOnly) {
+ return `has(${stringifyExpr(expr.selectExpr.operand!)}.${expr.selectExpr.field})`;
+ } else {
+ return `${stringifyExpr(expr.selectExpr.operand!)}.${expr.selectExpr.field}`;
+ }
+ } else if (expr.callExpr) {
+ // Remove underscores from function name. e.g. "_&&_" -> "&&"
+ // Reference: https://github.com/google/cel-spec/blob/master/doc/langdef.md#list-of-standard-definitions
+ const functionName = expr.callExpr.function.replace(/_/g, "");
+ if (expr.callExpr.target) {
+ const target = stringifyExpr(expr.callExpr.target);
+ const args = expr.callExpr.args
+ .map((arg) => stringifyExpr(arg))
+ .join(", ");
+ return `${target}.${functionName}(${args})`;
+ } else {
+ const args = expr.callExpr.args.map((arg) => stringifyExpr(arg));
+ if (functionName === "&&" || functionName === "||") {
+ return `(${args.join(` ${functionName} `)})`;
+ } else {
+ return args.join(` ${functionName} `);
+ }
+ }
+ } else if (expr.listExpr) {
+ const elements = expr.listExpr.elements
+ .map((el) => stringifyExpr(el))
+ .join(", ");
+ return `[${elements}]`;
+ } else if (expr.structExpr) {
+ const entries = expr.structExpr.entries
+ .map((entry) => {
+ const key = entry.fieldKey
+ ? entry.fieldKey
+ : stringifyExpr(entry.mapKey!);
+ const value = stringifyExpr(entry.value!);
+ return `${key}: ${value}`;
+ })
+ .join(", ");
+ return `{${entries}}`;
+ } else if (expr.comprehensionExpr) {
+ const iterRange = stringifyExpr(expr.comprehensionExpr.iterRange!);
+ const accuInit = stringifyExpr(expr.comprehensionExpr.accuInit!);
+ const loopCondition = stringifyExpr(expr.comprehensionExpr.loopCondition!);
+ const loopStep = stringifyExpr(expr.comprehensionExpr.loopStep!);
+ const result = stringifyExpr(expr.comprehensionExpr.result!);
+ return `comprehension(${expr.comprehensionExpr.iterVar} in ${iterRange}; ${expr.comprehensionExpr.accuVar} = ${accuInit}; ${loopCondition}; ${loopStep}; ${result})`;
+ } else {
+ throw new Error("Unknown expression type");
+ }
+}
+
+function stringifyConstant(constant: Constant): string {
+ if (constant.nullValue !== undefined) {
+ return "null";
+ } else if (constant.boolValue !== undefined) {
+ return constant.boolValue.toString();
+ } else if (constant.int64Value !== undefined) {
+ return constant.int64Value.toString();
+ } else if (constant.uint64Value !== undefined) {
+ return constant.uint64Value.toString();
+ } else if (constant.doubleValue !== undefined) {
+ return constant.doubleValue.toString();
+ } else if (constant.stringValue !== undefined) {
+ return `"${constant.stringValue}"`;
+ } else if (constant.bytesValue !== undefined) {
+ return `b'${constant.bytesValue.toString()}'`;
+ } else if (constant.durationValue !== undefined) {
+ return `duration(${constant.durationValue})`;
+ } else if (constant.timestampValue !== undefined) {
+ return `timestamp(${constant.timestampValue})`;
+ } else {
+ throw new Error("Unknown constant type");
+ }
+}
+
+export default stringifyExpr;
diff --git a/frontend/src/plugins/cel/logic/validate.ts b/frontend/src/plugins/cel/logic/validate.ts
index ab945b9ede..ba1c86e1af 100644
--- a/frontend/src/plugins/cel/logic/validate.ts
+++ b/frontend/src/plugins/cel/logic/validate.ts
@@ -1,6 +1,16 @@
import { isNumber } from "lodash-es";
-import type { ConditionExpr, ConditionGroupExpr, SimpleExpr } from "../types";
-import { isEqualityExpr, isNumberFactor, isStringFactor } from "../types";
+import type {
+ ConditionExpr,
+ ConditionGroupExpr,
+ RawStringExpr,
+ SimpleExpr,
+} from "../types";
+import {
+ isEqualityExpr,
+ isNumberFactor,
+ isRawStringExpr,
+ isStringFactor,
+} from "../types";
import {
isCollectionExpr,
isConditionExpr,
@@ -63,9 +73,13 @@ export const validateSimpleExpr = (expr: SimpleExpr): boolean => {
if (args.length === 0) return false;
return args.every(validate);
};
+ const validateRawString = (rawString: RawStringExpr): boolean => {
+ return Boolean(rawString.content);
+ };
const validate = (expr: SimpleExpr): boolean => {
if (isConditionGroupExpr(expr)) return validateConditionGroup(expr);
if (isConditionExpr(expr)) return validateCondition(expr);
+ if (isRawStringExpr(expr)) return validateRawString(expr);
throw new Error(`unsupported expr '${JSON.stringify(expr)}'`);
};
return validate(expr);
diff --git a/frontend/src/plugins/cel/types/simple.ts b/frontend/src/plugins/cel/types/simple.ts
index 4d96951f7e..18c7fb3735 100644
--- a/frontend/src/plugins/cel/types/simple.ts
+++ b/frontend/src/plugins/cel/types/simple.ts
@@ -9,30 +9,39 @@ import {
type CollectionOperator,
isStringOperator,
isCollectionOperator,
- isLogicalOperator,
isCompareOperator,
isEqualityOperator,
} from "./operator";
-export type EqualityExpr = {
+export enum ExprType {
+ RawString = "RawString",
+ Condition = "Condition",
+ ConditionGroup = "ConditionGroup",
+}
+
+interface BaseConditionExpr {
+ type: ExprType.Condition;
+}
+
+export interface EqualityExpr extends BaseConditionExpr {
operator: EqualityOperator;
args: [StringFactor | NumberFactor, string | number];
-};
+}
-export type CompareExpr = {
+export interface CompareExpr extends BaseConditionExpr {
operator: CompareOperator;
args: [NumberFactor | TimestampFactor, number | Date];
-};
+}
-export type CollectionExpr = {
+export interface CollectionExpr extends BaseConditionExpr {
operator: CollectionOperator;
args: [StringFactor | NumberFactor, string[] | number[]];
-};
+}
-export type StringExpr = {
+export interface StringExpr extends BaseConditionExpr {
operator: StringOperator;
args: [StringFactor, string];
-};
+}
export type ConditionExpr =
| EqualityExpr
@@ -40,42 +49,48 @@ export type ConditionExpr =
| CollectionExpr
| StringExpr;
+// RawStringExpr is used to represent a string that is unable to be parsed as a condition.
+export type RawStringExpr = {
+ type: ExprType.RawString;
+ content: string;
+};
+
export type LogicalExpr = {
+ type: ExprType.ConditionGroup;
operator: LogicalOperator;
- args: (ConditionExpr | ConditionGroupExpr)[];
+ args: (ConditionExpr | RawStringExpr | ConditionGroupExpr)[];
};
export type ConditionGroupExpr = LogicalExpr;
-export type SimpleExpr = ConditionExpr | ConditionGroupExpr;
+export type SimpleExpr = ConditionExpr | ConditionGroupExpr | RawStringExpr;
export const isConditionGroupExpr = (
expr: SimpleExpr
): expr is ConditionGroupExpr => {
- return isLogicalOperator(expr.operator);
+ return expr.type === ExprType.ConditionGroup;
+};
+
+export const isConditionExpr = (expr: SimpleExpr): expr is ConditionExpr => {
+ return expr.type === ExprType.Condition;
};
export const isEqualityExpr = (expr: SimpleExpr): expr is EqualityExpr => {
- return isEqualityOperator(expr.operator);
+ return isConditionExpr(expr) && isEqualityOperator(expr.operator);
};
export const isCompareExpr = (expr: SimpleExpr): expr is CompareExpr => {
- return isCompareOperator(expr.operator);
+ return isConditionExpr(expr) && isCompareOperator(expr.operator);
};
export const isCollectionExpr = (expr: SimpleExpr): expr is CollectionExpr => {
- return isCollectionOperator(expr.operator);
+ return isConditionExpr(expr) && isCollectionOperator(expr.operator);
};
export const isStringExpr = (expr: SimpleExpr): expr is StringExpr => {
- return isStringOperator(expr.operator);
+ return isConditionExpr(expr) && isStringOperator(expr.operator);
};
-export const isConditionExpr = (expr: SimpleExpr): expr is ConditionExpr => {
- return (
- isEqualityExpr(expr) ||
- isCompareExpr(expr) ||
- isCollectionExpr(expr) ||
- isStringExpr(expr)
- );
+export const isRawStringExpr = (expr: SimpleExpr): expr is RawStringExpr => {
+ return expr.type === ExprType.RawString;
};
diff --git a/frontend/src/store/modules/dbGroup.ts b/frontend/src/store/modules/dbGroup.ts
index bfab30f55f..6be7236b9d 100644
--- a/frontend/src/store/modules/dbGroup.ts
+++ b/frontend/src/store/modules/dbGroup.ts
@@ -1,5 +1,5 @@
import { computedAsync } from "@vueuse/core";
-import { isEqual } from "lodash-es";
+import { head, isEqual } from "lodash-es";
import { defineStore } from "pinia";
import type { MaybeRef } from "vue";
import { computed, ref, unref } from "vue";
@@ -184,12 +184,17 @@ export const useDBGroupStore = defineStore("db-group", () => {
validateOnly?: boolean;
}) => {
const createdDatabaseGroup =
- await databaseGroupServiceClient.createDatabaseGroup({
- parent: projectName,
- databaseGroup,
- databaseGroupId,
- validateOnly,
- });
+ await databaseGroupServiceClient.createDatabaseGroup(
+ {
+ parent: projectName,
+ databaseGroup,
+ databaseGroupId,
+ validateOnly,
+ },
+ {
+ silent: validateOnly,
+ }
+ );
if (!validateOnly) {
const composedData = await batchComposeDatabaseGroup([
@@ -209,10 +214,10 @@ export const useDBGroupStore = defineStore("db-group", () => {
}) => {
const celStrings = await batchConvertParsedExprToCELString([
ParsedExpr.fromJSON({
- expr: buildCELExpr(expr),
+ expr: await buildCELExpr(expr),
}),
]);
- const expression = celStrings[0] || "true";
+ const expression = head(celStrings) || "true"; // Fallback to true.
const validateOnlyResourceId = `creating-database-group-${Date.now()}`;
const result = await createDatabaseGroup({
diff --git a/frontend/src/utils/issue/cel.ts b/frontend/src/utils/issue/cel.ts
index c9e78d8d97..b433e86405 100644
--- a/frontend/src/utils/issue/cel.ts
+++ b/frontend/src/utils/issue/cel.ts
@@ -1,6 +1,6 @@
import { cloneDeep, last } from "lodash-es";
import type { SimpleExpr } from "@/plugins/cel";
-import { resolveCELExpr } from "@/plugins/cel";
+import { isRawStringExpr, resolveCELExpr } from "@/plugins/cel";
import type { DatabaseResource } from "@/types";
import type { Expr } from "@/types/proto/google/api/expr/v1alpha1/syntax";
import { batchConvertCELStringToParsedExpr } from "@/utils";
@@ -177,6 +177,11 @@ export const convertFromCELString = async (
};
async function processCondition(expr: SimpleExpr) {
+ // Do not process raw string expression.
+ if (isRawStringExpr(expr)) {
+ return;
+ }
+
if (expr.operator === "_&&_" || expr.operator === "_||_") {
for (const arg of expr.args) {
await processCondition(arg);
@@ -263,6 +268,11 @@ export const convertFromExpr = (expr: Expr): ConditionExpression => {
};
function processCondition(expr: SimpleExpr) {
+ // Do not process raw string expression.
+ if (isRawStringExpr(expr)) {
+ return;
+ }
+
if (expr.operator === "_&&_" || expr.operator === "_||_") {
for (const arg of expr.args) {
processCondition(arg);
diff --git a/frontend/src/utils/v1/database.ts b/frontend/src/utils/v1/database.ts
index 60579e9b91..6d5df6d746 100644
--- a/frontend/src/utils/v1/database.ts
+++ b/frontend/src/utils/v1/database.ts
@@ -1,5 +1,4 @@
import { orderBy } from "lodash-es";
-import type { SimpleExpr } from "@/plugins/cel";
import {
hasFeature,
useCurrentUserIamPolicy,
@@ -243,13 +242,3 @@ export function allowDatabaseV1Access(
return false;
}
-
-export const extractEnvironmentNameListFromExpr = (
- expr: SimpleExpr
-): string[] => {
- const [left, right] = expr.args;
- if (expr.operator === "@in" && left === "resource.environment_name") {
- return right as any as string[];
- }
- return [];
-};
diff --git a/frontend/src/utils/workspaceApprovalSetting.ts b/frontend/src/utils/workspaceApprovalSetting.ts
index 0f2f7daf77..b2284d0c28 100644
--- a/frontend/src/utils/workspaceApprovalSetting.ts
+++ b/frontend/src/utils/workspaceApprovalSetting.ts
@@ -1,7 +1,13 @@
import { cloneDeep, isNumber } from "lodash-es";
import { v4 as uuidv4 } from "uuid";
import type { EqualityExpr, LogicalExpr, SimpleExpr } from "@/plugins/cel";
-import { buildCELExpr, resolveCELExpr } from "@/plugins/cel";
+import {
+ buildCELExpr,
+ ExprType,
+ isConditionExpr,
+ isConditionGroupExpr,
+ resolveCELExpr,
+} from "@/plugins/cel";
import { t, te } from "@/plugins/i18n";
import { useSettingV1Store, useUserStore } from "@/store";
import { userNamePrefix } from "@/store/modules/v1/common";
@@ -136,6 +142,7 @@ const resolveApprovalConfigRules = (rules: LocalApprovalRule[]) => {
};
const resolveLogicAndExpr = (expr: SimpleExpr, rule: LocalApprovalRule) => {
+ if (!isConditionGroupExpr(expr)) return fail(expr, rule);
const { operator, args } = expr;
if (operator !== "_&&_") return fail(expr, rule);
if (!args || args.length !== 2) return fail(expr, rule);
@@ -153,23 +160,27 @@ const resolveApprovalConfigRules = (rules: LocalApprovalRule[]) => {
};
const resolveLogicOrExpr = (expr: SimpleExpr, rule: LocalApprovalRule) => {
+ if (!isConditionGroupExpr(expr)) return fail(expr, rule);
const { operator, args } = expr;
if (operator !== "_||_") return fail(expr, rule);
if (!args || args.length === 0) return fail(expr, rule);
- for (let i = 0; i < args.length; i++) {
- if (args[i].operator === "_&&_") {
- resolveLogicAndExpr(args[i], rule);
+ for (const subExpr of args) {
+ if (!isConditionGroupExpr(subExpr)) {
+ continue;
+ }
+ if (subExpr.operator === "_&&_") {
+ resolveLogicAndExpr(subExpr, rule);
}
- if (args[i].operator === "_||_") {
- resolveLogicOrExpr(args[i], rule);
+ if (subExpr.operator === "_||_") {
+ resolveLogicOrExpr(subExpr, rule);
}
}
};
for (const rule of rules) {
const expr = rule.expr;
- if (!expr) {
+ if (!expr || !isConditionGroupExpr(expr)) {
fail(expr, rule);
continue;
}
@@ -207,7 +218,7 @@ export const buildWorkspaceApprovalSetting = async (
approvalRuleMap.set(i, approvalRule);
const parsed = parsedMap.get(uid) ?? [];
- const parsedExpr = buildParsedExpression(parsed);
+ const parsedExpr = await buildParsedExpression(parsed);
if (parsedExpr.expr) {
exprList.push(parsedExpr);
ruleIndexList.push(i);
@@ -228,6 +239,7 @@ export const buildWorkspaceApprovalSetting = async (
};
const resolveSourceExpr = (expr: SimpleExpr): Risk_Source => {
+ if (!isConditionExpr(expr)) return Risk_Source.UNRECOGNIZED;
const { operator, args } = expr;
if (operator !== "_==_") return Risk_Source.UNRECOGNIZED;
if (!args || args.length !== 2) return Risk_Source.UNRECOGNIZED;
@@ -239,6 +251,7 @@ const resolveSourceExpr = (expr: SimpleExpr): Risk_Source => {
};
const resolveLevelExpr = (expr: SimpleExpr): number => {
+ if (!isConditionExpr(expr)) return Number.NaN;
const { operator, args } = expr;
if (operator !== "_==_") return Number.NaN;
if (!args || args.length !== 2) return Number.NaN;
@@ -264,30 +277,34 @@ const toMap = <T extends { rule: string }>(items: T[]): Map<string, T[]> => {
}, new Map());
};
-const buildParsedExpression = (parsed: ParsedApprovalRule[]) => {
+const buildParsedExpression = async (parsed: ParsedApprovalRule[]) => {
if (parsed.length === 0) {
return ParsedExpr.fromJSON({});
}
- const args = parsed.map<LogicalExpr>(({ source, level }) => {
+ const args = parsed.map(({ source, level }) => {
const sourceExpr: EqualityExpr = {
+ type: ExprType.Condition,
operator: "_==_",
args: ["source", source],
};
const levelExpr: EqualityExpr = {
+ type: ExprType.Condition,
operator: "_==_",
args: ["level", level],
};
return {
+ type: ExprType.Condition,
operator: "_&&_",
args: [sourceExpr, levelExpr],
};
});
const listedOrExpr: LogicalExpr = {
+ type: ExprType.ConditionGroup,
operator: "_||_",
- args,
+ args: args as SimpleExpr[],
};
// expr will be unwrapped to an "&&" expr if listedOrExpr.length === 0
- const expr = buildCELExpr(listedOrExpr);
+ const expr = await buildCELExpr(listedOrExpr);
return ParsedExpr.fromJSON({
expr,
});
diff --git a/frontend/src/views/DatabaseGroupDetail.vue b/frontend/src/views/DatabaseGroupDetail.vue
index 741aa8cb75..75f01b88b3 100644
--- a/frontend/src/views/DatabaseGroupDetail.vue
+++ b/frontend/src/views/DatabaseGroupDetail.vue
@@ -69,6 +69,7 @@
<ExprEditor
:expr="state.expr!"
:allow-admin="false"
+ :enable-raw-expression="true"
:factor-list="FactorList"
:factor-support-dropdown="factorSupportDropdown"
:factor-options-map="DatabaseGroupFactorOptionsMap(project)"