Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support issue labels in approval CEL (#20758)
p0ny45f57adc37cf
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex 4badd4f973..98e54a9bce 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -928,22 +928,16 @@ func (s *IssueService) updateIssueApprovalPayload(ctx context.Context, issue *streturn updatedIssue, nil}- updated, err := s.store.UpdateIssuePayloadIfCurrentApprovalInputVersion(ctx, issue.ProjectID, issue.UID, payloadPatch, approvalInputVersion)- if err != nil {- return nil, errors.Wrapf(err, "failed to update issue")- }- if !updated {- return nil, errStaleApprovalFinding- }-- uid := issue.UID- updatedIssue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{- Workspace: common.GetWorkspaceIDFromContext(ctx),- ProjectIDs: []string{issue.ProjectID},- UID: &uid,+ updatedIssue, err := s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: payloadPatch,+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireIssueApprovalInputVersion: &approvalInputVersion,})if err != nil {- return nil, errors.Wrapf(err, "failed to refresh issue")+ if errors.Is(err, store.ErrIssueUpdateSkipped) {+ return nil, errStaleApprovalFinding+ }+ return nil, errors.Wrapf(err, "failed to update issue")}if updatedIssue == nil {return nil, errors.New("issue not found after update")@@ -1112,7 +1106,10 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1pupdateMasks := map[string]bool{}patch := &store.UpdateIssueMessage{}+ hasDirectIssueUpdate := falsevar issueCommentCreates []*store.IssueCommentMessage+ var labelsChangedWithApprovalReset bool+ var labelsForApprovalReset []stringfor _, path := range req.Msg.UpdateMask.Paths {updateMasks[path] = trueswitch path {@@ -1128,6 +1125,7 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1p}patch.Title = &trimmed+ hasDirectIssueUpdate = trueissueCommentCreates = append(issueCommentCreates, &store.IssueCommentMessage{IssueUID: issue.UID,@@ -1146,6 +1144,7 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1pcontinue}patch.Description = &req.Msg.Issue.Description+ hasDirectIssueUpdate = trueissueCommentCreates = append(issueCommentCreates, &store.IssueCommentMessage{IssueUID: issue.UID,@@ -1164,13 +1163,23 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1pif slices.Equal(issue.Payload.Labels, labels) {continue}- if len(labels) == 0 {- patch.RemoveLabels = true+ resetApprovalForLabels, err := s.shouldResetApprovalForIssueLabels(ctx, issue)+ if err != nil {+ return nil, err+ }+ if resetApprovalForLabels {+ labelsChangedWithApprovalReset = true+ labelsForApprovalReset = labels} else {- if patch.PayloadUpsert == nil {- patch.PayloadUpsert = &storepb.Issue{}+ if len(labels) == 0 {+ patch.RemoveLabels = true+ } else {+ if patch.PayloadUpsert == nil {+ patch.PayloadUpsert = &storepb.Issue{}+ }+ patch.PayloadUpsert.Labels = labels}- patch.PayloadUpsert.Labels = labels+ hasDirectIssueUpdate = true}issueCommentCreates = append(issueCommentCreates, &store.IssueCommentMessage{@@ -1188,9 +1197,25 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1p}}- issue, err = s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, patch)- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update issue"))+ if hasDirectIssueUpdate {+ issue, err = s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, patch)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update issue"))+ }+ }++ if labelsChangedWithApprovalReset {+ updatedIssue, approvalResetApplied, err := s.store.UpdateIssueLabelsAndMaybeResetApproval(ctx, issue.ProjectID, issue.UID, labelsForApprovalReset)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to update issue labels"))+ }+ if updatedIssue == nil {+ return nil, connect.NewError(connect.CodeNotFound, errors.New("issue not found after issue label update"))+ }+ issue = updatedIssue+ if approvalResetApplied {+ s.bus.ApprovalCheckChan <- bus.IssueRef{ProjectID: issue.ProjectID, UID: issue.UID}+ }}for _, ic := range issueCommentCreates {@@ -1207,6 +1232,25 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1preturn connect.NewResponse(issueV1), nil}+func (s *IssueService) shouldResetApprovalForIssueLabels(ctx context.Context, issue *store.IssueMessage) (bool, error) {+ if issue.Type != storepb.Issue_DATABASE_CHANGE || issue.PlanUID == nil {+ return false, nil+ }+ plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{ProjectID: issue.ProjectID, UID: issue.PlanUID})+ if err != nil {+ return false, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get plan for issue label update"))+ }+ if plan == nil {+ return false, connect.NewError(connect.CodeNotFound, errors.New("plan not found for issue label update"))+ }+ for _, spec := range plan.Config.GetSpecs() {+ if _, ok := spec.Config.(*storepb.PlanConfig_Spec_ChangeDatabaseConfig); ok {+ return true, nil+ }+ }+ return false, nil+}+// BatchUpdateIssuesStatus batch updates issues status.func (s *IssueService) BatchUpdateIssuesStatus(ctx context.Context, req *connect.Request[v1pb.BatchUpdateIssuesStatusRequest]) (*connect.Response[v1pb.BatchUpdateIssuesStatusResponse], error) {user, ok := GetUserFromContext(ctx)diff --git a/backend/api/v1/issue_service_test.go b/backend/api/v1/issue_service_test.gonew file mode 100644index 0000000000..b5c53a80a9--- /dev/null+++ b/backend/api/v1/issue_service_test.go@@ -0,0 +1,310 @@+package v1++import (+ "context"+ "fmt"+ "testing"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"+ "google.golang.org/protobuf/types/known/fieldmaskpb"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+ "github.com/bytebase/bytebase/backend/component/bus"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+ "github.com/bytebase/bytebase/backend/migrator"+ "github.com/bytebase/bytebase/backend/store"++ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"+)++func TestUpdateIssueLabelsResetsApprovalBeforeRollout(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ service := newIssueServiceForTest(t, stores)+ _, issue := createIssueServiceApprovalIssue(ctx, t, stores)++ updateIssueLabels(ctx, t, service, issue, []string{"environment:staging"})++ got := getIssueForTest(ctx, t, stores, issue.UID)+ require.Equal(t, []string{"environment:staging"}, got.Payload.GetLabels())+ require.False(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueLabelsClearedBeforeRolloutResetsApproval(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ service := newIssueServiceForTest(t, stores)+ _, issue := createIssueServiceApprovalIssue(ctx, t, stores)++ updateIssueLabels(ctx, t, service, issue, nil)++ got := getIssueForTest(ctx, t, stores, issue.UID)+ require.Empty(t, got.Payload.GetLabels())+ require.False(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+ require.Len(t, service.bus.ApprovalCheckChan, 1)+}++func TestUpdateIssueLabelsDoesNotResetApprovalAfterRollout(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ service := newIssueServiceForTest(t, stores)+ plan, issue := createIssueServiceApprovalIssue(ctx, t, stores)++ approvalInputVersion := int64(2)+ marked, _, err := stores.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)+ require.NoError(t, err)+ require.True(t, marked)++ updateIssueLabels(ctx, t, service, issue, []string{"environment:staging"})++ got := getIssueForTest(ctx, t, stores, issue.UID)+ require.Equal(t, []string{"environment:staging"}, got.Payload.GetLabels())+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+ require.Len(t, service.bus.ApprovalCheckChan, 0)+}++func TestCreateRolloutAndPendingTasksAllowsUnapprovedIssueWhenApprovalNotRequired(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ plan, issue := createIssueServiceApprovalIssue(ctx, t, stores)+ approvalInputVersion := int64(2)+ _, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: 2,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ })+ require.NoError(t, err)++ stalePlan := *plan+ stalePlan.Config = &storepb.PlanConfig{ApprovalInputVersion: 1}+ err = CreateRolloutAndPendingTasks(ctx, stores, "[email protected]", &stalePlan, issue, &store.ProjectMessage{+ ResourceID: "project-a",+ Setting: &storepb.Project{RequireIssueApproval: false},+ }, []*store.TaskMessage{})+ require.Error(t, err)+ require.True(t, IsStaleRolloutApprovalError(err))++ err = CreateRolloutAndPendingTasks(ctx, stores, "[email protected]", plan, issue, &store.ProjectMessage{+ ResourceID: "project-a",+ Setting: &storepb.Project{RequireIssueApproval: false},+ }, []*store.TaskMessage{})+ require.NoError(t, err)++ gotPlan, err := stores.GetPlan(ctx, &store.FindPlanMessage{ProjectID: "project-a", UID: &plan.UID})+ require.NoError(t, err)+ require.True(t, gotPlan.Config.GetHasRollout())++ gotIssue := getIssueForTest(ctx, t, stores, issue.UID)+ require.Equal(t, storepb.Issue_DONE, gotIssue.Status)+}++func TestUpdateIssueLabelsNoopDoesNotResetApproval(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ service := newIssueServiceForTest(t, stores)+ _, issue := createIssueServiceApprovalIssue(ctx, t, stores)++ updateIssueLabels(ctx, t, service, issue, []string{" environment:prod ", "environment:prod"})++ got := getIssueForTest(ctx, t, stores, issue.UID)+ require.Equal(t, []string{"environment:prod"}, got.Payload.GetLabels())+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+ require.Len(t, service.bus.ApprovalCheckChan, 0)+}++func TestUpdateIssueLabelsDoesNotResetCreateDatabaseApproval(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ service := newIssueServiceForTest(t, stores)+ _, issue := createIssueServiceCreateDatabaseApprovalIssue(ctx, t, stores)++ updateIssueLabels(ctx, t, service, issue, []string{"environment:staging"})++ got := getIssueForTest(ctx, t, stores, issue.UID)+ require.Equal(t, []string{"environment:staging"}, got.Payload.GetLabels())+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+ require.Len(t, service.bus.ApprovalCheckChan, 0)+}++func setupIssueServiceTestStore(ctx context.Context, t *testing.T) *store.Store {+ t.Helper()++ container := testcontainer.GetTestPgContainer(ctx, t)+ t.Cleanup(func() { container.Close(ctx) })++ db := container.GetDB()+ require.NoError(t, migrator.MigrateSchema(ctx, db))++ _, err := db.ExecContext(ctx, `+ INSERT INTO workspace (resource_id) VALUES ('default');+ INSERT INTO principal (name, email, password_hash) VALUES ('creator', '[email protected]', 'unused');+ INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', 'default', 'Project A');+ `)+ require.NoError(t, err)++ pgURL := fmt.Sprintf(+ "host=%s port=%s user=postgres password=root-password database=postgres",+ container.GetHost(), container.GetPort(),+ )+ stores, err := store.New(ctx, pgURL, false)+ require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, stores.Close()) })+ return stores+}++func issueServiceTestContext() context.Context {+ ctx := context.Background()+ ctx = context.WithValue(ctx, common.WorkspaceIDContextKey, "default")+ ctx = context.WithValue(ctx, common.UserContextKey, &store.UserMessage{+ Email: "[email protected]",+ Name: "creator",+ })+ return ctx+}++func newIssueServiceForTest(t *testing.T, stores *store.Store) *IssueService {+ t.Helper()++ b, err := bus.New()+ require.NoError(t, err)+ return NewIssueService(stores, nil, b, nil, nil)+}++func createIssueServiceApprovalIssue(ctx context.Context, t *testing.T, stores *store.Store) (*store.PlanMessage, *store.IssueMessage) {+ t.Helper()++ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{+ ApprovalInputVersion: 2,+ Specs: []*storepb.PlanConfig_Spec{+ {+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{+ Targets: []string{"instances/prod/databases/app"},+ },+ },+ },+ },+ },+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"environment:prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalTemplate: &storepb.ApprovalTemplate{+ Flow: &storepb.ApprovalFlow{Roles: []string{"roles/projectOwner"}},+ Title: "manual approval",+ },+ Approvers: []*storepb.IssuePayloadApproval_Approver{+ {+ Status: storepb.IssuePayloadApproval_Approver_APPROVED,+ Principal: common.FormatUserEmail("[email protected]"),+ },+ },+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)+ return plan, issue+}++func createIssueServiceCreateDatabaseApprovalIssue(ctx context.Context, t *testing.T, stores *store.Store) (*store.PlanMessage, *store.IssueMessage) {+ t.Helper()++ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{+ ApprovalInputVersion: 2,+ Specs: []*storepb.PlanConfig_Spec{+ {+ Config: &storepb.PlanConfig_Spec_CreateDatabaseConfig{+ CreateDatabaseConfig: &storepb.PlanConfig_CreateDatabaseConfig{+ Target: "instances/prod/databases/app",+ },+ },+ },+ },+ },+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"environment:prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalTemplate: &storepb.ApprovalTemplate{+ Flow: &storepb.ApprovalFlow{Roles: []string{"roles/projectOwner"}},+ Title: "manual approval",+ },+ Approvers: []*storepb.IssuePayloadApproval_Approver{+ {+ Status: storepb.IssuePayloadApproval_Approver_APPROVED,+ Principal: common.FormatUserEmail("[email protected]"),+ },+ },+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)+ return plan, issue+}++func updateIssueLabels(ctx context.Context, t *testing.T, service *IssueService, issue *store.IssueMessage, labels []string) {+ t.Helper()++ _, err := service.UpdateIssue(ctx, connect.NewRequest(&v1pb.UpdateIssueRequest{+ Issue: &v1pb.Issue{+ Name: common.FormatIssue(issue.ProjectID, issue.UID),+ Labels: labels,+ },+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"labels"}},+ }))+ require.NoError(t, err)+}++func getIssueForTest(ctx context.Context, t *testing.T, stores *store.Store, issueUID int64) *store.IssueMessage {+ t.Helper()++ got, err := stores.GetIssue(ctx, &store.FindIssueMessage{+ ProjectIDs: []string{"project-a"},+ UID: &issueUID,+ })+ require.NoError(t, err)+ require.NotNil(t, got)+ return got+}diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex 68d778aab9..11bf7eb7d4 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -471,19 +471,18 @@ func resetIssueApprovalFindingIfPlanApprovalInputVersion(ctx context.Context, stif issue.Type == storepb.Issue_DATABASE_CHANGE {// Plan check rows are visible before the reset finishes. If another worker already// recomputed approval for this version, the reset must not move the issue back to CHECKING.- updated, err := stores.ResetIssueApprovalFindingIfPlanApprovalInputVersion(ctx, issue.ProjectID, issue.UID, approvalInputVersion)+ updatedIssue, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: payloadPatch,+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ SkipIfCurrentApprovalFindingDone: &approvalInputVersion,+ })if err != nil {+ if errors.Is(err, store.ErrIssueUpdateSkipped) {+ return nil, false, nil+ }return nil, false, err}- if !updated {- return nil, false, nil- }- uid := issue.UID- updatedIssue, err := stores.GetIssue(ctx, &store.FindIssueMessage{- ProjectIDs: []string{issue.ProjectID},- UID: &uid,- })- return updatedIssue, true, err+ return updatedIssue, true, nil}updatedIssue, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{diff --git a/backend/api/v1/plan_service_test.go b/backend/api/v1/plan_service_test.goindex 7b9e5b6726..ca8f7b99da 100644--- a/backend/api/v1/plan_service_test.go+++ b/backend/api/v1/plan_service_test.go@@ -103,7 +103,7 @@ func TestPlanSpecsEqualSet(t *testing.T) {}}-func TestResetIssueApprovalFindingSkipsStalePlanApprovalInputVersion(t *testing.T) {+func TestUpdateIssueApprovalResetSkipsStalePlanApprovalInputVersion(t *testing.T) {ctx := context.Background()s := setupPlanServiceTestStore(ctx, t)diff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.goindex 146d909b4a..a7a744c323 100644--- a/backend/api/v1/rollout_service.go+++ b/backend/api/v1/rollout_service.go@@ -12,6 +12,7 @@ import ("connectrpc.com/connect""github.com/jackc/pgtype""github.com/pkg/errors"+ "google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/timestamppb""github.com/bytebase/bytebase/backend/common"@@ -407,12 +408,21 @@ func CreateRolloutAndPendingTasks(}}- var approvalInputVersion *int64+ var issueApprovalGuard *store.IssueApprovalGuardif issue != nil && issue.Type == storepb.Issue_DATABASE_CHANGE {v := plan.Config.GetApprovalInputVersion()- approvalInputVersion = &v+ issueApprovalGuard = &store.IssueApprovalGuard{ApprovalInputVersion: v}+ if project.Setting.RequireIssueApproval {+ var approval *storepb.IssuePayloadApproval+ if sourceApproval := issue.Payload.GetApproval(); sourceApproval != nil {+ approval = &storepb.IssuePayloadApproval{}+ proto.Merge(approval, sourceApproval)+ }+ issueApprovalGuard.IssueUID = issue.UID+ issueApprovalGuard.Approval = approval+ }}- marked, createdTasks, err := s.CreateRolloutTasks(ctx, project.ResourceID, plan.UID, approvalInputVersion, tasks)+ marked, createdTasks, err := s.CreateRolloutTasks(ctx, project.ResourceID, plan.UID, issueApprovalGuard, tasks)if err != nil {return errors.Wrap(err, "failed to create rollout tasks")}diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.goindex 80d008e361..3766ad49b5 100644--- a/backend/api/v1/setting_service.go+++ b/backend/api/v1/setting_service.go@@ -404,16 +404,13 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Reqif _, err := common.ConvertUnparsedApproval(rule.Condition); err != nil {return nil, err}+ conditionExpr := ""+ if rule.Condition != nil {+ conditionExpr = rule.Condition.Expression+ }- // 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 := common.ValidateApprovalExprForSource(conditionExpr, storepb.WorkspaceApprovalSetting_Rule_Source(rule.Source)); err != nil {+ return nil, err}if err := validateApprovalTemplate(rule.Template); err != nil {diff --git a/backend/common/cel.go b/backend/common/cel.goindex c240736d82..02b8a46ea5 100644--- a/backend/common/cel.go+++ b/backend/common/cel.go@@ -11,6 +11,8 @@ import ("github.com/pkg/errors"exprproto "google.golang.org/genproto/googleapis/api/expr/v1alpha1""google.golang.org/genproto/googleapis/type/expr"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store")const celLimit = 1024 * 1024@@ -38,6 +40,8 @@ var ApprovalFactors = []cel.EnvOption{cel.Variable(CELAttributeRequestExport, cel.BoolType),// Risk scopecel.Variable(CELAttributeRiskLevel, cel.StringType),+ // Issue scope+ cel.Variable(CELAttributeIssueLabels, cel.ListType(cel.StringType)),// String extension functions (split, join, trim, etc.)ext.Strings(),// Size limit@@ -52,27 +56,47 @@ var FallbackApprovalFactors = []cel.EnvOption{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 {+// ValidateApprovalExprForSource validates source-specific approval expressions.+func ValidateApprovalExprForSource(expression string, source storepb.WorkspaceApprovalSetting_Rule_Source) error {if expression == "" || expression == "true" {return nil}- e, err := cel.NewEnv(FallbackApprovalFactors...)+ factors := ApprovalFactors+ if source == storepb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED {+ factors = FallbackApprovalFactors+ }+ e, err := cel.NewEnv(factors...)if err != nil {return errors.Wrap(err, "failed to create CEL env")}- _, issues := e.Compile(expression)+ ast, 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()))+ if source == storepb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED {+ return connect.NewError(connect.CodeInvalidArgument,+ errors.Errorf("fallback rules can only use resource.project_id in conditions: %v", issues.Err()))+ }+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid approval rule condition: %v", issues.Err()))+ }+ if source != storepb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED && source != storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE {+ if astReferencesIssueLabels(ast) {+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("issue.labels is only supported for database change approval rules"))+ }}return nil}+func astReferencesIssueLabels(ast *cel.Ast) bool {+ for _, reference := range ast.NativeRep().ReferenceMap() {+ if reference.Name == CELAttributeIssueLabels {+ return true+ }+ }+ return false+}+// IAMPolicyConditionCELAttributes are the variables when evaluating IAM policy condition.var IAMPolicyConditionCELAttributes = []cel.EnvOption{cel.Variable(CELAttributeResourceEnvironmentID, cel.StringType),diff --git a/backend/common/cel_attributes.go b/backend/common/cel_attributes.goindex 2e48741533..a33e7b947e 100644--- a/backend/common/cel_attributes.go+++ b/backend/common/cel_attributes.go@@ -58,3 +58,9 @@ const (// CELAttributeRiskLevel is the risk level of the issue (LOW, MODERATE, HIGH).CELAttributeRiskLevel = "risk.level")++// CEL attribute names for issue scope.+const (+ // CELAttributeIssueLabels is the canonical labels attached to the issue.+ CELAttributeIssueLabels = "issue.labels"+)diff --git a/backend/common/cel_test.go b/backend/common/cel_test.goindex 9e7bdbba9a..742dfb4d1d 100644--- a/backend/common/cel_test.go+++ b/backend/common/cel_test.go@@ -8,6 +8,8 @@ import ("github.com/google/cel-go/cel""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store")func TestPartialEval(t *testing.T) {@@ -143,7 +145,7 @@ func TestFallbackApprovalFactorsOnlyAllowsProjectId(t *testing.T) {a.Error(issues.Err())}-func TestValidateFallbackApprovalExpr(t *testing.T) {+func TestValidateApprovalExprForSourceFallbackOnlyAllowsProjectID(t *testing.T) {tests := []struct {name stringexpression string@@ -179,7 +181,7 @@ func TestValidateFallbackApprovalExpr(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {a := require.New(t)- err := ValidateFallbackApprovalExpr(tt.expression)+ err := ValidateApprovalExprForSource(tt.expression, storepb.WorkspaceApprovalSetting_Rule_SOURCE_UNSPECIFIED)if tt.wantErr {a.Error(err)} else {@@ -209,6 +211,87 @@ func TestApprovalFactorsIncludesRiskLevel(t *testing.T) {a.Nil(issues)}+func TestApprovalFactorsIncludesIssueLabels(t *testing.T) {+ a := require.New(t)++ e, err := cel.NewEnv(ApprovalFactors...)+ a.NoError(err)++ _, issues := e.Compile(`"prod" in issue.labels`)+ a.Nil(issues)++ _, issues = e.Compile(`!("security" in issue.labels) && risk.level == "HIGH"`)+ a.Nil(issues)+}++func TestValidateApprovalExprForSourceAllowsIssueLabelsOnlyForDatabaseChange(t *testing.T) {+ tests := []struct {+ name string+ expression string+ source storepb.WorkspaceApprovalSetting_Rule_Source+ wantErr bool+ }{+ {+ name: "allows issue labels for database change",+ expression: `"prod" in issue.labels`,+ source: storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE,+ wantErr: false,+ },+ {+ name: "rejects issue labels for request role",+ expression: `"prod" in issue.labels`,+ source: storepb.WorkspaceApprovalSetting_Rule_REQUEST_ROLE,+ wantErr: true,+ },+ {+ name: "allows existing approval factors without issue labels",+ expression: `request.role == "roles/projectViewer" && resource.project_id == "project-a"`,+ source: storepb.WorkspaceApprovalSetting_Rule_REQUEST_ROLE,+ wantErr: false,+ },+ {+ name: "allows issue labels text in string literal",+ expression: `"issue.labels" == "issue.labels"`,+ source: storepb.WorkspaceApprovalSetting_Rule_REQUEST_ROLE,+ wantErr: false,+ },+ {+ name: "allows true",+ expression: `true`,+ source: storepb.WorkspaceApprovalSetting_Rule_REQUEST_ROLE,+ wantErr: false,+ },+ {+ name: "allows empty",+ expression: ``,+ source: storepb.WorkspaceApprovalSetting_Rule_REQUEST_ROLE,+ wantErr: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := ValidateApprovalExprForSource(tt.expression, tt.source)+ if tt.wantErr {+ require.Error(t, err)+ } else {+ require.NoError(t, err)+ }+ })+ }+}++func TestFallbackApprovalFactorsExcludesIssueLabels(t *testing.T) {+ a := require.New(t)++ e, err := cel.NewEnv(FallbackApprovalFactors...)+ a.NoError(err)++ _, issues := e.Compile(`"prod" in issue.labels`)+ a.NotNil(issues)+ a.Error(issues.Err())+}+func TestStringsExtensionEnabled(t *testing.T) {a := require.New(t)diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.goindex fa5e2543b2..a679a2f061 100644--- a/backend/runner/approval/runner.go+++ b/backend/runner/approval/runner.go@@ -181,6 +181,10 @@ func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webhif payload.Approval != nil && payload.Approval.ApprovalFindingDone && payload.Approval.GetApprovalInputVersion() == approvalInputVersion {return nil}+ approvalLabels := store.CanonicalizeIssueLabels(payload.GetLabels())+ if approvalLabels == nil {+ approvalLabels = []string{}+ }approvalTemplate, celVarsList, approvalInputVersion, done, err := func() (*storepb.ApprovalTemplate, []map[string]any, int64, bool, error) {// no need to find if feature is not enabled@@ -216,6 +220,7 @@ func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webhif approvalSource == storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE {riskLevel := calculateRiskLevelFromCELVars(celVarsList)injectRiskLevelIntoCELVars(celVarsList, riskLevel)+ injectIssueLabelsIntoCELVars(celVarsList, approvalLabels)}// Step 4: Find matching approval template@@ -252,13 +257,19 @@ func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webhRiskLevel: riskLevel,}if issue.Type == storepb.Issue_DATABASE_CHANGE {- updated, err := stores.UpdateIssuePayloadIfPlanApprovalInputVersion(ctx, issue.ProjectID, issue.UID, payloadPatch, approvalInputVersion)+ requireNoRollout := project.Setting.GetRequireIssueApproval()+ _, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: payloadPatch,+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &approvalLabels,+ RequireNoRollout: requireNoRollout,+ })if err != nil {+ if errors.Is(err, store.ErrIssueUpdateSkipped) {+ return nil+ }return errors.Wrap(err, "failed to update issue payload")}- if !updated {- return nil- }} else if _, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{PayloadUpsert: payloadPatch,}); err != nil {@@ -306,6 +317,16 @@ func injectRiskLevelIntoCELVars(celVarsList []map[string]any, riskLevel storepb.}}+func injectIssueLabelsIntoCELVars(celVarsList []map[string]any, labels []string) {+ canonicalLabels := store.CanonicalizeIssueLabels(labels)+ if canonicalLabels == nil {+ canonicalLabels = []string{}+ }+ for _, celVars := range celVarsList {+ celVars[common.CELAttributeIssueLabels] = canonicalLabels+ }+}+// riskLevelToString converts a RiskLevel enum to its string representation for CEL.func riskLevelToString(level storepb.RiskLevel) string {switch level {diff --git a/backend/runner/approval/runner_test.go b/backend/runner/approval/runner_test.goindex 71ae5dc134..487807e8b5 100644--- a/backend/runner/approval/runner_test.go+++ b/backend/runner/approval/runner_test.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/testcontainer"+ "github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/migrator"@@ -203,6 +204,42 @@ func TestApprovalTemplateMatchesUnspecifiedStatementSQLType(t *testing.T) {a.Equal("Unspecified SQL type rule", approvalTemplate.Title)}+func TestApprovalTemplateMatchesIssueLabels(t *testing.T) {+ a := require.New(t)++ celVars := map[string]any{+ common.CELAttributeResourceProjectID: "project",+ common.CELAttributeIssueLabels: []string{"prod", "security"},+ }+ injectRiskLevelIntoCELVars([]map[string]any{celVars}, storepb.RiskLevel_HIGH)++ approvalTemplate, err := getApprovalTemplate(&storepb.WorkspaceApprovalSetting{+ Rules: []*storepb.WorkspaceApprovalSetting_Rule{+ {+ Source: storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE,+ Condition: &expr.Expr{Expression: `"prod" in issue.labels && risk.level == "HIGH"`},+ Template: &storepb.ApprovalTemplate{Title: "Production label rule"},+ },+ },+ }, storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE, []map[string]any{celVars})+ a.NoError(err)+ a.NotNil(approvalTemplate)+ a.Equal("Production label rule", approvalTemplate.Title)+}++func TestInjectIssueLabelsIntoCELVars(t *testing.T) {+ celVarsList := []map[string]any{+ {common.CELAttributeResourceProjectID: "project-a"},+ {common.CELAttributeResourceProjectID: "project-a"},+ }++ injectIssueLabelsIntoCELVars(celVarsList, []string{" security ", "prod", "prod"})++ for _, celVars := range celVarsList {+ require.Equal(t, []string{"prod", "security"}, celVars[common.CELAttributeIssueLabels])+ }+}+func TestBuildStatementSummaryResultMapUsesSheetSHA256(t *testing.T) {results := []*storepb.PlanCheckRunResult_Result{{@@ -432,6 +469,112 @@ func TestBuildCELVariablesForDatabaseChangeCreatesMissingPlanCheckRun(t *testingrequire.EqualValues(t, 2, planCheckRun.Result.GetApprovalInputVersion())}+func TestFindApprovalTemplateForIssueSkipsDatabaseChangeAfterRolloutWhenApprovalRequired(t *testing.T) {+ ctx := context.Background()+ s := setupApprovalRunnerStore(ctx, t)+ require.NoError(t, s.UpdateProjects(ctx, &store.UpdateProjectMessage{+ ResourceID: "project-a",+ Workspace: "default",+ Setting: &storepb.Project{RequireIssueApproval: true},+ }))++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{+ ApprovalInputVersion: 2,+ Specs: []*storepb.PlanConfig_Spec{{+ Config: &storepb.PlanConfig_Spec_CreateDatabaseConfig{+ CreateDatabaseConfig: &storepb.PlanConfig_CreateDatabaseConfig{+ Target: "instances/prod",+ Database: "app",+ Environment: "prod",+ },+ },+ }},+ },+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{Labels: []string{"prod"}},+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)+ require.NoError(t, err)+ require.True(t, marked)++ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, s, false, "")+ require.NoError(t, err)+ err = findApprovalTemplateForIssue(ctx, s, nil, licenseService, issue, &storepb.WorkspaceApprovalSetting{})+ require.NoError(t, err)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.Nil(t, got.Payload.GetApproval())+ require.Equal(t, storepb.RiskLevel_RISK_LEVEL_UNSPECIFIED, got.Payload.GetRiskLevel())+}++func TestFindApprovalTemplateForIssueCompletesAfterRolloutWhenApprovalNotRequired(t *testing.T) {+ ctx := context.Background()+ s := setupApprovalRunnerStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{+ ApprovalInputVersion: 2,+ Specs: []*storepb.PlanConfig_Spec{{+ Config: &storepb.PlanConfig_Spec_CreateDatabaseConfig{+ CreateDatabaseConfig: &storepb.PlanConfig_CreateDatabaseConfig{+ Target: "instances/prod",+ Database: "app",+ Environment: "prod",+ },+ },+ }},+ },+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{Labels: []string{"prod"}},+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)+ require.NoError(t, err)+ require.True(t, marked)++ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, s, false, "")+ require.NoError(t, err)+ err = findApprovalTemplateForIssue(ctx, s, nil, licenseService, issue, &storepb.WorkspaceApprovalSetting{})+ require.NoError(t, err)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+ require.Nil(t, got.Payload.GetApproval().GetApprovalTemplate())+}+func setupApprovalRunnerStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()diff --git a/backend/store/issue.go b/backend/store/issue.goindex d773cde8e0..83bd08d8e2 100644--- a/backend/store/issue.go+++ b/backend/store/issue.go@@ -2,6 +2,8 @@ package storeimport ("context"+ "database/sql"+ "encoding/json""fmt""slices""strings"@@ -18,6 +20,9 @@ import (var getSegmenter func() *gse.Segmenter+// ErrIssueUpdateSkipped indicates that a guarded issue update did not match the current row state.+var ErrIssueUpdateSkipped = errors.New("issue update skipped")+func init() {var segmenterDic gse.Segmenterif err := segmenterDic.LoadDictEmbed("zh"); err != nil {@@ -76,7 +81,23 @@ type UpdateIssueMessage struct {Description *string// PayloadUpsert upserts the presented top-level keys.PayloadUpsert *storepb.Issue- RemoveLabels bool+ // ConditionalPayloadUpsert upserts the presented top-level keys only if+ // ConditionalPlanApprovalInputVersion matches. The main update still applies+ // if it does not.+ ConditionalPayloadUpsert *storepb.Issue+ RemoveLabels bool++ RequirePlanApprovalInputVersion *int64+ RequireIssueApprovalInputVersion *int64+ RequireApprovalFindingDone *bool+ RequireLabels *[]string+ RequireNoRollout bool+ // SkipIfCurrentApprovalFindingDone skips when approval finding is already done+ // for the same approval input version.+ SkipIfCurrentApprovalFindingDone *int64++ ConditionalPlanApprovalInputVersion *int64+ ConditionalRequireNoRollout bool}// FindIssueMessage is the message to find issues.@@ -235,15 +256,32 @@ func (s *Store) UpdateIssue(ctx context.Context, projectID string, uid int64, paif v := patch.Description; v != nil {set.Comma("description = ?", *v)}+ payloadSet := qb.Q().Space("payload")if v := patch.PayloadUpsert; v != nil {v.Labels = CanonicalizeIssueLabels(v.Labels)p, err := protojson.Marshal(v)if err != nil {return nil, errors.Wrapf(err, "failed to marshal patch.PayloadUpsert")}- set.Comma("payload = payload || ?", p)- } else if patch.RemoveLabels {- set.Comma("payload = payload || jsonb_build_object('labels', ?::JSONB)", nil)+ payloadSet.Space("|| ?::jsonb", string(p))+ }+ if patch.RemoveLabels {+ payloadSet.Space("|| jsonb_build_object('labels', ?::JSONB)", nil)+ }+ if v := patch.ConditionalPayloadUpsert; v != nil {+ if patch.ConditionalPlanApprovalInputVersion == nil {+ return nil, errors.New("ConditionalPayloadUpsert requires ConditionalPlanApprovalInputVersion")+ }+ v.Labels = CanonicalizeIssueLabels(v.Labels)+ p, err := protojson.Marshal(v)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to marshal patch.ConditionalPayloadUpsert")+ }+ condition := issuePlanApprovalInputVersionCondition(*patch.ConditionalPlanApprovalInputVersion, patch.ConditionalRequireNoRollout)+ payloadSet.Space("|| CASE WHEN ? THEN ?::jsonb ELSE '{}'::jsonb END", condition, string(p))+ }+ if payloadSet.Len() > 1 {+ set.Comma("payload = ?", payloadSet)}if patch.Title != nil || patch.Description != nil {@@ -260,142 +298,215 @@ func (s *Store) UpdateIssue(ctx context.Context, projectID string, uid int64, paset.Comma("ts_vector = ?", tsVector)}- q := qb.Q().Space("UPDATE issue SET ? WHERE project = ? AND id = ?", set, projectID, uid)+ where, hasGuard, err := buildUpdateIssueGuard(patch, projectID, uid)+ if err != nil {+ return nil, err+ }+ q := qb.Q().Space("UPDATE issue SET ? WHERE ?", set, where)query, args, err := q.ToSQL()if err != nil {return nil, errors.Wrapf(err, "failed to build sql")}- if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {+ result, err := s.GetDB().ExecContext(ctx, query, args...)+ if err != nil {return nil, err}+ if hasGuard {+ rowsAffected, err := result.RowsAffected()+ if err != nil {+ return nil, errors.Wrapf(err, "failed to inspect issue update")+ }+ if rowsAffected == 0 {+ return nil, ErrIssueUpdateSkipped+ }+ }return s.GetIssue(ctx, &FindIssueMessage{ProjectIDs: []string{projectID}, UID: &uid})}-func (s *Store) UpdateIssuePayloadIfPlanApprovalInputVersion(ctx context.Context, projectID string, uid int64, payload *storepb.Issue, approvalInputVersion int64) (bool, error) {- p, err := protojson.Marshal(payload)+// UpdateIssueLabelsAndMaybeResetApproval updates issue labels and, while the linked plan+// has no rollout, resets approval in the same transaction. This remains separate from+// generic UpdateIssue because labels and approval reset are one domain invariant here:+// composing a label write with a conditional approval reset can persist labels while+// silently skipping the reset during plan-version or rollout races.+func (s *Store) UpdateIssueLabelsAndMaybeResetApproval(ctx context.Context, projectID string, uid int64, labels []string) (*IssueMessage, bool, error) {+ labels = CanonicalizeIssueLabels(labels)++ tx, err := s.GetDB().BeginTx(ctx, nil)if err != nil {- return false, errors.Wrapf(err, "failed to marshal payload")+ return nil, false, errors.Wrapf(err, "failed to begin tx")}+ defer tx.Rollback()- q := qb.Q().Space(`- UPDATE issue- SET- updated_at = ?,- payload = payload || ?- WHERE project = ?- AND id = ?- AND EXISTS (- SELECT 1- FROM plan- WHERE plan.project = issue.project- AND plan.id = issue.plan_id- AND COALESCE((plan.config->>'approvalInputVersion')::bigint, 0) = ?- )`, time.Now(), p, projectID, uid, approvalInputVersion)-- query, args, err := q.ToSQL()- if err != nil {- return false, errors.Wrapf(err, "failed to build sql")+ var planUID sql.NullInt64+ currentPayload := &storepb.Issue{}+ var payload []byte+ if err := tx.QueryRowContext(ctx, `+ SELECT plan_id, payload+ FROM issue+ WHERE project = $1+ AND id = $2+ FOR UPDATE`,+ projectID, uid).Scan(&planUID, &payload); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, false, nil+ }+ return nil, false, errors.Wrapf(err, "failed to lock issue")}- result, err := s.GetDB().ExecContext(ctx, query, args...)- if err != nil {- return false, err+ if err := common.ProtojsonUnmarshaler.Unmarshal(payload, currentPayload); err != nil {+ return nil, false, errors.Wrap(err, "failed to unmarshal issue payload")}- rowsAffected, err := result.RowsAffected()- if err != nil {- return false, errors.Wrapf(err, "failed to inspect issue update")+ if slices.Equal(CanonicalizeIssueLabels(currentPayload.GetLabels()), labels) {+ if err := tx.Commit(); err != nil {+ return nil, false, errors.Wrapf(err, "failed to commit tx")+ }+ issue, err := s.GetIssue(ctx, &FindIssueMessage{ProjectIDs: []string{projectID}, UID: &uid})+ if err != nil {+ return nil, false, err+ }+ return issue, false, nil}- return rowsAffected > 0, nil-}-// ResetIssueApprovalFindingIfPlanApprovalInputVersion avoids clobbering approval work that raced-// ahead after a new plan check row became visible for the same plan version.-func (s *Store) ResetIssueApprovalFindingIfPlanApprovalInputVersion(ctx context.Context, projectID string, uid int64, approvalInputVersion int64) (bool, error) {- payload := &storepb.Issue{- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: false,- ApprovalInputVersion: approvalInputVersion,- },+ approvalResetApplied := false+ var approvalInputVersion int64+ if planUID.Valid {+ planConfig := &storepb.PlanConfig{}+ var config []byte+ if err := tx.QueryRowContext(ctx, `+ SELECT config+ FROM plan+ WHERE project = $1+ AND id = $2+ FOR UPDATE`,+ projectID, planUID.Int64).Scan(&config); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, false, errors.Errorf("plan %d not found", planUID.Int64)+ }+ return nil, false, errors.Wrapf(err, "failed to lock plan")+ }+ if err := common.ProtojsonUnmarshaler.Unmarshal(config, planConfig); err != nil {+ return nil, false, errors.Wrap(err, "failed to unmarshal plan config")+ }+ if !planConfig.GetHasRollout() {+ approvalResetApplied = true+ approvalInputVersion = planConfig.GetApprovalInputVersion()+ }}- p, err := protojson.Marshal(payload)- if err != nil {- return false, errors.Wrapf(err, "failed to marshal payload")++ payloadSet := qb.Q().Space("payload")+ if len(labels) == 0 {+ payloadSet.Space("|| jsonb_build_object('labels', ?::JSONB)", nil)+ } else {+ p, err := protojson.Marshal(&storepb.Issue{Labels: labels})+ if err != nil {+ return nil, false, errors.Wrapf(err, "failed to marshal issue labels")+ }+ payloadSet.Space("|| ?::jsonb", string(p))+ }+ if approvalResetApplied {+ p, err := protojson.Marshal(&storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: approvalInputVersion,+ },+ })+ if err != nil {+ return nil, false, errors.Wrapf(err, "failed to marshal issue approval reset")+ }+ payloadSet.Space("|| ?::jsonb", string(p))}q := qb.Q().Space(`UPDATE issueSETupdated_at = ?,- payload = payload || ?+ payload = ?WHERE project = ?- AND id = ?- AND EXISTS (- SELECT 1- FROM plan- WHERE plan.project = issue.project- AND plan.id = issue.plan_id- AND COALESCE((plan.config->>'approvalInputVersion')::bigint, 0) = ?- )- AND NOT (- COALESCE((payload->'approval'->>'approvalFindingDone')::boolean, false)- AND COALESCE((payload->'approval'->>'approvalInputVersion')::bigint, 0) = ?- )`,- time.Now(), p, projectID, uid, approvalInputVersion, approvalInputVersion)-+ AND id = ?`,+ time.Now(), payloadSet, projectID, uid)query, args, err := q.ToSQL()if err != nil {- return false, errors.Wrapf(err, "failed to build sql")+ return nil, false, errors.Wrapf(err, "failed to build sql")}- result, err := s.GetDB().ExecContext(ctx, query, args...)- if err != nil {- return false, err+ if _, err := tx.ExecContext(ctx, query, args...); err != nil {+ return nil, false, err}- rowsAffected, err := result.RowsAffected()- if err != nil {- return false, errors.Wrapf(err, "failed to inspect issue approval reset")++ if err := tx.Commit(); err != nil {+ return nil, false, errors.Wrapf(err, "failed to commit tx")}- return rowsAffected > 0, nil-}-// UpdateIssuePayloadIfCurrentApprovalInputVersion updates the issue payload only when both the issue approval payload-// and its plan still match the observed approval input version.-func (s *Store) UpdateIssuePayloadIfCurrentApprovalInputVersion(ctx context.Context, projectID string, uid int64, payload *storepb.Issue, approvalInputVersion int64) (bool, error) {- p, err := protojson.Marshal(payload)+ issue, err := s.GetIssue(ctx, &FindIssueMessage{ProjectIDs: []string{projectID}, UID: &uid})if err != nil {- return false, errors.Wrapf(err, "failed to marshal payload")+ return nil, false, err}+ return issue, approvalResetApplied, nil+}- q := qb.Q().Space(`- UPDATE issue- SET- updated_at = ?,- payload = payload || ?- WHERE project = ?- AND id = ?- AND COALESCE((payload->'approval'->>'approvalInputVersion')::bigint, 0) = ?- AND EXISTS (- SELECT 1- FROM plan- WHERE plan.project = issue.project- AND plan.id = issue.plan_id- AND COALESCE((plan.config->>'approvalInputVersion')::bigint, 0) = ?- )`, time.Now(), p, projectID, uid, approvalInputVersion, approvalInputVersion)-- query, args, err := q.ToSQL()- if err != nil {- return false, errors.Wrapf(err, "failed to build sql")+func marshalCanonicalIssueLabels(labels []string) ([]byte, error) {+ canonicalLabels := CanonicalizeIssueLabels(labels)+ if canonicalLabels == nil {+ canonicalLabels = []string{}}- result, err := s.GetDB().ExecContext(ctx, query, args...)+ labelBytes, err := json.Marshal(canonicalLabels)if err != nil {- return false, err+ return nil, errors.Wrapf(err, "failed to marshal issue labels")}- rowsAffected, err := result.RowsAffected()- if err != nil {- return false, errors.Wrapf(err, "failed to inspect issue update")+ return labelBytes, nil+}++func buildUpdateIssueGuard(patch *UpdateIssueMessage, projectID string, uid int64) (*qb.Query, bool, error) {+ where := qb.Q().Space("project = ? AND id = ?", projectID, uid)+ hasGuard := false+ if version := patch.RequirePlanApprovalInputVersion; version != nil {+ where.Space("AND ?", issuePlanApprovalInputVersionCondition(*version, patch.RequireNoRollout))+ hasGuard = true+ } else if patch.RequireNoRollout {+ return nil, false, errors.New("RequireNoRollout requires RequirePlanApprovalInputVersion")+ }+ if version := patch.RequireIssueApprovalInputVersion; version != nil {+ where.Space("AND COALESCE((payload->'approval'->>'approvalInputVersion')::bigint, 0) = ?", *version)+ hasGuard = true+ }+ if done := patch.RequireApprovalFindingDone; done != nil {+ where.Space("AND COALESCE((payload->'approval'->>'approvalFindingDone')::boolean, false) = ?", *done)+ hasGuard = true+ }+ if labels := patch.RequireLabels; labels != nil {+ labelBytes, err := marshalCanonicalIssueLabels(*labels)+ if err != nil {+ return nil, false, err+ }+ where.Space("AND COALESCE(NULLIF(payload->'labels', 'null'::jsonb), '[]'::jsonb) = ?::jsonb", string(labelBytes))+ hasGuard = true+ }+ if version := patch.SkipIfCurrentApprovalFindingDone; version != nil {+ where.Space(`+ AND NOT (+ COALESCE((payload->'approval'->>'approvalFindingDone')::boolean, false)+ AND COALESCE((payload->'approval'->>'approvalInputVersion')::bigint, 0) = ?+ )`, *version)+ hasGuard = true+ }+ return where, hasGuard, nil+}++func issuePlanApprovalInputVersionCondition(approvalInputVersion int64, requireNoRollout bool) *qb.Query {+ planWhere := qb.Q().Space(`+ plan.project = issue.project+ AND plan.id = issue.plan_id+ AND COALESCE((plan.config->>'approvalInputVersion')::bigint, 0) = ?`, approvalInputVersion)+ if requireNoRollout {+ planWhere.Space("AND COALESCE((plan.config->>'hasRollout')::boolean, false) = false")}- return rowsAffected > 0, nil+ return qb.Q().Space(`+ EXISTS (+ SELECT 1+ FROM plan+ WHERE ?+ )`, planWhere)}// ListIssues returns the list of issues by find query.diff --git a/backend/store/plan_approval_input_version_test.go b/backend/store/plan_approval_input_version_test.goindex dbf7b1db85..8d7f12d88c 100644--- a/backend/store/plan_approval_input_version_test.go+++ b/backend/store/plan_approval_input_version_test.go@@ -114,7 +114,7 @@ func TestCreateRolloutTasksRequiresMatchingApprovalInputVersion(t *testing.T) {require.NoError(t, err)staleVersion := int64(1)- updated, createdTasks, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &staleVersion, nil)+ updated, createdTasks, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: staleVersion}, nil)require.NoError(t, err)require.False(t, updated)require.Empty(t, createdTasks)@@ -126,7 +126,7 @@ func TestCreateRolloutTasksRequiresMatchingApprovalInputVersion(t *testing.T) {requirePlanSpecID(t, got.Config, "spec-a")currentVersion := int64(2)- updated, createdTasks, err = s.CreateRolloutTasks(ctx, "project-a", plan.UID, ¤tVersion, nil)+ updated, createdTasks, err = s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: currentVersion}, nil)require.NoError(t, err)require.True(t, updated)require.Empty(t, createdTasks)@@ -138,6 +138,134 @@ func TestCreateRolloutTasksRequiresMatchingApprovalInputVersion(t *testing.T) {requirePlanSpecID(t, got.Config, "spec-a")}+func TestCreateRolloutTasksRequiresCurrentIssueApproval(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{+ ApprovalInputVersion: 2,+ Specs: []*storepb.PlanConfig_Spec{{Id: "spec-a"}},+ },+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ ApprovalTemplate: &storepb.ApprovalTemplate{+ Flow: &storepb.ApprovalFlow{Roles: []string{"roles/sql-reviewer"}},+ },+ Approvers: []*storepb.IssuePayloadApproval_Approver{+ {+ Status: storepb.IssuePayloadApproval_Approver_APPROVED,+ Principal: "users/[email protected]",+ },+ },+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ approvedIssueApproval := &storepb.IssuePayloadApproval{}+ proto.Merge(approvedIssueApproval, issue.Payload.GetApproval())+ updatedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{Labels: []string{"security"}},+ ConditionalPayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: approvalInputVersion,+ },+ },+ ConditionalPlanApprovalInputVersion: &approvalInputVersion,+ ConditionalRequireNoRollout: true,+ })+ require.NoError(t, err)+ require.False(t, updatedIssue.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, updatedIssue.Payload.GetApproval().GetApprovalInputVersion())+ require.Equal(t, []string{"security"}, updatedIssue.Payload.Labels)++ updatedRollout, createdTasks, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{+ IssueUID: issue.UID,+ ApprovalInputVersion: approvalInputVersion,+ Approval: approvedIssueApproval,+ }, nil)+ require.NoError(t, err)+ require.False(t, updatedRollout)+ require.Empty(t, createdTasks)++ got, err := s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: "project-a", UID: &plan.UID})+ require.NoError(t, err)+ require.False(t, got.Config.GetHasRollout())+ require.EqualValues(t, 2, got.Config.GetApprovalInputVersion())++ labels := []string{"security"}+ recomputedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ ApprovalTemplate: &storepb.ApprovalTemplate{+ Flow: &storepb.ApprovalFlow{Roles: []string{"roles/sql-reviewer"}},+ },+ Approvers: []*storepb.IssuePayloadApproval_Approver{+ {+ Status: storepb.IssuePayloadApproval_Approver_APPROVED,+ Principal: "users/[email protected]",+ },+ },+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ })+ require.NoError(t, err)+ require.False(t, approvedIssueApproval.Equal(recomputedIssue.Payload.GetApproval()))++ updatedRollout, createdTasks, err = s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{+ IssueUID: issue.UID,+ ApprovalInputVersion: approvalInputVersion,+ Approval: approvedIssueApproval,+ }, nil)+ require.NoError(t, err)+ require.False(t, updatedRollout)+ require.Empty(t, createdTasks)++ got, err = s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: "project-a", UID: &plan.UID})+ require.NoError(t, err)+ require.False(t, got.Config.GetHasRollout())+ require.EqualValues(t, 2, got.Config.GetApprovalInputVersion())++ currentIssueApproval := &storepb.IssuePayloadApproval{}+ proto.Merge(currentIssueApproval, recomputedIssue.Payload.GetApproval())+ updatedRollout, createdTasks, err = s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{+ IssueUID: issue.UID,+ ApprovalInputVersion: approvalInputVersion,+ Approval: currentIssueApproval,+ }, nil)+ require.NoError(t, err)+ require.True(t, updatedRollout)+ require.Empty(t, createdTasks)++ got, err = s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: "project-a", UID: &plan.UID})+ require.NoError(t, err)+ require.True(t, got.Config.GetHasRollout())+ require.EqualValues(t, 2, got.Config.GetApprovalInputVersion())+}+func TestCreateRolloutTasksAddsMissingTasksAfterRolloutExists(t *testing.T) {ctx := context.Background()s := setupPlanApprovalInputVersionStore(ctx, t)@@ -192,7 +320,7 @@ func TestUpdatePlanRequireNoRolloutDoesNotOverwriteRollout(t *testing.T) {staleConfig.Specs = []*storepb.PlanConfig_Spec{{Id: "spec-b"}}approvalInputVersion := int64(1)- marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &approvalInputVersion, nil)+ marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)require.NoError(t, err)require.True(t, marked)@@ -231,7 +359,7 @@ func TestUpdatePlanRequireNoRolloutRejectsConfigUpdateAfterRollout(t *testing.T)staleConfig.Specs = []*storepb.PlanConfig_Spec{{Id: "spec-b"}}approvalInputVersion := int64(1)- marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &approvalInputVersion, nil)+ marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)require.NoError(t, err)require.True(t, marked)@@ -251,7 +379,7 @@ func TestUpdatePlanRequireNoRolloutRejectsConfigUpdateAfterRollout(t *testing.T)requirePlanSpecID(t, got.Config, "spec-a")}-func TestUpdateIssuePayloadIfPlanApprovalInputVersionUpdatesMatchingVersion(t *testing.T) {+func TestUpdateIssueWithPlanApprovalInputVersionGuardUpdatesMatchingVersion(t *testing.T) {ctx := context.Background()s := setupPlanApprovalInputVersionStore(ctx, t)@@ -274,15 +402,18 @@ func TestUpdateIssuePayloadIfPlanApprovalInputVersionUpdatesMatchingVersion(t *t})require.NoError(t, err)- updated, err := s.UpdateIssuePayloadIfPlanApprovalInputVersion(ctx, "project-a", issue.UID, &storepb.Issue{- RiskLevel: storepb.RiskLevel_HIGH,- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: true,- ApprovalInputVersion: 2,+ approvalInputVersion := int64(2)+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },},- }, 2)+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ })require.NoError(t, err)- require.True(t, updated)got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})require.NoError(t, err)@@ -292,7 +423,53 @@ func TestUpdateIssuePayloadIfPlanApprovalInputVersionUpdatesMatchingVersion(t *trequire.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())}-func TestUpdateIssuePayloadIfPlanApprovalInputVersionSkipsStaleVersion(t *testing.T) {+func TestUpdateIssuePayloadUpsertCanRemoveLabels(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ RiskLevel: storepb.RiskLevel_LOW,+ },+ })+ require.NoError(t, err)++ updatedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{RiskLevel: storepb.RiskLevel_HIGH},+ RemoveLabels: true,+ })+ require.NoError(t, err)+ require.Empty(t, updatedIssue.Payload.GetLabels())+ require.Equal(t, storepb.RiskLevel_HIGH, updatedIssue.Payload.GetRiskLevel())+}++func TestUpdateIssueConditionalPayloadRequiresPlanGuard(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{},+ })+ require.NoError(t, err)++ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ ConditionalPayloadUpsert: &storepb.Issue{RiskLevel: storepb.RiskLevel_HIGH},+ })+ require.ErrorContains(t, err, "ConditionalPayloadUpsert requires ConditionalPlanApprovalInputVersion")+}++func TestUpdateIssueWithPlanApprovalInputVersionGuardSkipsStaleVersion(t *testing.T) {ctx := context.Background()s := setupPlanApprovalInputVersionStore(ctx, t)@@ -315,15 +492,18 @@ func TestUpdateIssuePayloadIfPlanApprovalInputVersionSkipsStaleVersion(t *testin})require.NoError(t, err)- updated, err := s.UpdateIssuePayloadIfPlanApprovalInputVersion(ctx, "project-a", issue.UID, &storepb.Issue{- RiskLevel: storepb.RiskLevel_HIGH,- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: true,- ApprovalInputVersion: 1,+ approvalInputVersion := int64(1)+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 1,+ },},- }, 1)- require.NoError(t, err)- require.False(t, updated)+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ })+ require.ErrorIs(t, err, store.ErrIssueUpdateSkipped)got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})require.NoError(t, err)@@ -332,7 +512,7 @@ func TestUpdateIssuePayloadIfPlanApprovalInputVersionSkipsStaleVersion(t *testinrequire.Nil(t, got.Payload.GetApproval())}-func TestUpdateIssuePayloadIfPlanApprovalInputVersionSkipsIssueWithoutPlan(t *testing.T) {+func TestUpdateIssueWithPlanApprovalInputVersionGuardSkipsIssueWithoutPlan(t *testing.T) {ctx := context.Background()s := setupPlanApprovalInputVersionStore(ctx, t)@@ -346,14 +526,17 @@ func TestUpdateIssuePayloadIfPlanApprovalInputVersionSkipsIssueWithoutPlan(t *te})require.NoError(t, err)- updated, err := s.UpdateIssuePayloadIfPlanApprovalInputVersion(ctx, "project-a", issue.UID, &storepb.Issue{- RiskLevel: storepb.RiskLevel_HIGH,- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: true,+ approvalInputVersion := int64(0)+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ },},- }, 0)- require.NoError(t, err)- require.False(t, updated)+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ })+ require.ErrorIs(t, err, store.ErrIssueUpdateSkipped)got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})require.NoError(t, err)@@ -362,7 +545,7 @@ func TestUpdateIssuePayloadIfPlanApprovalInputVersionSkipsIssueWithoutPlan(t *terequire.Nil(t, got.Payload.GetApproval())}-func TestResetIssueApprovalFindingIfPlanApprovalInputVersionSkipsCurrentDoneApproval(t *testing.T) {+func TestUpdateIssueWithPlanApprovalInputVersionAndLabelsGuardsUpdatesMatchingLabels(t *testing.T) {ctx := context.Background()s := setupPlanApprovalInputVersionStore(ctx, t)@@ -381,29 +564,36 @@ func TestResetIssueApprovalFindingIfPlanApprovalInputVersionSkipsCurrentDoneApprType: storepb.Issue_DATABASE_CHANGE,Description: "",Payload: &storepb.Issue{+ Labels: []string{"prod", "security"},+ RiskLevel: storepb.RiskLevel_LOW,+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ labels := []string{"security", "prod", "prod"}+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{RiskLevel: storepb.RiskLevel_HIGH,Approval: &storepb.IssuePayloadApproval{ApprovalFindingDone: true,ApprovalInputVersion: 2,},},- PlanUID: &plan.UID,+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,})require.NoError(t, err)- updated, err := s.ResetIssueApprovalFindingIfPlanApprovalInputVersion(ctx, "project-a", issue.UID, 2)- require.NoError(t, err)- require.False(t, updated)-got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})require.NoError(t, err)- require.NotNil(t, got)require.Equal(t, storepb.RiskLevel_HIGH, got.Payload.GetRiskLevel())require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())}-func TestUpdateIssuePayloadIfCurrentApprovalInputVersionUpdatesMatchingVersion(t *testing.T) {+func TestUpdateIssueWithPlanApprovalInputVersionAndLabelsGuardsUpdatesEmptyLabels(t *testing.T) {ctx := context.Background()s := setupPlanApprovalInputVersionStore(ctx, t)@@ -421,36 +611,87 @@ func TestUpdateIssuePayloadIfCurrentApprovalInputVersionUpdatesMatchingVersion(tTitle: "issue-a",Type: storepb.Issue_DATABASE_CHANGE,Description: "",- Payload: &storepb.Issue{- RiskLevel: storepb.RiskLevel_LOW,+ Payload: &storepb.Issue{RiskLevel: storepb.RiskLevel_LOW},+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ var labels []string+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,Approval: &storepb.IssuePayloadApproval{ApprovalFindingDone: true,ApprovalInputVersion: 2,},},+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ })+ require.NoError(t, err)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.Equal(t, storepb.RiskLevel_HIGH, got.Payload.GetRiskLevel())+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueWithPlanApprovalInputVersionAndLabelsGuardsUpdatesJSONNullLabels(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ RiskLevel: storepb.RiskLevel_LOW,+ },PlanUID: &plan.UID,})require.NoError(t, err)- updated, err := s.UpdateIssuePayloadIfCurrentApprovalInputVersion(ctx, "project-a", issue.UID, &storepb.Issue{- RiskLevel: storepb.RiskLevel_HIGH,- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: true,- ApprovalInputVersion: 2,+ updatedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{RemoveLabels: true})+ require.NoError(t, err)+ require.Empty(t, updatedIssue.Payload.GetLabels())++ approvalInputVersion := int64(2)+ var labels []string+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },},- }, 2)+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ })require.NoError(t, err)- require.True(t, updated)got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})require.NoError(t, err)- require.NotNil(t, got)+ require.Empty(t, got.Payload.GetLabels())require.Equal(t, storepb.RiskLevel_HIGH, got.Payload.GetRiskLevel())require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())}-func TestUpdateIssuePayloadIfCurrentApprovalInputVersionSkipsStaleIssueApprovalVersion(t *testing.T) {+func TestUpdateIssueWithPlanApprovalInputVersionAndLabelsGuardsSkipsStaleLabels(t *testing.T) {ctx := context.Background()s := setupPlanApprovalInputVersionStore(ctx, t)@@ -469,25 +710,575 @@ func TestUpdateIssuePayloadIfCurrentApprovalInputVersionSkipsStaleIssueApprovalVType: storepb.Issue_DATABASE_CHANGE,Description: "",Payload: &storepb.Issue{+ Labels: []string{"prod"},RiskLevel: storepb.RiskLevel_LOW,+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ updatedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{Labels: []string{"stage"}},+ })+ require.NoError(t, err)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())++ approvalInputVersion := int64(2)+ labels := []string{"prod"}+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,Approval: &storepb.IssuePayloadApproval{ApprovalFindingDone: true,- ApprovalInputVersion: 1,+ ApprovalInputVersion: 2,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ })+ require.ErrorIs(t, err, store.ErrIssueUpdateSkipped)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.Equal(t, storepb.RiskLevel_LOW, got.Payload.GetRiskLevel())+ require.Nil(t, got.Payload.GetApproval())+}++func TestUpdateIssueWithPlanApprovalInputVersionLabelsAndNoRolloutGuardsUpdatesBeforeRollout(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod", "security"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,},},PlanUID: &plan.UID,})require.NoError(t, err)- updated, err := s.UpdateIssuePayloadIfCurrentApprovalInputVersion(ctx, "project-a", issue.UID, &storepb.Issue{- RiskLevel: storepb.RiskLevel_HIGH,- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: true,- ApprovalInputVersion: 1,+ approvalInputVersion := int64(2)+ labels := []string{"security", "prod", "prod"}+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: 2,+ },},- }, 2)+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ RequireNoRollout: true,+ })require.NoError(t, err)- require.False(t, updated)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.False(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueWithPlanApprovalInputVersionLabelsAndNoRolloutGuardsUpdatesJSONNullLabels(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ updatedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{RemoveLabels: true})+ require.NoError(t, err)+ require.Empty(t, updatedIssue.Payload.GetLabels())++ approvalInputVersion := int64(2)+ var labels []string+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: 2,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ RequireNoRollout: true,+ })+ require.NoError(t, err)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.Empty(t, got.Payload.GetLabels())+ require.False(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueWithPlanApprovalInputVersionLabelsAndNoRolloutGuardsSkipsAfterRollout(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod", "security"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)+ require.NoError(t, err)+ require.True(t, marked)++ labels := []string{"security", "prod", "prod"}+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: 2,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ RequireNoRollout: true,+ })+ require.ErrorIs(t, err, store.ErrIssueUpdateSkipped)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueConditionalPayloadSkipsAfterRolloutButMainUpdateApplies(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)+ require.NoError(t, err)+ require.True(t, marked)++ updatedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{Labels: []string{"stage"}},+ ConditionalPayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: approvalInputVersion,+ },+ },+ ConditionalPlanApprovalInputVersion: &approvalInputVersion,+ ConditionalRequireNoRollout: true,+ })+ require.NoError(t, err)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())+ require.True(t, updatedIssue.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, updatedIssue.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueLabelsAndMaybeResetApprovalResetsBeforeRollout(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ updatedIssue, approvalResetApplied, err := s.UpdateIssueLabelsAndMaybeResetApproval(ctx, "project-a", issue.UID, []string{"stage"})+ require.NoError(t, err)+ require.True(t, approvalResetApplied)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())+ require.False(t, updatedIssue.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, updatedIssue.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueLabelsAndMaybeResetApprovalDoesNotResetAfterRollout(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ marked, _, err := s.CreateRolloutTasks(ctx, "project-a", plan.UID, &store.IssueApprovalGuard{ApprovalInputVersion: approvalInputVersion}, nil)+ require.NoError(t, err)+ require.True(t, marked)++ updatedIssue, approvalResetApplied, err := s.UpdateIssueLabelsAndMaybeResetApproval(ctx, "project-a", issue.UID, []string{"stage"})+ require.NoError(t, err)+ require.False(t, approvalResetApplied)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())+ require.True(t, updatedIssue.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, updatedIssue.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueLabelsAndMaybeResetApprovalUsesCurrentPlanVersion(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ updatedPlan, err := s.UpdatePlan(ctx, &store.UpdatePlanMessage{+ UID: plan.UID,+ ProjectID: plan.ProjectID,+ Config: plan.Config,+ BumpApprovalInputVersion: true,+ })+ require.NoError(t, err)+ require.EqualValues(t, 3, updatedPlan.Config.GetApprovalInputVersion())++ updatedIssue, approvalResetApplied, err := s.UpdateIssueLabelsAndMaybeResetApproval(ctx, "project-a", issue.UID, []string{"stage"})+ require.NoError(t, err)+ require.True(t, approvalResetApplied)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())+ require.False(t, updatedIssue.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 3, updatedIssue.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueLabelsAndMaybeResetApprovalNoopsWhenLockedLabelsMatch(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ updatedIssue, approvalResetApplied, err := s.UpdateIssueLabelsAndMaybeResetApproval(ctx, "project-a", issue.UID, []string{"stage"})+ require.NoError(t, err)+ require.True(t, approvalResetApplied)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())+ require.False(t, updatedIssue.Payload.GetApproval().GetApprovalFindingDone())++ approvalInputVersion := int64(2)+ labels := []string{"stage"}+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: approvalInputVersion,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireLabels: &labels,+ })+ require.NoError(t, err)++ updatedIssue, approvalResetApplied, err = s.UpdateIssueLabelsAndMaybeResetApproval(ctx, "project-a", issue.UID, []string{"stage"})+ require.NoError(t, err)+ require.False(t, approvalResetApplied)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())+ require.True(t, updatedIssue.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, updatedIssue.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueWithCurrentDoneApprovalGuardSkipsCurrentDoneApproval(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ ApprovalInputVersion: 2,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ SkipIfCurrentApprovalFindingDone: &approvalInputVersion,+ })+ require.ErrorIs(t, err, store.ErrIssueUpdateSkipped)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.NotNil(t, got)+ require.Equal(t, storepb.RiskLevel_HIGH, got.Payload.GetRiskLevel())+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueWithCurrentApprovalInputVersionGuardsUpdatesMatchingVersion(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_LOW,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireIssueApprovalInputVersion: &approvalInputVersion,+ })+ require.NoError(t, err)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.NotNil(t, got)+ require.Equal(t, storepb.RiskLevel_HIGH, got.Payload.GetRiskLevel())+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+ require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+}++func TestUpdateIssueWithCurrentApprovalInputVersionGuardsSkipsStaleIssueApprovalVersion(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_LOW,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 1,+ },+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ approvalInputVersion := int64(2)+ _, err = s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 1,+ },+ },+ RequirePlanApprovalInputVersion: &approvalInputVersion,+ RequireIssueApprovalInputVersion: &approvalInputVersion,+ })+ require.ErrorIs(t, err, store.ErrIssueUpdateSkipped)got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})require.NoError(t, err)diff --git a/backend/store/task.go b/backend/store/task.goindex daf0918f23..b28389932a 100644--- a/backend/store/task.go+++ b/backend/store/task.go@@ -78,6 +78,17 @@ type TaskStatusCount struct {Count int32}+// IssueApprovalGuard carries the approval-input version used for rollout+// creation. When issue approval is required, it also carries the issue approval+// snapshot that the API layer has already accepted. The store uses it only as a+// race guard: the plan must still be on this version and, when Approval is set,+// the locked issue row must still have the same approval payload.+type IssueApprovalGuard struct {+ IssueUID int64+ ApprovalInputVersion int64+ Approval *storepb.IssuePayloadApproval+}+// GetTaskByID gets a task by ID.func (s *Store) GetTaskByID(ctx context.Context, projectID string, id int64) (*TaskMessage, error) {tasks, err := s.ListTasks(ctx, &TaskFind{ProjectID: projectID, ID: &id})@@ -496,15 +507,46 @@ func (s *Store) BatchSkipTasks(ctx context.Context, projectID string, taskUIDs [}// CreateRolloutTasks marks the plan as having rollout and creates tasks in one transaction.-// If approvalInputVersion is set, the transaction creates no tasks unless the plan-// still has that approval input version.-func (s *Store) CreateRolloutTasks(ctx context.Context, projectID string, planUID int64, approvalInputVersion *int64, tasks []*TaskMessage) (bool, []*TaskMessage, error) {+// If issueApprovalGuard is set, the transaction creates no tasks unless the plan+// still has that approval input version. The API layer owns the "is this issue+// approved" policy check before calling this method; the store only verifies+// that the locked issue approval payload still matches the approved snapshot.+func (s *Store) CreateRolloutTasks(ctx context.Context, projectID string, planUID int64, issueApprovalGuard *IssueApprovalGuard, tasks []*TaskMessage) (bool, []*TaskMessage, error) {tx, err := s.GetDB().BeginTx(ctx, nil)if err != nil {return false, nil, errors.Wrapf(err, "failed to begin tx")}defer tx.Rollback()+ var approvalInputVersion *int64+ if issueApprovalGuard != nil {+ approvalInputVersion = &issueApprovalGuard.ApprovalInputVersion+ }++ if issueApprovalGuard != nil && issueApprovalGuard.Approval != nil {+ var payload []byte+ if err := tx.QueryRowContext(ctx, `+ SELECT payload+ FROM issue+ WHERE project = $1+ AND id = $2+ AND plan_id = $3+ FOR UPDATE`,+ projectID, issueApprovalGuard.IssueUID, planUID).Scan(&payload); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return false, nil, nil+ }+ return false, nil, errors.Wrapf(err, "failed to lock issue approval")+ }+ current, err := isIssueApprovalPayloadSameAsGuard(payload, issueApprovalGuard)+ if err != nil {+ return false, nil, err+ }+ if !current {+ return false, nil, nil+ }+ }+var updatedPlanUID int64if err := tx.QueryRowContext(ctx, `UPDATE plan@@ -542,6 +584,24 @@ func (s *Store) CreateRolloutTasks(ctx context.Context, projectID string, planUIreturn true, tasks, nil}+func isIssueApprovalPayloadSameAsGuard(payload []byte, guard *IssueApprovalGuard) (bool, error) {+ if guard == nil || guard.Approval == nil {+ return false, nil+ }+ if guard.Approval.GetApprovalInputVersion() != guard.ApprovalInputVersion {+ return false, nil+ }+ issuePayload := &storepb.Issue{}+ if err := common.ProtojsonUnmarshaler.Unmarshal(payload, issuePayload); err != nil {+ return false, errors.Wrap(err, "failed to unmarshal issue payload")+ }+ approval := issuePayload.GetApproval()+ if approval == nil || !approval.GetApprovalFindingDone() {+ return false, nil+ }+ return approval.Equal(guard.Approval), nil+}+func (s *Store) createTasksTxDedup(ctx context.Context, tx *sql.Tx, projectID string, planUID int64, tasks []*TaskMessage) ([]*TaskMessage, error) {// Check existing tasks to avoid duplicatesexistingTasks, err := s.listTasksImpl(ctx, tx, &TaskFind{diff --git a/docs/superpowers/plans/2026-07-03-approval-cel-issue-labels.md b/docs/superpowers/plans/2026-07-03-approval-cel-issue-labels.mdnew file mode 100644index 0000000000..d7289efaf1--- /dev/null+++ b/docs/superpowers/plans/2026-07-03-approval-cel-issue-labels.md@@ -0,0 +1,811 @@+# Approval CEL Issue Labels Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Add `issue.labels` to `CHANGE_DATABASE` approval-flow CEL and keep approval state correct when labels change.++**Architecture:** Treat issue labels as approval-affecting input for database-change issues only. The approval runner canonicalizes labels once, injects the same slice into CEL variables, and passes that slice to a guarded store update so stale label computations cannot write approval state. Label updates reset approval finding only while the linked plan has no rollout.++**Tech Stack:** Go, PostgreSQL JSONB, cel-go, ConnectRPC services, React, TypeScript, existing CEL expression editor.++---++## File Structure++- Modify `backend/common/cel_attributes.go`: add the shared `issue.labels` CEL attribute name.+- Modify `backend/common/cel.go`: add `issue.labels` to source-specific approval CEL factors as `list<string>`.+- Modify `backend/common/cel_test.go`: cover compile behavior for `issue.labels` and fallback rejection.+- Modify `backend/store/issue.go`: add a label-aware guarded approval payload update.+- Modify `backend/store/plan_approval_input_version_test.go`: cover label-aware write success and stale-label rejection.+- Modify `backend/runner/approval/runner.go`: canonicalize labels, inject them into database-change CEL variables, and use the label-aware guarded write.+- Modify `backend/runner/approval/runner_test.go`: cover approval rule matching on `issue.labels`.+- Modify `backend/api/v1/issue_service.go`: reset approval finding and enqueue approval finding when labels change before rollout; skip reset after rollout.+- Modify `backend/api/v1/issue_service_test.go`: cover label reset semantics before and after rollout.+- Modify `frontend/src/utils/cel-attributes.ts`: add the frontend `issue.labels` constant.+- Modify `frontend/src/plugins/cel/types/factor.ts`: add a list factor type for `issue.labels`.+- Modify `frontend/src/plugins/cel/types/operator.ts`: support list membership operators for `issue.labels`.+- Modify `frontend/src/plugins/cel/types/simple.ts`: add a list-membership condition shape.+- Modify `frontend/src/plugins/cel/logic/build.ts`: build `"value" in issue.labels` and `!("value" in issue.labels)`.+- Modify `frontend/src/react/components/CustomApproval/utils.ts`: expose `issue.labels` for `CHANGE_DATABASE` only.+- Create `frontend/src/plugins/cel/logic/build.test.ts`: cover list factor build behavior.+- Create `frontend/src/react/components/CustomApproval/utils.test.ts`: cover approval factor exposure.++---++### Task 1: Backend CEL Attribute And Compile Tests++**Files:**+- Modify: `backend/common/cel_attributes.go`+- Modify: `backend/common/cel.go`+- Modify: `backend/common/cel_test.go`++- [ ] **Step 1: Write failing tests for approval and fallback CEL environments**++Add these cases to `backend/common/cel_test.go` near `TestApprovalFactorsIncludesRiskLevel`:++```go+func TestApprovalFactorsIncludesIssueLabels(t *testing.T) {+ a := require.New(t)++ e, err := cel.NewEnv(ApprovalFactors...)+ a.NoError(err)++ _, issues := e.Compile(`"prod" in issue.labels`)+ a.Nil(issues)++ _, issues = e.Compile(`!("security" in issue.labels) && risk.level == "HIGH"`)+ a.Nil(issues)+}++func TestFallbackApprovalFactorsExcludesIssueLabels(t *testing.T) {+ a := require.New(t)++ e, err := cel.NewEnv(FallbackApprovalFactors...)+ a.NoError(err)++ _, issues := e.Compile(`"prod" in issue.labels`)+ a.NotNil(issues)+ a.Error(issues.Err())+}+```++- [ ] **Step 2: Run the focused common tests and verify failure**++Run:++```bash+go test -v -count=1 ./backend/common -run '^(TestApprovalFactorsIncludesIssueLabels|TestFallbackApprovalFactorsExcludesIssueLabels)$'+```++Expected: `TestApprovalFactorsIncludesIssueLabels` fails because `issue.labels` is undeclared.++- [ ] **Step 3: Add the backend CEL attribute and type**++In `backend/common/cel_attributes.go`, add:++```go+// CEL attribute names for issue scope.+const (+ // CELAttributeIssueLabels is the canonical labels attached to the issue.+ CELAttributeIssueLabels = "issue.labels"+)+```++In `backend/common/cel.go`, add this variable to `ApprovalFactors` after the risk scope entry:++```go+ // Issue scope+ cel.Variable(CELAttributeIssueLabels, cel.ListType(cel.StringType)),+```++Do not add the variable to `FallbackApprovalFactors`.++- [ ] **Step 4: Run the focused common tests and verify pass**++Run:++```bash+go test -v -count=1 ./backend/common -run '^(TestApprovalFactorsIncludesIssueLabels|TestFallbackApprovalFactorsExcludesIssueLabels)$'+```++Expected: both tests pass.++- [ ] **Step 5: Commit backend CEL env change**++Run:++```bash+gofmt -w backend/common/cel_attributes.go backend/common/cel.go backend/common/cel_test.go+git add backend/common/cel_attributes.go backend/common/cel.go backend/common/cel_test.go+git commit -m "feat: add issue labels to approval CEL"+```++---++### Task 2: Store Guard For Stale Issue Labels++**Files:**+- Modify: `backend/store/issue.go`+- Modify: `backend/store/plan_approval_input_version_test.go`++- [ ] **Step 1: Write failing store tests for label-aware approval writes**++Add these tests to `backend/store/plan_approval_input_version_test.go` after `TestUpdateIssuePayloadIfPlanApprovalInputVersionSkipsIssueWithoutPlan`:++```go+func TestUpdateIssuePayloadIfPlanApprovalInputVersionAndLabelsUpdatesMatchingLabels(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod", "security"},+ RiskLevel: storepb.RiskLevel_LOW,+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ updated, err := s.UpdateIssuePayloadIfPlanApprovalInputVersionAndLabels(ctx, "project-a", issue.UID, &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ }, 2, []string{"security", "prod", "prod"})+ require.NoError(t, err)+ require.True(t, updated)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.Equal(t, storepb.RiskLevel_HIGH, got.Payload.GetRiskLevel())+ require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+}++func TestUpdateIssuePayloadIfPlanApprovalInputVersionAndLabelsSkipsStaleLabels(t *testing.T) {+ ctx := context.Background()+ s := setupPlanApprovalInputVersionStore(ctx, t)++ plan, err := s.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "plan-a",+ Description: "",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2},+ }, "[email protected]")+ require.NoError(t, err)++ issue, err := s.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a",+ CreatorEmail: "[email protected]",+ Title: "issue-a",+ Type: storepb.Issue_DATABASE_CHANGE,+ Description: "",+ Payload: &storepb.Issue{+ Labels: []string{"prod"},+ RiskLevel: storepb.RiskLevel_LOW,+ },+ PlanUID: &plan.UID,+ })+ require.NoError(t, err)++ updatedIssue, err := s.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{Labels: []string{"stage"}},+ })+ require.NoError(t, err)+ require.Equal(t, []string{"stage"}, updatedIssue.Payload.GetLabels())++ updated, err := s.UpdateIssuePayloadIfPlanApprovalInputVersionAndLabels(ctx, "project-a", issue.UID, &storepb.Issue{+ RiskLevel: storepb.RiskLevel_HIGH,+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: true,+ ApprovalInputVersion: 2,+ },+ }, 2, []string{"prod"})+ require.NoError(t, err)+ require.False(t, updated)++ got, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.Equal(t, storepb.RiskLevel_LOW, got.Payload.GetRiskLevel())+ require.Nil(t, got.Payload.GetApproval())+}+```++- [ ] **Step 2: Run the store tests and verify failure**++Run:++```bash+go test -v -count=1 ./backend/store -run '^(TestUpdateIssuePayloadIfPlanApprovalInputVersionAndLabelsUpdatesMatchingLabels|TestUpdateIssuePayloadIfPlanApprovalInputVersionAndLabelsSkipsStaleLabels)$'+```++Expected: compile failure because `UpdateIssuePayloadIfPlanApprovalInputVersionAndLabels` does not exist.++- [ ] **Step 3: Implement the label-aware guarded update**++In `backend/store/issue.go`, add `encoding/json` to imports:++```go+import (+ "context"+ "encoding/json"+ "fmt"+ "slices"+ "strings"+ "time"+)+```++Add this method after `UpdateIssuePayloadIfPlanApprovalInputVersion`:++```go+func (s *Store) UpdateIssuePayloadIfPlanApprovalInputVersionAndLabels(ctx context.Context, projectID string, uid int64, payload *storepb.Issue, approvalInputVersion int64, labels []string) (bool, error) {+ p, err := protojson.Marshal(payload)+ if err != nil {+ return false, errors.Wrapf(err, "failed to marshal payload")+ }+ labelBytes, err := json.Marshal(CanonicalizeIssueLabels(labels))+ if err != nil {+ return false, errors.Wrapf(err, "failed to marshal issue labels")+ }++ q := qb.Q().Space(`+ UPDATE issue+ SET+ updated_at = ?,+ payload = payload || ?+ WHERE project = ?+ AND id = ?+ AND COALESCE(payload->'labels', '[]'::jsonb) = ?::jsonb+ AND EXISTS (+ SELECT 1+ FROM plan+ WHERE plan.project = issue.project+ AND plan.id = issue.plan_id+ AND COALESCE((plan.config->>'approvalInputVersion')::bigint, 0) = ?+ )`, time.Now(), p, projectID, uid, string(labelBytes), approvalInputVersion)++ query, args, err := q.ToSQL()+ if err != nil {+ return false, errors.Wrapf(err, "failed to build sql")+ }+ result, err := s.GetDB().ExecContext(ctx, query, args...)+ if err != nil {+ return false, err+ }+ rowsAffected, err := result.RowsAffected()+ if err != nil {+ return false, errors.Wrapf(err, "failed to inspect issue update")+ }+ return rowsAffected > 0, nil+}+```++- [ ] **Step 4: Run the focused store tests and verify pass**++Run:++```bash+go test -v -count=1 ./backend/store -run '^(TestUpdateIssuePayloadIfPlanApprovalInputVersionAndLabelsUpdatesMatchingLabels|TestUpdateIssuePayloadIfPlanApprovalInputVersionAndLabelsSkipsStaleLabels)$'+```++Expected: both tests pass.++- [ ] **Step 5: Commit store guard**++Run:++```bash+gofmt -w backend/store/issue.go backend/store/plan_approval_input_version_test.go+git add backend/store/issue.go backend/store/plan_approval_input_version_test.go+git commit -m "fix: guard approval writes by issue labels"+```++---++### Task 3: Approval Runner Uses Observed Canonical Labels++**Files:**+- Modify: `backend/runner/approval/runner.go`+- Modify: `backend/runner/approval/runner_test.go`++- [ ] **Step 1: Write failing approval runner tests**++Add these tests to `backend/runner/approval/runner_test.go` near `TestApprovalTemplateMatchesUnspecifiedStatementSQLType`:++```go+func TestApprovalTemplateMatchesIssueLabels(t *testing.T) {+ a := require.New(t)++ celVars := map[string]any{+ common.CELAttributeResourceProjectID: "project",+ common.CELAttributeIssueLabels: []string{"prod", "security"},+ }+ injectRiskLevelIntoCELVars([]map[string]any{celVars}, storepb.RiskLevel_HIGH)++ approvalTemplate, err := getApprovalTemplate(&storepb.WorkspaceApprovalSetting{+ Rules: []*storepb.WorkspaceApprovalSetting_Rule{+ {+ Source: storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE,+ Condition: &expr.Expr{Expression: `"prod" in issue.labels && risk.level == "HIGH"`},+ Template: &storepb.ApprovalTemplate{Title: "Production label rule"},+ },+ },+ }, storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE, []map[string]any{celVars})+ a.NoError(err)+ a.NotNil(approvalTemplate)+ a.Equal("Production label rule", approvalTemplate.Title)+}++func TestInjectIssueLabelsIntoCELVars(t *testing.T) {+ celVarsList := []map[string]any{+ {common.CELAttributeResourceProjectID: "project-a"},+ {common.CELAttributeResourceProjectID: "project-a"},+ }++ injectIssueLabelsIntoCELVars(celVarsList, []string{" security ", "prod", "prod"})++ for _, celVars := range celVarsList {+ require.Equal(t, []string{"prod", "security"}, celVars[common.CELAttributeIssueLabels])+ }+}+```++- [ ] **Step 2: Run the focused approval runner tests and verify failure**++Run:++```bash+go test -v -count=1 ./backend/runner/approval -run '^(TestApprovalTemplateMatchesIssueLabels|TestInjectIssueLabelsIntoCELVars)$'+```++Expected: compile failure for `injectIssueLabelsIntoCELVars`, or CEL compile failure if Task 1 has not been applied.++- [ ] **Step 3: Implement label injection and guarded runner write**++In `backend/runner/approval/runner.go`, add:++```go+func injectIssueLabelsIntoCELVars(celVarsList []map[string]any, labels []string) {+ canonicalLabels := store.CanonicalizeIssueLabels(labels)+ if canonicalLabels == nil {+ canonicalLabels = []string{}+ }+ for _, celVars := range celVarsList {+ celVars[common.CELAttributeIssueLabels] = canonicalLabels+ }+}+```++In `findApprovalTemplateForIssue`, compute labels before the inner closure:++```go+ approvalLabels := store.CanonicalizeIssueLabels(payload.GetLabels())+ if approvalLabels == nil {+ approvalLabels = []string{}+ }+```++After risk-level injection for `CHANGE_DATABASE`, inject labels:++```go+ if approvalSource == storepb.WorkspaceApprovalSetting_Rule_CHANGE_DATABASE {+ riskLevel := calculateRiskLevelFromCELVars(celVarsList)+ injectRiskLevelIntoCELVars(celVarsList, riskLevel)+ injectIssueLabelsIntoCELVars(celVarsList, approvalLabels)+ }+```++Replace the database-change payload write call:++```go+ updated, err := stores.UpdateIssuePayloadIfPlanApprovalInputVersionAndLabels(ctx, issue.ProjectID, issue.UID, payloadPatch, approvalInputVersion, approvalLabels)+```++- [ ] **Step 4: Run the focused approval runner tests and verify pass**++Run:++```bash+go test -v -count=1 ./backend/runner/approval -run '^(TestApprovalTemplateMatchesIssueLabels|TestInjectIssueLabelsIntoCELVars)$'+```++Expected: both tests pass.++- [ ] **Step 5: Commit approval runner label matching**++Run:++```bash+gofmt -w backend/runner/approval/runner.go backend/runner/approval/runner_test.go+git add backend/runner/approval/runner.go backend/runner/approval/runner_test.go+git commit -m "feat: match approval rules on issue labels"+```++---++### Task 4: Label Updates Reset Approval Before Rollout Only++**Files:**+- Modify: `backend/api/v1/issue_service.go`+- Modify: `backend/api/v1/issue_service_test.go`++- [ ] **Step 1: Write failing service tests for label reset behavior**++Add tests in `backend/api/v1/issue_service_test.go` using existing service/store test setup in that file. The tests should create a `DATABASE_CHANGE` issue linked to a plan with `ApprovalInputVersion: 2` and a completed approval payload, then update labels through `IssueService.UpdateIssue`.++The pre-rollout assertion must check:++```go+require.False(t, got.Payload.GetApproval().GetApprovalFindingDone())+require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+```++The post-rollout assertion must mark the plan as rolled out by calling:++```go+approvalInputVersion := int64(2)+marked, _, err := stores.CreateRolloutTasks(ctx, "project-a", plan.UID, &approvalInputVersion, nil)+require.NoError(t, err)+require.True(t, marked)+```++Then update labels and assert:++```go+require.True(t, got.Payload.GetApproval().GetApprovalFindingDone())+require.EqualValues(t, 2, got.Payload.GetApproval().GetApprovalInputVersion())+```++- [ ] **Step 2: Run the focused service tests and verify failure**++Run the exact test names added in Step 1:++```bash+go test -v -count=1 ./backend/api/v1 -run '^(TestUpdateIssueLabelsResetsApprovalBeforeRollout|TestUpdateIssueLabelsDoesNotResetApprovalAfterRollout)$'+```++Expected: the pre-rollout test fails because labels update without resetting approval.++- [ ] **Step 3: Implement label-driven reset in `UpdateIssue`**++In `backend/api/v1/issue_service.go`, track label changes:++```go+ var labelsChanged bool+```++Inside the `"labels"` update-mask case, set it after confirming this is not a no-op:++```go+ labelsChanged = true+```++After `issue, err = s.store.UpdateIssue(...)` and before comment creation, add:++```go+ if labelsChanged && issue.Type == storepb.Issue_DATABASE_CHANGE && issue.PlanUID != nil {+ plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{ProjectID: issue.ProjectID, UID: issue.PlanUID})+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get plan"))+ }+ if plan == nil {+ return nil, connect.NewError(connect.CodeNotFound, errors.New("plan not found"))+ }+ if !plan.Config.GetHasRollout() {+ updatedIssue, updated, err := resetIssueApprovalFindingIfPlanApprovalInputVersion(ctx, s.store, issue, plan.Config.GetApprovalInputVersion())+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to reset approval finding after issue label update"))+ }+ if updated {+ issue = updatedIssue+ s.bus.ApprovalCheckChan <- bus.IssueRef{ProjectID: issue.ProjectID, UID: issue.UID}+ }+ }+ }+```++- [ ] **Step 4: Run the focused service tests and verify pass**++Run:++```bash+go test -v -count=1 ./backend/api/v1 -run '^(TestUpdateIssueLabelsResetsApprovalBeforeRollout|TestUpdateIssueLabelsDoesNotResetApprovalAfterRollout)$'+```++Expected: both tests pass.++- [ ] **Step 5: Commit label reset behavior**++Run:++```bash+gofmt -w backend/api/v1/issue_service.go backend/api/v1/issue_service_test.go+git add backend/api/v1/issue_service.go backend/api/v1/issue_service_test.go+git commit -m "fix: reset approval on issue label changes"+```++---++### Task 5: Frontend CEL Editor List Factor++**Files:**+- Modify: `frontend/src/utils/cel-attributes.ts`+- Modify: `frontend/src/plugins/cel/types/factor.ts`+- Modify: `frontend/src/plugins/cel/types/operator.ts`+- Modify: `frontend/src/plugins/cel/types/simple.ts`+- Modify: `frontend/src/plugins/cel/logic/build.ts`+- Modify: `frontend/src/react/components/CustomApproval/utils.ts`+- Create: `frontend/src/plugins/cel/logic/build.test.ts`+- Create: `frontend/src/react/components/CustomApproval/utils.test.ts`++- [ ] **Step 1: Write failing frontend tests**++Create `frontend/src/plugins/cel/logic/build.test.ts`:++```ts+import { describe, expect, it } from "vitest";+import { ExprType, type SimpleExpr } from "@/plugins/cel";+import { CEL_ATTRIBUTE_ISSUE_LABELS } from "@/utils/cel-attributes";+import { buildCELExpr } from "./build";++describe("buildCELExpr", () => {+ it("builds label membership as value in issue.labels", async () => {+ const expr: SimpleExpr = {+ type: ExprType.Condition,+ operator: "@contains",+ args: [CEL_ATTRIBUTE_ISSUE_LABELS, "prod"],+ };++ const built = await buildCELExpr(expr);++ expect(built?.exprKind.case).toBe("callExpr");+ const call = built?.exprKind.value;+ expect(call?.function).toBe("@in");+ expect(call?.args[0].exprKind.case).toBe("constExpr");+ expect(+ call?.args[0].exprKind.value.constantKind.case+ ).toBe("stringValue");+ expect(+ call?.args[0].exprKind.value.constantKind.value+ ).toBe("prod");+ expect(call?.args[1].exprKind.case).toBe("identExpr");+ expect(call?.args[1].exprKind.value.name).toBe(CEL_ATTRIBUTE_ISSUE_LABELS);+ });+});+```++Create `frontend/src/react/components/CustomApproval/utils.test.ts`:++```ts+import { describe, expect, it } from "vitest";+import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";+import { CEL_ATTRIBUTE_ISSUE_LABELS } from "@/utils/cel-attributes";+import { getApprovalFactorList } from "./utils";++describe("getApprovalFactorList", () => {+ it("exposes issue labels for database-change approval rules only", () => {+ expect(+ getApprovalFactorList(WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE)+ ).toContain(CEL_ATTRIBUTE_ISSUE_LABELS);+ expect(+ getApprovalFactorList(+ WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED+ )+ ).not.toContain(CEL_ATTRIBUTE_ISSUE_LABELS);+ expect(+ getApprovalFactorList(WorkspaceApprovalSetting_Rule_Source.REQUEST_ACCESS)+ ).not.toContain(CEL_ATTRIBUTE_ISSUE_LABELS);+ });+});+```++- [ ] **Step 2: Run frontend tests and verify failure**++Run:++```bash+pnpm --dir frontend test --run build.test.ts utils.test.ts+```++Expected: compile failure because `CEL_ATTRIBUTE_ISSUE_LABELS`, list factors, or `@contains` are not defined.++- [ ] **Step 3: Add frontend constants and list factor type**++In `frontend/src/utils/cel-attributes.ts`, add:++```ts+// CEL attribute names for issue scope.+export const CEL_ATTRIBUTE_ISSUE_LABELS = "issue.labels";+```++In `frontend/src/plugins/cel/types/factor.ts`, import the new constant and add:++```ts+export const ListFactorList = [CEL_ATTRIBUTE_ISSUE_LABELS] as const;+export type ListFactor = (typeof ListFactorList)[number];+```++Extend `Factor`:++```ts+export type Factor =+ | NumberFactor+ | StringFactor+ | BooleanFactor+ | TimestampFactor+ | ListFactor;+```++Add:++```ts+export const isListFactor = (factor: string): factor is ListFactor => {+ return ListFactorList.includes(factor as ListFactor);+};+```++- [ ] **Step 4: Add membership operators and builder support**++In `frontend/src/plugins/cel/types/operator.ts`, add:++```ts+export const ListMembershipOperatorList = ["@contains", "@not_contains"] as const;+export type ListMembershipOperator = (typeof ListMembershipOperatorList)[number];+```++Include `ListMembershipOperator` in `ConditionOperator`, add `isListMembershipOperator`, and add this to `OperatorList`:++```ts+ [CEL_ATTRIBUTE_ISSUE_LABELS]: uniq([...ListMembershipOperatorList]),+```++In `frontend/src/plugins/cel/types/simple.ts`, add:++```ts+export interface ListMembershipExpr extends BaseConditionExpr {+ operator: ListMembershipOperator;+ args: [ListFactor, string];+}+```++Include it in `ConditionExpr` and add:++```ts+export const isListMembershipExpr = (+ expr: SimpleExpr+): expr is ListMembershipExpr => {+ return isConditionExpr(expr) && isListMembershipOperator(expr.operator);+};+```++In `frontend/src/plugins/cel/logic/build.ts`, import `isListMembershipExpr` and handle it before string expressions:++```ts+ if (isListMembershipExpr(condition)) {+ const { operator, args } = condition;+ const [factor, value] = args;+ const membership = wrapCallExpr("@in", [+ wrapConstExpr(value),+ wrapIdentExpr(factor),+ ]);+ if (operator === "@not_contains") {+ return wrapCallExpr("!_", [membership]);+ }+ return membership;+ }+```++- [ ] **Step 5: Expose `issue.labels` for `CHANGE_DATABASE` only**++In `frontend/src/react/components/CustomApproval/utils.ts`, import `CEL_ATTRIBUTE_ISSUE_LABELS` and add it to the `CHANGE_DATABASE` factor list:++```ts+ CEL_ATTRIBUTE_RISK_LEVEL,+ CEL_ATTRIBUTE_ISSUE_LABELS,+```++Do not add it to `SOURCE_UNSPECIFIED` or other source factor lists.++- [ ] **Step 6: Run frontend tests and verify pass**++Run:++```bash+pnpm --dir frontend test --run build.test.ts utils.test.ts+```++Expected: the new frontend tests pass.++- [ ] **Step 7: Commit frontend CEL editor support**++Run:++```bash+pnpm --dir frontend fix+git add frontend/src/utils/cel-attributes.ts frontend/src/plugins/cel/types/factor.ts frontend/src/plugins/cel/types/operator.ts frontend/src/plugins/cel/types/simple.ts frontend/src/plugins/cel/logic/build.ts frontend/src/plugins/cel/logic/build.test.ts frontend/src/react/components/CustomApproval/utils.ts frontend/src/react/components/CustomApproval/utils.test.ts+git commit -m "feat: expose issue labels in approval CEL editor"+```++---++### Task 6: Full Verification++**Files:**+- No code changes expected.++- [ ] **Step 1: Run backend focused tests**++Run:++```bash+go test -v -count=1 ./backend/common ./backend/store ./backend/runner/approval ./backend/api/v1 -run '(IssueLabels|ApprovalInputVersion|UpdateIssueLabels|ApprovalFactors)'+```++Expected: all selected tests pass.++- [ ] **Step 2: Run Go formatting**++Run:++```bash+gofmt -w backend/common/cel_attributes.go backend/common/cel.go backend/common/cel_test.go backend/store/issue.go backend/store/plan_approval_input_version_test.go backend/runner/approval/runner.go backend/runner/approval/runner_test.go backend/api/v1/issue_service.go backend/api/v1/issue_service_test.go+```++Expected: command exits with code 0.++- [ ] **Step 3: Run backend lint**++Run:++```bash+golangci-lint run --allow-parallel-runners+```++Expected: no lint issues. If it reports issues, fix them and rerun the same command until it reports no issues.++- [ ] **Step 4: Run frontend checks**++Run:++```bash+pnpm --dir frontend fix+pnpm --dir frontend check+pnpm --dir frontend type-check+pnpm --dir frontend test+```++Expected: all commands pass.++- [ ] **Step 5: Run backend build**++Run:++```bash+go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go+```++Expected: build succeeds and writes `./bytebase-build/bytebase`.++- [ ] **Step 6: Final git status**++Run:++```bash+git status --short+```++Expected: clean worktree.diff --git a/docs/superpowers/specs/2026-07-03-approval-cel-issue-labels-design.md b/docs/superpowers/specs/2026-07-03-approval-cel-issue-labels-design.mdnew file mode 100644index 0000000000..ad9f3a316e--- /dev/null+++ b/docs/superpowers/specs/2026-07-03-approval-cel-issue-labels-design.md@@ -0,0 +1,150 @@+# Approval CEL Issue Labels Design++## Context++The linked design note splits the approval-flow work into three areas:+approval input correctness, issue labels in approval-flow CEL, and creating+plans and issues together. Approval input correctness is mostly complete. This+spec covers the second slice: exposing issue labels to approval-flow CEL and+making label changes participate in approval correctness.++Issue labels are already stored in `issue.payload.labels`, normalized through+`store.CanonicalizeIssueLabels`, and used by the issue store. Approval-flow CEL+currently evaluates source-specific rules with resource, statement, request,+and risk attributes. Fallback approval rules are deliberately narrower and only+allow `resource.project_id`.++## Goals++- Let `CHANGE_DATABASE` approval rules use `issue.labels`.+- Represent labels as a CEL `list<string>`, so expressions such as+ `"prod" in issue.labels` work naturally.+- Use canonical issue labels for evaluation.+- Reset approval finding when issue labels change before rollout creation.+- Preserve the existing approval flow when issue labels change after rollout+ creation.+- Reject approval payload writes computed from stale issue labels.+- Ensure the generated approval flow matches the canonical labels used to+ compute it.+- Surface `issue.labels` in the custom approval CEL editor.+- Keep fallback approval rules unchanged.++## Non-Goals++- Do not expose labels to `CREATE_DATABASE`, `REQUEST_ROLE`, `REQUEST_ACCESS`,+ or fallback approval rules.+- Do not add a project-label dropdown in the CEL editor.+- Do not change plan/issue lifecycle behavior outside label-driven approval+ invalidation.+- Do not introduce a separate label matcher outside CEL.++## Backend Design++Add a new CEL attribute constant named `issue.labels` in the shared CEL+attribute definitions. Add it to `common.ApprovalFactors` as a+`cel.ListType(cel.StringType)` variable. Do not add it to+`common.FallbackApprovalFactors`.++When building CEL variables for `DATABASE_CHANGE` issues, read labels from+`issue.Payload.GetLabels()`, canonicalize them with+`store.CanonicalizeIssueLabels`, and attach the resulting string slice to every+CEL variable map generated for that issue. This keeps the existing approval+matching model intact: a source-specific rule matches if any generated+per-target CEL variable map evaluates to true.++The attribute is attached only in the `DATABASE_CHANGE` path. Other issue types+continue to receive the variables they receive today.++Because labels become approval-affecting input, the approval runner must keep+the canonical label slice it used while computing the approval template. The+final database write must be conditional on both freshness dimensions:++- The plan still has the approval input version observed by the runner.+- The issue still has the same canonical labels observed by the runner.++If the conditional update affects zero rows, the runner discards the computed+approval payload. This matches the existing stale plan-version behavior and+prevents an older runner from writing approval state after issue labels changed.+The label comparison should use canonical value equality. Empty and missing+labels compare as the same empty list.++This design does not require a new plan-version mechanism. It uses the existing+`approvalInputVersion` guard for plan inputs and adds the missing issue-label+guard for the new approval-affecting input.++Issue-label updates must reset approval finding for `DATABASE_CHANGE` issues+before rollout creation. The `UpdateIssue` labels path already canonicalizes and+compares labels before writing them. When that path makes a real label change+and the issue is linked to a plan whose config does not have `hasRollout`, reset+the issue approval payload with the same approval-input-version-aware helper+used after plan spec changes, then enqueue approval finding again. This keeps+the visible approval flow aligned with the current canonical labels.++Once rollout has been created, label updates must not reset approval finding.+Rollout creation marks the linked plan config with `hasRollout = true`; after+that point labels are metadata for the issue and must not regenerate the+approval flow used to authorize the rollout. The generated approval flow remains+the one computed from the labels that were current when approval was found and+guarded by the stale-label write check.++## Frontend Design++Add `CEL_ATTRIBUTE_ISSUE_LABELS = "issue.labels"` to the frontend CEL+attribute constants. Include it in the `CHANGE_DATABASE` factor list for custom+approval rules.++The existing expression editor can treat `issue.labels` as a normal factor.+This iteration does not need a project-label dropdown or project-label+existence validation. Users can author expressions with typed values, for+example:++```cel+"prod" in issue.labels+```++## Error Handling++Malformed expressions continue to fail through existing approval-rule CEL+compilation. Rules that reference `issue.labels` under fallback approval rules+remain invalid because fallback rules use the restricted fallback CEL+environment.++Missing labels evaluate as an empty canonical string list. Duplicate or+out-of-order labels are normalized before evaluation.++If labels change while approval finding is running, the stale runner may finish,+but its approval payload write is rejected by the label freshness guard. The+label-update path is responsible for resetting approval finding and scheduling a+fresh approval finding pass when no rollout exists.++If labels change after rollout creation, no approval reset is attempted. The+existing approval flow is left intact even if the new labels would have matched+a different approval rule.++## Testing++Add backend tests that verify:++- `common.ApprovalFactors` accepts `issue.labels` list expressions.+- `common.FallbackApprovalFactors` rejects `issue.labels`.+- A `CHANGE_DATABASE` approval rule using `"prod" in issue.labels` matches when+ the issue has that label.+- Canonicalization makes duplicate or unordered labels behave consistently.+- Updating labels before rollout creation resets approval finding and schedules+ a fresh approval flow.+- Updating labels after rollout creation does not reset or regenerate approval+ finding.+- A stale approval payload write is rejected when issue labels changed after the+ runner observed them.+- The existing plan approval input version guard still rejects stale plan-input+ writes.++Add frontend coverage where practical for the factor list, or otherwise rely on+the existing frontend check and type-check gates for the small constant/map+change.++## Rollout++This is additive for source-specific `CHANGE_DATABASE` approval rules. Existing+rules keep their behavior. Fallback rules remain intentionally unchanged, so no+migration is required.diff --git a/frontend/src/plugins/cel/logic/build.test.ts b/frontend/src/plugins/cel/logic/build.test.tsnew file mode 100644index 0000000000..2dba161367--- /dev/null+++ b/frontend/src/plugins/cel/logic/build.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";+import { ExprType, type SimpleExpr } from "@/plugins/cel";+import {+ CEL_ATTRIBUTE_ISSUE_LABELS,+ CEL_ATTRIBUTE_STATEMENT_TEXT,+} from "@/utils/cel-attributes";+import { buildCELExpr } from "./build";++describe("buildCELExpr", () => {+ it("builds label membership as value in issue.labels", async () => {+ const expr: SimpleExpr = {+ type: ExprType.Condition,+ operator: "@contains",+ args: [CEL_ATTRIBUTE_ISSUE_LABELS, "prod"],+ };++ const built = await buildCELExpr(expr);++ expect(built?.exprKind.case).toBe("callExpr");+ if (built?.exprKind.case !== "callExpr") {+ throw new Error("expected callExpr");+ }+ const call = built.exprKind.value;+ expect(call.function).toBe("@in");++ const valueExpr = call.args[0];+ expect(valueExpr.exprKind.case).toBe("constExpr");+ if (valueExpr.exprKind.case !== "constExpr") {+ throw new Error("expected constExpr");+ }+ const constantKind = valueExpr.exprKind.value.constantKind;+ expect(constantKind.case).toBe("stringValue");+ if (constantKind.case !== "stringValue") {+ throw new Error("expected stringValue");+ }+ expect(constantKind.value).toBe("prod");++ const factorExpr = call.args[1];+ expect(factorExpr.exprKind.case).toBe("identExpr");+ if (factorExpr.exprKind.case !== "identExpr") {+ throw new Error("expected identExpr");+ }+ expect(factorExpr.exprKind.value.name).toBe(CEL_ATTRIBUTE_ISSUE_LABELS);+ });++ it("keeps string not contains as a target call", async () => {+ const expr: SimpleExpr = {+ type: ExprType.Condition,+ operator: "@not_contains",+ args: [CEL_ATTRIBUTE_STATEMENT_TEXT, "drop"],+ };++ const built = await buildCELExpr(expr);++ expect(built?.exprKind.case).toBe("callExpr");+ if (built?.exprKind.case !== "callExpr") {+ throw new Error("expected callExpr");+ }+ const negation = built.exprKind.value;+ expect(negation.function).toBe("!_");+ const containsExpr = negation.args[0];+ expect(containsExpr.exprKind.case).toBe("callExpr");+ if (containsExpr.exprKind.case !== "callExpr") {+ throw new Error("expected callExpr");+ }+ const contains = containsExpr.exprKind.value;+ expect(contains.function).toBe("contains");+ expect(contains.target?.exprKind.case).toBe("identExpr");+ if (contains.target?.exprKind.case !== "identExpr") {+ throw new Error("expected identExpr target");+ }+ expect(contains.target.exprKind.value.name).toBe(+ CEL_ATTRIBUTE_STATEMENT_TEXT+ );+ });+});diff --git a/frontend/src/plugins/cel/logic/build.ts b/frontend/src/plugins/cel/logic/build.tsindex 5405b5d390..05a8b326bb 100644--- a/frontend/src/plugins/cel/logic/build.ts+++ b/frontend/src/plugins/cel/logic/build.ts@@ -20,6 +20,7 @@ import {isConditionExpr,isConditionGroupExpr,isEqualityExpr,+ isListMembershipExpr,isRawStringExpr,isStringExpr,} from "../types";@@ -69,6 +70,18 @@ export const buildCELExpr = async (wrapConstExpr(value),]);}+ if (isListMembershipExpr(condition)) {+ const { operator, args } = condition;+ const [factor, value] = args;+ const membership = wrapCallExpr("@in", [+ wrapConstExpr(value),+ wrapIdentExpr(factor),+ ]);+ if (operator === "@not_contains") {+ return wrapCallExpr("!_", [membership]);+ }+ return membership;+ }if (isStringExpr(condition)) {const { operator, args } = condition;const [factor, value] = args;diff --git a/frontend/src/plugins/cel/logic/resolve.test.ts b/frontend/src/plugins/cel/logic/resolve.test.tsnew file mode 100644index 0000000000..8ad9f40277--- /dev/null+++ b/frontend/src/plugins/cel/logic/resolve.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";+import { ExprType, type SimpleExpr } from "@/plugins/cel";+import { CEL_ATTRIBUTE_ISSUE_LABELS } from "@/utils/cel-attributes";+import { buildCELExpr } from "./build";+import { resolveCELExpr } from "./resolve";++describe("resolveCELExpr", () => {+ it("round-trips list membership from built CEL", async () => {+ const expr: SimpleExpr = {+ type: ExprType.Condition,+ operator: "@contains",+ args: [CEL_ATTRIBUTE_ISSUE_LABELS, "prod"],+ };++ const built = await buildCELExpr(expr);++ expect(built).toBeDefined();+ if (!built) {+ throw new Error("expected built CEL expression");+ }+ expect(resolveCELExpr(built)).toEqual(expr);+ });++ it("round-trips negated list membership from built CEL", async () => {+ const expr: SimpleExpr = {+ type: ExprType.Condition,+ operator: "@not_contains",+ args: [CEL_ATTRIBUTE_ISSUE_LABELS, "prod"],+ };++ const built = await buildCELExpr(expr);++ expect(built).toBeDefined();+ if (!built) {+ throw new Error("expected built CEL expression");+ }+ expect(resolveCELExpr(built)).toEqual(expr);+ });+});diff --git a/frontend/src/plugins/cel/logic/resolve.ts b/frontend/src/plugins/cel/logic/resolve.tsindex 31b42a55c8..0a58fd49fe 100644--- a/frontend/src/plugins/cel/logic/resolve.ts+++ b/frontend/src/plugins/cel/logic/resolve.ts@@ -7,6 +7,9 @@ import type {ConditionGroupExpr,EqualityExpr,EqualityOperator,+ ListFactor,+ ListMembershipExpr,+ ListMembershipOperator,LogicalOperator,Operator,RawStringExpr,@@ -22,6 +25,7 @@ import {isCompareOperator,isConditionGroupExpr,isEqualityOperator,+ isListFactor,isLogicalOperator,isNegativeOperator,isNumberFactor,@@ -123,6 +127,9 @@ export const resolveCELExpr = (expr: CELExpr): SimpleExpr => {return resolveStringExpr(expr, negative);}if (isCollectionOperator(operator)) {+ if (isListMembershipCall(expr)) {+ return resolveListMembershipExpr(expr, negative);+ }return resolveCollectionExpr(expr, negative);}throw new Error(`unsupported expr "${JSON.stringify(expr)}"`);@@ -134,6 +141,30 @@ export const resolveCELExpr = (expr: CELExpr): SimpleExpr => {return dfs(expr);};+const isStringConstantExpr = (expr: CELExpr): boolean => {+ return (+ expr.exprKind?.case === "constExpr" &&+ expr.exprKind.value.constantKind?.case === "stringValue"+ );+};++const isListMembershipCall = (expr: CELExpr): boolean => {+ const callExpr =+ expr.exprKind?.case === "callExpr" ? expr.exprKind.value : null;+ if (!callExpr || callExpr.function !== "@in") {+ return false;+ }+ const [valueExpr, factorExpr] = callExpr.args;+ if (!valueExpr || !factorExpr || !isStringConstantExpr(valueExpr)) {+ return false;+ }+ try {+ return isListFactor(getFactorName(factorExpr));+ } catch {+ return false;+ }+};+const resolveEqualityExpr = (expr: CELExpr): EqualityExpr => {const callExpr =expr.exprKind?.case === "callExpr" ? expr.exprKind.value : null;@@ -218,6 +249,28 @@ const resolveStringExpr = (};};+const resolveListMembershipExpr = (+ expr: CELExpr,+ negative: boolean = false+): ListMembershipExpr => {+ const callExpr =+ expr.exprKind?.case === "callExpr" ? expr.exprKind.value : null;+ if (!callExpr)+ throw new Error(`Expected callExpr but got ${expr.exprKind?.case}`);+ const [valueExpr, factorExpr] = callExpr.args;+ const operator: ListMembershipOperator = negative+ ? "@not_contains"+ : "@contains";+ return {+ type: ExprType.Condition,+ operator,+ args: [+ getFactorName(factorExpr) as ListFactor,+ getConstantStringValue(valueExpr),+ ],+ };+};+const resolveCollectionExpr = (expr: CELExpr,negative: boolean = falsediff --git a/frontend/src/plugins/cel/logic/validate.test.ts b/frontend/src/plugins/cel/logic/validate.test.tsnew file mode 100644index 0000000000..5532d9f5ef--- /dev/null+++ b/frontend/src/plugins/cel/logic/validate.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";+import { ExprType, type SimpleExpr } from "@/plugins/cel";+import { CEL_ATTRIBUTE_ISSUE_LABELS } from "@/utils/cel-attributes";+import { validateSimpleExpr } from "./validate";++describe("validateSimpleExpr", () => {+ it("accepts valid list membership", () => {+ const expr: SimpleExpr = {+ type: ExprType.Condition,+ operator: "@contains",+ args: [CEL_ATTRIBUTE_ISSUE_LABELS, "prod"],+ };++ expect(validateSimpleExpr(expr)).toBe(true);+ });++ it("rejects list membership with empty string value", () => {+ const expr: SimpleExpr = {+ type: ExprType.Condition,+ operator: "@contains",+ args: [CEL_ATTRIBUTE_ISSUE_LABELS, ""],+ };++ expect(validateSimpleExpr(expr)).toBe(false);+ });+});diff --git a/frontend/src/plugins/cel/logic/validate.ts b/frontend/src/plugins/cel/logic/validate.tsindex c8ff6450ba..d998db2ed5 100644--- a/frontend/src/plugins/cel/logic/validate.ts+++ b/frontend/src/plugins/cel/logic/validate.ts@@ -12,6 +12,7 @@ import {isConditionExpr,isConditionGroupExpr,isEqualityExpr,+ isListMembershipExpr,isNumberFactor,isRawStringExpr,isStringExpr,@@ -65,6 +66,10 @@ export const validateSimpleExpr = (expr: SimpleExpr): boolean => {const value = condition.args[1];return validateString(value);}+ if (isListMembershipExpr(condition)) {+ const value = condition.args[1];+ return validateString(value);+ }// unknown condition expr typereturn false;};diff --git a/frontend/src/plugins/cel/types/factor.ts b/frontend/src/plugins/cel/types/factor.tsindex 6ce603a3b1..99fcd99ed0 100644--- a/frontend/src/plugins/cel/types/factor.ts+++ b/frontend/src/plugins/cel/types/factor.ts@@ -1,4 +1,5 @@import {+ CEL_ATTRIBUTE_ISSUE_LABELS,CEL_ATTRIBUTE_REQUEST_EXPIRATION_DAYS,CEL_ATTRIBUTE_REQUEST_EXPORT,CEL_ATTRIBUTE_REQUEST_ROLE,@@ -67,11 +68,15 @@ export type BooleanFactor = (typeof BooleanFactorList)[number];export const TimestampFactorList = [CEL_ATTRIBUTE_REQUEST_TIME] as const;export type TimestampFactor = (typeof TimestampFactorList)[number];+export const ListFactorList = [CEL_ATTRIBUTE_ISSUE_LABELS] as const;+export type ListFactor = (typeof ListFactorList)[number];+export type Factor =| NumberFactor| StringFactor| BooleanFactor- | TimestampFactor;+ | TimestampFactor+ | ListFactor;export const isNumberFactor = (factor: string): factor is NumberFactor => {return NumberFactorList.includes(factor as NumberFactor);@@ -90,3 +95,7 @@ export const isTimestampFactor = (): factor is TimestampFactor => {return TimestampFactorList.includes(factor as TimestampFactor);};++export const isListFactor = (factor: string): factor is ListFactor => {+ return ListFactorList.includes(factor as ListFactor);+};diff --git a/frontend/src/plugins/cel/types/operator.ts b/frontend/src/plugins/cel/types/operator.tsindex ab9fb0d6cf..7455715595 100644--- a/frontend/src/plugins/cel/types/operator.ts+++ b/frontend/src/plugins/cel/types/operator.ts@@ -1,5 +1,6 @@import { uniq } from "lodash-es";import {+ CEL_ATTRIBUTE_ISSUE_LABELS,CEL_ATTRIBUTE_REQUEST_EXPIRATION_DAYS,CEL_ATTRIBUTE_REQUEST_EXPORT,CEL_ATTRIBUTE_REQUEST_ROLE,@@ -38,6 +39,13 @@ export type CompareOperator = (typeof CompareOperatorList)[number];export const CollectionOperatorList = ["@in", "@not_in"] as const;export type CollectionOperator = (typeof CollectionOperatorList)[number];+export const ListMembershipOperatorList = [+ "@contains",+ "@not_contains",+] as const;+export type ListMembershipOperator =+ (typeof ListMembershipOperatorList)[number];+export const StringOperatorList = ["contains","@not_contains",@@ -52,6 +60,7 @@ export type ConditionOperator =| EqualityOperator| CompareOperator| CollectionOperator+ | ListMembershipOperator| StringOperator;export type Operator = LogicalOperator | NegativeOperator | ConditionOperator;@@ -75,6 +84,11 @@ export const isCollectionOperator = (export const isStringOperator = (op: Operator): op is StringOperator => {return StringOperatorList.includes(op as StringOperator);};+export const isListMembershipOperator = (+ op: Operator+): op is ListMembershipOperator => {+ return ListMembershipOperatorList.includes(op as ListMembershipOperator);+};// Display labels for operators that differ from their source form.const OPERATOR_DISPLAY: Record<string, string> = {@@ -84,6 +98,7 @@ const OPERATOR_DISPLAY: Record<string, string> = {"!=": "≠","@in": "in","@not_in": "not in",+ "@contains": "contains","@not_contains": "not contains",};@@ -184,6 +199,8 @@ const OperatorList: Record<Factor, Operator[]> = {// These factors don't have operator candidates for user selection.[CEL_ATTRIBUTE_RESOURCE_DATABASE]: [],[CEL_ATTRIBUTE_REQUEST_TIME]: [],++ [CEL_ATTRIBUTE_ISSUE_LABELS]: uniq([...ListMembershipOperatorList]),};export const getOperatorListByFactor = (factor: Factor) => {diff --git a/frontend/src/plugins/cel/types/simple.ts b/frontend/src/plugins/cel/types/simple.tsindex e40ea49368..90fc98a9da 100644--- a/frontend/src/plugins/cel/types/simple.ts+++ b/frontend/src/plugins/cel/types/simple.ts@@ -1,7 +1,10 @@/// Define a simplified version (less nested) of CEL Expr./// Convenient for local editing.-import type {+import {BooleanFactor,+ isListFactor,+ isStringFactor,+ ListFactor,NumberFactor,StringFactor,TimestampFactor,@@ -13,7 +16,9 @@ import {isCollectionOperator,isCompareOperator,isEqualityOperator,+ isListMembershipOperator,isStringOperator,+ type ListMembershipOperator,type LogicalOperator,type StringOperator,} from "./operator";@@ -51,11 +56,17 @@ export interface StringExpr extends BaseConditionExpr {args: [StringFactor, string];}+export interface ListMembershipExpr extends BaseConditionExpr {+ operator: ListMembershipOperator;+ args: [ListFactor, string];+}+export type ConditionExpr =| EqualityExpr| CompareExpr| CollectionExpr- | StringExpr;+ | StringExpr+ | ListMembershipExpr;// RawStringExpr is used to represent a string that is unable to be parsed as a condition.export type RawStringExpr = {@@ -96,7 +107,21 @@ export const isCollectionExpr = (expr: SimpleExpr): expr is CollectionExpr => {};export const isStringExpr = (expr: SimpleExpr): expr is StringExpr => {- return isConditionExpr(expr) && isStringOperator(expr.operator);+ return (+ isConditionExpr(expr) &&+ isStringOperator(expr.operator) &&+ isStringFactor(expr.args[0])+ );+};++export const isListMembershipExpr = (+ expr: SimpleExpr+): expr is ListMembershipExpr => {+ return (+ isConditionExpr(expr) &&+ isListMembershipOperator(expr.operator) &&+ isListFactor(expr.args[0])+ );};export const isRawStringExpr = (expr: SimpleExpr): expr is RawStringExpr => {diff --git a/frontend/src/react/components/CustomApproval/utils.test.ts b/frontend/src/react/components/CustomApproval/utils.test.tsnew file mode 100644index 0000000000..d97f47d65b--- /dev/null+++ b/frontend/src/react/components/CustomApproval/utils.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from "vitest";+import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";+import { CEL_ATTRIBUTE_ISSUE_LABELS } from "@/utils/cel-attributes";+import { getApprovalFactorList } from "./utils";++describe("getApprovalFactorList", () => {+ it("exposes issue labels for database-change approval rules only", () => {+ expect(+ getApprovalFactorList(+ WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE+ )+ ).toContain(CEL_ATTRIBUTE_ISSUE_LABELS);+ expect(+ getApprovalFactorList(+ WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED+ )+ ).not.toContain(CEL_ATTRIBUTE_ISSUE_LABELS);+ expect(+ getApprovalFactorList(WorkspaceApprovalSetting_Rule_Source.REQUEST_ACCESS)+ ).not.toContain(CEL_ATTRIBUTE_ISSUE_LABELS);+ });+});diff --git a/frontend/src/react/components/CustomApproval/utils.ts b/frontend/src/react/components/CustomApproval/utils.tsindex 2108adbfdd..05ed7ec7bc 100644--- a/frontend/src/react/components/CustomApproval/utils.ts+++ b/frontend/src/react/components/CustomApproval/utils.ts@@ -19,6 +19,7 @@ import {supportedEngineV1List,} from "@/utils";import {+ CEL_ATTRIBUTE_ISSUE_LABELS,CEL_ATTRIBUTE_REQUEST_EXPIRATION_DAYS,CEL_ATTRIBUTE_REQUEST_EXPORT,CEL_ATTRIBUTE_REQUEST_ROLE,@@ -123,6 +124,7 @@ export const ApprovalSourceFactorMap: Map<...schemaObjectNameFactorList,...migrationFactorList,CEL_ATTRIBUTE_RISK_LEVEL,+ CEL_ATTRIBUTE_ISSUE_LABELS,],],[diff --git a/frontend/src/utils/cel-attributes.ts b/frontend/src/utils/cel-attributes.tsindex 53a9595389..4510ffdc84 100644--- a/frontend/src/utils/cel-attributes.ts+++ b/frontend/src/utils/cel-attributes.ts@@ -26,5 +26,8 @@ export const CEL_ATTRIBUTE_REQUEST_UNMASK = "request.unmask";export const CEL_ATTRIBUTE_REQUEST_EXPORT = "request.data_export";export const CEL_ATTRIBUTE_REQUEST_TIME = "request.time";+// CEL attribute names for issue scope.+export const CEL_ATTRIBUTE_ISSUE_LABELS = "issue.labels";+// CEL attribute names for risk scope.export const CEL_ATTRIBUTE_RISK_LEVEL = "risk.level";