Skip to content

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

feat(approval): implement fallback rules for SOURCE_UNSPECIFIED (#18296)

p0ny615879b7387e
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.go
index 7dc7a10b6a..6ffb023f69 100644
--- a/backend/api/v1/setting_service.go
+++ b/backend/api/v1/setting_service.go
@@ -300,6 +300,18 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
if _, err := common.ConvertUnparsedApproval(rule.Condition); err != nil {
return nil, err
}
+
+ // For SOURCE_UNSPECIFIED (fallback) rules, validate that only project_id is used
+ if rule.Source == v1pb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED {
+ conditionExpr := ""
+ if rule.Condition != nil {
+ conditionExpr = rule.Condition.Expression
+ }
+ if err := common.ValidateFallbackApprovalExpr(conditionExpr); err != nil {
+ return nil, err
+ }
+ }
+
if err := validateApprovalTemplate(rule.Template); err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid approval template: %v, err: %v", rule.Template, err))
}
diff --git a/backend/common/cel.go b/backend/common/cel.go
index 736a280e6b..e9fdbfa791 100644
--- a/backend/common/cel.go
+++ b/backend/common/cel.go
@@ -37,6 +37,35 @@ var ApprovalFactors = []cel.EnvOption{
cel.ParserExpressionSizeLimit(celLimit),
}
+// FallbackApprovalFactors are the variables for SOURCE_UNSPECIFIED fallback rules.
+// These rules can only use resource.project_id since it's the only variable
+// guaranteed to be available across all issue types.
+var FallbackApprovalFactors = []cel.EnvOption{
+ cel.Variable(CELAttributeResourceProjectID, cel.StringType),
+ cel.ParserExpressionSizeLimit(celLimit),
+}
+
+// ValidateFallbackApprovalExpr validates that a CEL expression only uses
+// variables allowed in fallback approval rules (only resource.project_id).
+func ValidateFallbackApprovalExpr(expression string) error {
+ if expression == "" || expression == "true" {
+ return nil
+ }
+
+ e, err := cel.NewEnv(FallbackApprovalFactors...)
+ if err != nil {
+ return errors.Wrap(err, "failed to create CEL env")
+ }
+
+ _, issues := e.Compile(expression)
+ if issues != nil && issues.Err() != nil {
+ return connect.NewError(connect.CodeInvalidArgument,
+ errors.Errorf("fallback rules can only use resource.project_id in conditions: %v", issues.Err()))
+ }
+
+ return nil
+}
+
// IAMPolicyConditionCELAttributes are the variables when evaluating IAM policy condition.
var IAMPolicyConditionCELAttributes = []cel.EnvOption{
cel.Variable(CELAttributeResourceEnvironmentID, cel.StringType),
diff --git a/backend/common/cel_test.go b/backend/common/cel_test.go
index 0405d6e67f..cf41bd595a 100644
--- a/backend/common/cel_test.go
+++ b/backend/common/cel_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"time"
+ "github.com/google/cel-go/cel"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -113,3 +114,77 @@ func TestGetQueryExportFactors(t *testing.T) {
a.Equal(tt.want, *factors)
}
}
+
+func TestFallbackApprovalFactors(t *testing.T) {
+ a := require.New(t)
+
+ // Fallback factors should only contain project_id
+ a.Len(FallbackApprovalFactors, 2) // 1 variable + 1 size limit
+
+ // Verify the first option is the project_id variable
+ // CEL EnvOptions are opaque, so we verify by creating an env
+ // and checking that project_id works but environment_id doesn't
+}
+
+func TestFallbackApprovalFactorsOnlyAllowsProjectId(t *testing.T) {
+ a := require.New(t)
+
+ // Create env with fallback factors
+ e, err := cel.NewEnv(FallbackApprovalFactors...)
+ a.NoError(err)
+
+ // resource.project_id should compile
+ _, issues := e.Compile(`resource.project_id == "proj-123"`)
+ a.Nil(issues)
+
+ // resource.environment_id should NOT compile (not in fallback factors)
+ _, issues = e.Compile(`resource.environment_id == "prod"`)
+ a.NotNil(issues)
+ a.Error(issues.Err())
+}
+
+func TestValidateFallbackApprovalExpr(t *testing.T) {
+ tests := []struct {
+ name string
+ expression string
+ wantErr bool
+ }{
+ {
+ name: "valid project_id condition",
+ expression: `resource.project_id == "proj-123"`,
+ wantErr: false,
+ },
+ {
+ name: "valid true condition",
+ expression: `true`,
+ wantErr: false,
+ },
+ {
+ name: "invalid environment_id condition",
+ expression: `resource.environment_id == "prod"`,
+ wantErr: true,
+ },
+ {
+ name: "invalid statement condition",
+ expression: `statement.affected_rows > 100`,
+ wantErr: true,
+ },
+ {
+ name: "empty condition",
+ expression: ``,
+ wantErr: false, // empty is allowed
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ a := require.New(t)
+ err := ValidateFallbackApprovalExpr(tt.expression)
+ if tt.wantErr {
+ a.Error(err)
+ } else {
+ a.NoError(err)
+ }
+ })
+ }
+}
diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.go
index 380c5b9c9a..2773b9ee37 100644
--- a/backend/runner/approval/runner.go
+++ b/backend/runner/approval/runner.go
@@ -275,17 +275,17 @@ func calculateRiskLevelFromCELVars(celVarsList []map[string]any) storepb.RiskLev
}
// getApprovalTemplate finds the first matching approval template for the given source and CEL variables.
-// After the risk layer removal (3.13), approval rules are directly evaluated with full CEL context.
-// The rules are ordered by priority (HIGH risk rules first, then MODERATE, then LOW, then UNSPECIFIED).
-// First matching rule wins.
+// Uses two-phase matching:
+// Phase 1: Try source-specific rules (filtered by riskSource)
+// Phase 2: Try SOURCE_UNSPECIFIED fallback rules (with limited CEL variables)
//
// Parameters:
// - approvalSetting: workspace approval setting containing rules
// - riskSource: the approval source enum (DDL, DML, CREATE_DATABASE, EXPORT_DATA, REQUEST_ROLE)
// - celVarsList: list of CEL variable maps (one per task/component in the issue)
//
-// For each rule filtered by source, we check if ANY of the celVars maps matches the condition.
-// This preserves the "maximum risk" behavior: if any task matches a high-priority rule, that template is used.
+// For each rule, we check if ANY of the celVars maps matches the condition.
+// First matching rule wins within each phase.
func getApprovalTemplate(approvalSetting *storepb.WorkspaceApprovalSetting, riskSource storepb.WorkspaceApprovalSetting_Rule_Source, celVarsList []map[string]any) (*storepb.ApprovalTemplate, error) {
if len(approvalSetting.Rules) == 0 {
return nil, nil
@@ -294,25 +294,43 @@ func getApprovalTemplate(approvalSetting *storepb.WorkspaceApprovalSetting, risk
return nil, nil
}
- e, err := cel.NewEnv(common.ApprovalFactors...)
+ // Phase 1: Try source-specific rules
+ template, err := matchRulesForSource(approvalSetting.Rules, riskSource, celVarsList, common.ApprovalFactors)
+ if err != nil {
+ return nil, err
+ }
+ if template != nil {
+ return template, nil
+ }
+
+ // Phase 2: Try SOURCE_UNSPECIFIED fallback rules with limited CEL variables
+ fallbackVars := buildFallbackCELVars(celVarsList)
+ template, err = matchRulesForSource(approvalSetting.Rules, storepb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED, fallbackVars, common.FallbackApprovalFactors)
+ if err != nil {
+ return nil, err
+ }
+ return template, nil
+}
+
+// matchRulesForSource evaluates rules for a specific source type.
+func matchRulesForSource(rules []*storepb.WorkspaceApprovalSetting_Rule, source storepb.WorkspaceApprovalSetting_Rule_Source, celVarsList []map[string]any, celFactors []cel.EnvOption) (*storepb.ApprovalTemplate, error) {
+ e, err := cel.NewEnv(celFactors...)
if err != nil {
return nil, err
}
- // Rules are already ordered by priority (migration ensures this)
- // First matching rule wins
- for _, rule := range approvalSetting.Rules {
+ for _, rule := range rules {
// Filter by source
- if rule.Source != riskSource {
+ if rule.Source != source {
continue
}
- // Empty condition means this rule always matches (fallback rule)
+ // Empty condition means skip (not a catch-all)
if rule.Condition == nil || rule.Condition.Expression == "" {
continue
}
- // Special case: "true" expression always matches (fallback from UNSPECIFIED level)
+ // Special case: "true" expression always matches
if rule.Condition.Expression == "true" {
return rule.Template, nil
}
@@ -346,6 +364,25 @@ func getApprovalTemplate(approvalSetting *storepb.WorkspaceApprovalSetting, risk
return nil, nil
}
+// buildFallbackCELVars extracts only the project_id from the first CEL vars map.
+// Fallback rules can only use resource.project_id.
+func buildFallbackCELVars(celVarsList []map[string]any) []map[string]any {
+ if len(celVarsList) == 0 {
+ return nil
+ }
+
+ // Extract project_id from the first vars map
+ firstVars := celVarsList[0]
+ projectID, ok := firstVars[common.CELAttributeResourceProjectID]
+ if !ok {
+ return nil
+ }
+
+ return []map[string]any{
+ {common.CELAttributeResourceProjectID: projectID},
+ }
+}
+
// buildCELVariablesForIssue builds the CEL variable maps for evaluating approval rules.
// Returns a list of CEL variable maps (one per task/component), done flag, and error.
// done=false means the caller should retry later (e.g., waiting for plan check runs).
diff --git a/backend/tests/approval_test.go b/backend/tests/approval_test.go
index cfcebf91fc..79d3eb9b48 100644
--- a/backend/tests/approval_test.go
+++ b/backend/tests/approval_test.go
@@ -3,6 +3,7 @@ package tests
import (
"context"
"fmt"
+ "strings"
"testing"
"time"
@@ -434,3 +435,354 @@ func TestApprovalRuleNoMatch(t *testing.T) {
a.True(issue.ApprovalStatus == v1pb.Issue_APPROVED || issue.ApprovalStatus == v1pb.Issue_SKIPPED,
"Issue should be auto-approved when no rule matches, got status: %v", issue.ApprovalStatus)
}
+
+// TestFallbackRuleValidation tests that SOURCE_UNSPECIFIED rules
+// can only use resource.project_id in conditions.
+func TestFallbackRuleValidation(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Test 1: Valid fallback rule with project_id should succeed
+ _, err = ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
+ AllowMissing: true,
+ Setting: &v1pb.Setting{
+ Name: "settings/WORKSPACE_APPROVAL",
+ Value: &v1pb.Value{
+ Value: &v1pb.Value_WorkspaceApprovalSettingValue{
+ WorkspaceApprovalSettingValue: &v1pb.WorkspaceApprovalSetting{
+ Rules: []*v1pb.WorkspaceApprovalSetting_Rule{
+ {
+ Source: v1pb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED,
+ Condition: &expr.Expr{
+ Expression: `resource.project_id == "proj-123"`,
+ },
+ Template: &v1pb.ApprovalTemplate{
+ Title: "Valid Fallback Rule",
+ Flow: &v1pb.ApprovalFlow{Roles: []string{"roles/workspaceOwner"}},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }))
+ a.NoError(err, "Fallback rule with project_id should be valid")
+
+ // Test 2: Invalid fallback rule with environment_id should fail
+ _, err = ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
+ AllowMissing: true,
+ Setting: &v1pb.Setting{
+ Name: "settings/WORKSPACE_APPROVAL",
+ Value: &v1pb.Value{
+ Value: &v1pb.Value_WorkspaceApprovalSettingValue{
+ WorkspaceApprovalSettingValue: &v1pb.WorkspaceApprovalSetting{
+ Rules: []*v1pb.WorkspaceApprovalSetting_Rule{
+ {
+ Source: v1pb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED,
+ Condition: &expr.Expr{
+ Expression: `resource.environment_id == "prod"`,
+ },
+ Template: &v1pb.ApprovalTemplate{
+ Title: "Invalid Fallback Rule",
+ Flow: &v1pb.ApprovalFlow{Roles: []string{"roles/workspaceOwner"}},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }))
+ a.Error(err, "Fallback rule with environment_id should be rejected")
+ a.Contains(err.Error(), "fallback rules can only use resource.project_id")
+}
+
+// TestFallbackRuleMatchesWhenSourceSpecificDoesNot tests that
+// SOURCE_UNSPECIFIED rules are used as fallback when no source-specific rules match.
+func TestFallbackRuleMatchesWhenSourceSpecificDoesNot(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create instance in TEST environment (not prod)
+ instanceDir := t.TempDir()
+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: generateRandomString("inst"),
+ Instance: &v1pb.Instance{
+ Title: "Test Instance",
+ Engine: v1pb.Engine_SQLITE,
+ Environment: stringPtr("environments/test"),
+ Activation: true,
+ DataSources: []*v1pb.DataSource{{
+ Type: v1pb.DataSourceType_ADMIN,
+ Host: instanceDir,
+ Id: "admin",
+ }},
+ },
+ }))
+ a.NoError(err)
+
+ // Create database
+ dbName := generateRandomString("db")
+ err = ctl.createDatabaseV2(ctx, ctl.project, instanceResp.Msg, nil, dbName, "")
+ a.NoError(err)
+
+ // Create rules:
+ // 1. Source-specific rule for prod only (won't match test environment)
+ // 2. Fallback rule for this project (should match)
+ projectID := strings.TrimPrefix(ctl.project.Name, "projects/")
+ _, err = ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
+ AllowMissing: true,
+ Setting: &v1pb.Setting{
+ Name: "settings/WORKSPACE_APPROVAL",
+ Value: &v1pb.Value{
+ Value: &v1pb.Value_WorkspaceApprovalSettingValue{
+ WorkspaceApprovalSettingValue: &v1pb.WorkspaceApprovalSetting{
+ Rules: []*v1pb.WorkspaceApprovalSetting_Rule{
+ {
+ // Source-specific: only matches prod
+ Source: v1pb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE,
+ Condition: &expr.Expr{
+ Expression: `resource.environment_id == "prod"`,
+ },
+ Template: &v1pb.ApprovalTemplate{
+ Title: "Prod Only Rule",
+ Flow: &v1pb.ApprovalFlow{Roles: []string{"roles/workspaceOwner"}},
+ },
+ },
+ {
+ // Fallback: matches this project
+ Source: v1pb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED,
+ Condition: &expr.Expr{
+ Expression: fmt.Sprintf(`resource.project_id == "%s"`, projectID),
+ },
+ Template: &v1pb.ApprovalTemplate{
+ Title: "Fallback Rule",
+ Flow: &v1pb.ApprovalFlow{Roles: []string{"roles/projectOwner"}},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }))
+ a.NoError(err)
+
+ // Create sheet with DDL statement
+ sheet, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{
+ Parent: ctl.project.Name,
+ Sheet: &v1pb.Sheet{
+ Title: "Test DDL Sheet",
+ Content: []byte("CREATE TABLE fallback_test (id INTEGER PRIMARY KEY);"),
+ },
+ }))
+ a.NoError(err)
+
+ // Create plan targeting test environment
+ planResp, err := ctl.planServiceClient.CreatePlan(ctx, connect.NewRequest(&v1pb.CreatePlanRequest{
+ Parent: ctl.project.Name,
+ Plan: &v1pb.Plan{
+ Title: "Test Fallback Plan",
+ Specs: []*v1pb.Plan_Spec{{
+ Id: uuid.NewString(),
+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{
+ Targets: []string{fmt.Sprintf("%s/databases/%s", instanceResp.Msg.Name, dbName)},
+ Sheet: sheet.Msg.Name,
+ Type: v1pb.DatabaseChangeType_MIGRATE,
+ },
+ },
+ }},
+ },
+ }))
+ a.NoError(err)
+
+ // Create issue
+ issueResp, err := ctl.issueServiceClient.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{
+ Parent: ctl.project.Name,
+ Issue: &v1pb.Issue{
+ Title: "Test Issue for Fallback Rule",
+ Type: v1pb.Issue_DATABASE_CHANGE,
+ Description: "Testing fallback rule matching",
+ Plan: planResp.Msg.Name,
+ },
+ }))
+ a.NoError(err)
+
+ // Wait for approval finding to complete
+ var issue *v1pb.Issue
+ for i := 0; i < 5; i++ {
+ if i > 0 {
+ time.Sleep(3 * time.Second)
+ }
+ issueGetResp, err := ctl.issueServiceClient.GetIssue(ctx, connect.NewRequest(&v1pb.GetIssueRequest{
+ Name: issueResp.Msg.Name,
+ }))
+ a.NoError(err)
+ issue = issueGetResp.Msg
+ if issue.ApprovalStatus != v1pb.Issue_CHECKING {
+ break
+ }
+ }
+
+ // Verify fallback rule was applied
+ a.NotNil(issue)
+ a.NotEqual(v1pb.Issue_CHECKING, issue.ApprovalStatus)
+ a.NotEqual(v1pb.Issue_ERROR, issue.ApprovalStatus)
+ a.NotNil(issue.ApprovalTemplate, "Fallback approval template should be assigned")
+ a.Equal("Fallback Rule", issue.GetApprovalTemplate().GetTitle(), "Fallback rule should be applied")
+}
+
+// TestSourceSpecificRuleTakesPriorityOverFallback verifies that
+// source-specific rules are always tried before fallback rules.
+func TestSourceSpecificRuleTakesPriorityOverFallback(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create instance in prod environment
+ instanceDir := t.TempDir()
+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: generateRandomString("inst"),
+ Instance: &v1pb.Instance{
+ Title: "Prod Instance",
+ Engine: v1pb.Engine_SQLITE,
+ Environment: stringPtr("environments/prod"),
+ Activation: true,
+ DataSources: []*v1pb.DataSource{{
+ Type: v1pb.DataSourceType_ADMIN,
+ Host: instanceDir,
+ Id: "admin",
+ }},
+ },
+ }))
+ a.NoError(err)
+
+ // Create database
+ dbName := generateRandomString("db")
+ err = ctl.createDatabaseV2(ctx, ctl.project, instanceResp.Msg, nil, dbName, "")
+ a.NoError(err)
+
+ // Create rules with fallback FIRST in the list, but source-specific should still win
+ projectID := strings.TrimPrefix(ctl.project.Name, "projects/")
+ _, err = ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
+ AllowMissing: true,
+ Setting: &v1pb.Setting{
+ Name: "settings/WORKSPACE_APPROVAL",
+ Value: &v1pb.Value{
+ Value: &v1pb.Value_WorkspaceApprovalSettingValue{
+ WorkspaceApprovalSettingValue: &v1pb.WorkspaceApprovalSetting{
+ Rules: []*v1pb.WorkspaceApprovalSetting_Rule{
+ {
+ // Fallback rule FIRST in list
+ Source: v1pb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED,
+ Condition: &expr.Expr{
+ Expression: fmt.Sprintf(`resource.project_id == "%s"`, projectID),
+ },
+ Template: &v1pb.ApprovalTemplate{
+ Title: "Fallback Rule (should NOT be used)",
+ Flow: &v1pb.ApprovalFlow{Roles: []string{"roles/projectOwner"}},
+ },
+ },
+ {
+ // Source-specific rule SECOND in list
+ Source: v1pb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE,
+ Condition: &expr.Expr{
+ Expression: `resource.environment_id == "prod"`,
+ },
+ Template: &v1pb.ApprovalTemplate{
+ Title: "Source Specific Rule (should be used)",
+ Flow: &v1pb.ApprovalFlow{Roles: []string{"roles/workspaceOwner"}},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }))
+ a.NoError(err)
+
+ // Create sheet with DDL statement
+ sheet, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{
+ Parent: ctl.project.Name,
+ Sheet: &v1pb.Sheet{
+ Title: "Test DDL Sheet",
+ Content: []byte("CREATE TABLE priority_test (id INTEGER PRIMARY KEY);"),
+ },
+ }))
+ a.NoError(err)
+
+ // Create plan
+ planResp, err := ctl.planServiceClient.CreatePlan(ctx, connect.NewRequest(&v1pb.CreatePlanRequest{
+ Parent: ctl.project.Name,
+ Plan: &v1pb.Plan{
+ Title: "Test Priority Plan",
+ Specs: []*v1pb.Plan_Spec{{
+ Id: uuid.NewString(),
+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{
+ Targets: []string{fmt.Sprintf("%s/databases/%s", instanceResp.Msg.Name, dbName)},
+ Sheet: sheet.Msg.Name,
+ Type: v1pb.DatabaseChangeType_MIGRATE,
+ },
+ },
+ }},
+ },
+ }))
+ a.NoError(err)
+
+ // Create issue
+ issueResp, err := ctl.issueServiceClient.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{
+ Parent: ctl.project.Name,
+ Issue: &v1pb.Issue{
+ Title: "Test Issue for Priority",
+ Type: v1pb.Issue_DATABASE_CHANGE,
+ Description: "Testing source-specific priority over fallback",
+ Plan: planResp.Msg.Name,
+ },
+ }))
+ a.NoError(err)
+
+ // Wait for approval finding to complete
+ var issue *v1pb.Issue
+ for i := 0; i < 5; i++ {
+ if i > 0 {
+ time.Sleep(3 * time.Second)
+ }
+ issueGetResp, err := ctl.issueServiceClient.GetIssue(ctx, connect.NewRequest(&v1pb.GetIssueRequest{
+ Name: issueResp.Msg.Name,
+ }))
+ a.NoError(err)
+ issue = issueGetResp.Msg
+ if issue.ApprovalStatus != v1pb.Issue_CHECKING {
+ break
+ }
+ }
+
+ // Verify source-specific rule was applied, NOT the fallback
+ a.NotNil(issue)
+ a.NotEqual(v1pb.Issue_CHECKING, issue.ApprovalStatus)
+ a.NotEqual(v1pb.Issue_ERROR, issue.ApprovalStatus)
+ a.NotNil(issue.ApprovalTemplate)
+ a.Equal("Source Specific Rule (should be used)", issue.GetApprovalTemplate().GetTitle(),
+ "Source-specific rule should take priority over fallback even when fallback is first in list")
+}
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
index d933700919..075dc59aa2 100644
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
+++ b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
@@ -19,6 +19,13 @@
</div>
<div class="flex-1 flex flex-col px-6 py-4 gap-y-4 overflow-y-auto">
+ <div
+ v-if="isFallback"
+ class="text-sm text-amber-600 bg-amber-50 p-3 rounded"
+ >
+ {{ $t("custom-approval.approval-flow.fallback-rules-hint") }}
+ </div>
+
<div v-if="mode === 'create'" class="flex flex-col gap-y-2">
<h3 class="font-medium text-sm text-control">
{{ $t("custom-approval.approval-flow.template.presets-title") }}
@@ -166,6 +173,7 @@ const props = defineProps<{
mode: "create" | "edit";
source: WorkspaceApprovalSetting_Rule_Source;
rule?: LocalApprovalRule;
+ isFallback?: boolean;
}>();
const emit = defineEmits<{
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesPanel.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesPanel.vue
index 1768d0f858..d9faacb3e2 100644
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesPanel.vue
+++ b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesPanel.vue
@@ -18,5 +18,6 @@ const supportedSourceList = computed(() => [
WorkspaceApprovalSetting_Rule_Source.CREATE_DATABASE,
WorkspaceApprovalSetting_Rule_Source.EXPORT_DATA,
WorkspaceApprovalSetting_Rule_Source.REQUEST_ROLE,
+ WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED,
]);
</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesSection.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesSection.vue
index 054b906c0f..7fe2b8f5f2 100644
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesSection.vue
+++ b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesSection.vue
@@ -26,6 +26,7 @@
:mode="modalMode"
:source="source"
:rule="editingRule"
+ :is-fallback="isFallback"
@save="handleSaveRule"
/>
</div>
@@ -40,7 +41,7 @@ import { useI18n } from "vue-i18n";
import { MiniActionButton } from "@/components/v2";
import { pushNotification, useWorkspaceApprovalSettingStore } from "@/store";
import type { LocalApprovalRule } from "@/types";
-import type { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
+import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
import { formatApprovalFlow } from "@/utils";
import { approvalSourceText } from "../../common/utils";
import { useCustomApprovalContext } from "../context";
@@ -50,6 +51,10 @@ const props = defineProps<{
source: WorkspaceApprovalSetting_Rule_Source;
}>();
+const isFallback = computed(
+ () => props.source === WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED
+);
+
const { t } = useI18n();
const store = useWorkspaceApprovalSettingStore();
const context = useCustomApprovalContext();
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts b/frontend/src/components/CustomApproval/Settings/components/common/utils.ts
index a356c0c304..dc2289e50f 100644
--- a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts
+++ b/frontend/src/components/CustomApproval/Settings/components/common/utils.ts
@@ -203,7 +203,7 @@ export const approvalSourceText = (
) => {
switch (source) {
case WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED:
- return t("common.all");
+ return t("custom-approval.approval-flow.fallback-rules");
case WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE:
return t("custom-approval.risk-rule.risk.namespace.change_database");
case WorkspaceApprovalSetting_Rule_Source.CREATE_DATABASE:
@@ -251,7 +251,11 @@ export const ApprovalSourceFactorMap: Map<
export const getApprovalFactorList = (
source: WorkspaceApprovalSetting_Rule_Source
-) => {
+): Factor[] => {
+ // Fallback rules (SOURCE_UNSPECIFIED) can only use resource.project_id
+ if (source === WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED) {
+ return [CEL_ATTRIBUTE_RESOURCE_PROJECT_ID] as Factor[];
+ }
return ApprovalSourceFactorMap.get(source) ?? [];
};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 9cfcb69755..f0dea76343 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2656,6 +2656,8 @@
},
"add-rule": "Add rule",
"edit-rule": "Edit rule",
+ "fallback-rules": "Fallback Rules",
+ "fallback-rules-hint": "Fallback rules are evaluated only when no other rules match.",
"template": {
"presets-title": "Presets",
"presets": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 43a7ab7130..5868c51d04 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2656,6 +2656,8 @@
},
"add-rule": "Agregar regla",
"edit-rule": "Editar regla",
+ "fallback-rules": "Reglas de respaldo",
+ "fallback-rules-hint": "Las reglas de respaldo solo se evalúan cuando ninguna otra regla coincide.",
"template": {
"presets-title": "Plantillas",
"presets": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 18af942ff5..a796247040 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2656,6 +2656,8 @@
},
"add-rule": "ルールを追加",
"edit-rule": "ルールを編集",
+ "fallback-rules": "フォールバックルール",
+ "fallback-rules-hint": "フォールバックルールは、他のルールが一致しない場合にのみ評価されます。",
"template": {
"presets-title": "プリセット",
"presets": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index c37e7c6fb0..fbc3715652 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2656,6 +2656,8 @@
},
"add-rule": "Thêm quy tắc",
"edit-rule": "Chỉnh sửa quy tắc",
+ "fallback-rules": "Quy tắc dự phòng",
+ "fallback-rules-hint": "Quy tắc dự phòng chỉ được đánh giá khi không có quy tắc nào khác khớp.",
"template": {
"presets-title": "Mẫu có sẵn",
"presets": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 9e93a7776d..b099db05bc 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2656,6 +2656,8 @@
},
"add-rule": "添加规则",
"edit-rule": "编辑规则",
+ "fallback-rules": "兜底规则",
+ "fallback-rules-hint": "兜底规则仅在没有其他规则匹配时才会被评估。",
"template": {
"presets-title": "预设模板",
"presets": {