Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: consolidate grant request auto-completion logic (#18715)
Danny Xu08258c46b866
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex 3b5e4a99bf..a1eab82b0e 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -406,6 +406,28 @@ func (s *IssueService) CreateIssue(ctx context.Context, req *connect.Request[v1plog.BBError(err))// Continue anyway - non-fatal error}++ // Refresh issue to get updated approval payload+ uid := issue.UID+ issue, err = s.store.GetIssue(ctx, &store.FindIssueMessage{UID: &uid})+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to refresh issue"))+ }++ // For GRANT_REQUEST that is auto-approved (no approval template), complete it+ if issue.Type == storepb.Issue_GRANT_REQUEST {+ approved, err := utils.CheckApprovalApproved(issue.Payload.Approval)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to check if approval is approved"))+ }+ if approved {+ issue, err = s.completeGrantRequestIssue(ctx, issue, issue.Payload.GrantRequest)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal,+ errors.Wrapf(err, "failed to complete grant request"))+ }+ }+ }case storepb.Issue_DATABASE_CHANGE:// DATABASE_CHANGE needs to wait for plan check to complete// Trigger async approval finding via event channel@@ -592,14 +614,6 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update issue"))}- // Grant the privilege if the issue is approved.- if approved && issue.Type == storepb.Issue_GRANT_REQUEST {- if err := utils.UpdateProjectPolicyFromGrantIssue(ctx, s.store, issue, payload.GrantRequest); err != nil {- return nil, err- }- // TODO(p0ny): Post project IAM policy update activity.- }-if _, err := s.store.CreateIssueComments(ctx, user.Email, &store.IssueCommentMessage{IssueUID: issue.UID,Payload: &storepb.IssueCommentPayload{@@ -616,38 +630,11 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1approval.NotifyApprovalRequested(ctx, s.store, s.webhookManager, issue, project)- // If the issue is a grant request and approved, we will always auto close it.- if issue.Type == storepb.Issue_GRANT_REQUEST {- if err := func() error {- payload := issue.Payload- approved, err := utils.CheckApprovalApproved(payload.Approval)- if err != nil {- return errors.Wrap(err, "failed to check if the approval is approved")- }- if approved {- newStatus := storepb.Issue_DONE- updatedIssue, err := s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{Status: &newStatus})- if err != nil {- return errors.Wrapf(err, "failed to update issue %q's status", issue.Title)- }-- if _, err := s.store.CreateIssueComments(ctx, common.SystemBotEmail, &store.IssueCommentMessage{- IssueUID: issue.UID,- Payload: &storepb.IssueCommentPayload{- Event: &storepb.IssueCommentPayload_IssueUpdate_{- IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{- FromStatus: &issue.Status,- ToStatus: &updatedIssue.Status,- },- },- },- }); err != nil {- return errors.Wrapf(err, "failed to create issue comment after changing the issue status")- }- }- return nil- }(); err != nil {- slog.Debug("failed to update issue status to done if grant request issue is approved", log.BBError(err))+ // If the issue is a grant request and approved, complete it+ if issue.Type == storepb.Issue_GRANT_REQUEST && approved {+ issue, err = s.completeGrantRequestIssue(ctx, issue, payload.GrantRequest)+ if err != nil {+ slog.Debug("failed to complete grant request issue", log.BBError(err))}}@@ -1240,6 +1227,44 @@ func (s *IssueService) getIssueMessage(ctx context.Context, name string) (*storereturn issue, nil}+// completeGrantRequestIssue grants privilege and closes a grant request issue.+// Called when:+// 1. Issue created without approval template (auto-approved)+// 2. Issue approval flow completes+//+// Returns the updated issue with DONE status.+func (s *IssueService) completeGrantRequestIssue(ctx context.Context, issue *store.IssueMessage, grantRequest *storepb.GrantRequest) (*store.IssueMessage, error) {+ // Grant the privilege+ if err := utils.UpdateProjectPolicyFromGrantIssue(ctx, s.store, issue, grantRequest); err != nil {+ return nil, err+ }++ // Update issue status to DONE+ newStatus := storepb.Issue_DONE+ updatedIssue, err := s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{Status: &newStatus})+ if err != nil {+ return nil, errors.Wrapf(err, "failed to update issue %q's status", issue.Title)+ }++ // Create issue comment documenting the status change+ if _, err := s.store.CreateIssueComments(ctx, common.SystemBotEmail, &store.IssueCommentMessage{+ IssueUID: issue.UID,+ Payload: &storepb.IssueCommentPayload{+ Event: &storepb.IssueCommentPayload_IssueUpdate_{+ IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{+ FromStatus: &issue.Status,+ ToStatus: &updatedIssue.Status,+ },+ },+ },+ }); err != nil {+ // Non-fatal: log warning but continue+ slog.Warn("failed to create issue comment after changing the issue status", log.BBError(err))+ }++ return updatedIssue, nil+}+func (s *IssueService) isUserReviewer(ctx context.Context, issue *store.IssueMessage, role string, user *store.UserMessage) bool {roles := s.getUserRoleMap(ctx, issue.ProjectID, user)return roles[role]diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.goindex ab7d7e4d97..281f184355 100644--- a/backend/runner/approval/runner.go+++ b/backend/runner/approval/runner.go@@ -167,38 +167,6 @@ func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webhreturn nil}- // Grant privilege and close issue similar to actions on issue approval.- if issue.Type == storepb.Issue_GRANT_REQUEST && approvalTemplate == nil {- if err := utils.UpdateProjectPolicyFromGrantIssue(ctx, stores, issue, payload.GrantRequest); err != nil {- return err- }- if err := func() error {- newStatus := storepb.Issue_DONE- updatedIssue, err := stores.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{Status: &newStatus})- if err != nil {- return errors.Wrapf(err, "failed to update issue %q's status", issue.Title)- }-- if _, err := stores.CreateIssueComments(ctx, common.SystemBotEmail, &store.IssueCommentMessage{- IssueUID: issue.UID,- Payload: &storepb.IssueCommentPayload{- Event: &storepb.IssueCommentPayload_IssueUpdate_{- IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{- FromStatus: &issue.Status,- ToStatus: &updatedIssue.Status,- },- },- },- }); err != nil {- return errors.Wrapf(err, "failed to create issue comment after changing the issue status")- }-- return nil- }(); err != nil {- return errors.Wrap(err, "failed to update issue status")- }- }-// Calculate risk level separately from approval flow// TODO(p0ny): maybe move risk calculation to another runner in the futureriskLevel := calculateRiskLevelFromCELVars(celVarsList)diff --git a/docs/plans/2025-12-31-grant-request-refactor-design.md b/docs/plans/2025-12-31-grant-request-refactor-design.mdnew file mode 100644index 0000000000..65cd3ffd5f--- /dev/null+++ b/docs/plans/2025-12-31-grant-request-refactor-design.md@@ -0,0 +1,218 @@+# Grant Request Auto-Completion Refactoring++## Problem++Grant request completion logic (grant privilege + close issue + create comment) is duplicated in two places:++1. **Runner** (`backend/runner/approval/runner.go:171-200`): When no approval template is found during issue creation+2. **ApproveIssue** (`backend/api/v1/issue_service.go:619-652`): When approval flow completes++Additionally, there's partial duplication at `issue_service.go:596-601` for granting privilege.++## Solution++1. Create a private helper method `completeGrantRequestIssue` on `IssueService`+2. Remove grant+close logic from the approval runner+3. Call the helper from both `CreateIssue` (when no approval needed) and `ApproveIssue` (when approval completes)++## Benefits++- Eliminates code duplication+- Separates concerns: runner finds approvals, service layer executes business logic+- Single source of truth for grant request completion+- Cleaner, more maintainable code++## Design Details++### 1. New Helper Method++Location: `backend/api/v1/issue_service.go`++```go+// completeGrantRequestIssue grants privilege and closes a grant request issue.+// Called when:+// 1. Issue created without approval template (auto-approved)+// 2. Issue approval flow completes+//+// Returns the updated issue with DONE status.+func (s *IssueService) completeGrantRequestIssue(+ ctx context.Context,+ issue *store.IssueMessage,+ grantRequest *storepb.GrantRequest,+) (*store.IssueMessage, error) {+ // 1. Grant the privilege+ if err := utils.UpdateProjectPolicyFromGrantIssue(ctx, s.store, issue, grantRequest); err != nil {+ return nil, err+ }++ // 2. Update issue status to DONE+ newStatus := storepb.Issue_DONE+ updatedIssue, err := s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{+ Status: &newStatus,+ })+ if err != nil {+ return nil, errors.Wrapf(err, "failed to update issue %q's status", issue.Title)+ }++ // 3. Create issue comment documenting the status change+ if _, err := s.store.CreateIssueComments(ctx, common.SystemBotEmail, &store.IssueCommentMessage{+ IssueUID: issue.UID,+ Payload: &storepb.IssueCommentPayload{+ Event: &storepb.IssueCommentPayload_IssueUpdate_{+ IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{+ FromStatus: &issue.Status,+ ToStatus: &updatedIssue.Status,+ },+ },+ },+ }); err != nil {+ // Non-fatal: log warning but continue+ slog.Warn("failed to create issue comment after changing the issue status", log.BBError(err))+ }++ return updatedIssue, nil+}+```++### 2. Modify `FindAndApplyApprovalTemplate`++Update signature to return whether approval template was found:++```go+func FindAndApplyApprovalTemplate(+ ctx context.Context,+ stores *store.Store,+ webhookManager *webhook.Manager,+ licenseService *enterprise.LicenseService,+ issue *store.IssueMessage,+) (approvalTemplateFound bool, error)+```++Changes in `backend/runner/approval/runner.go`:+- Remove grant+close logic (lines 170-200)+- Return `approvalTemplate != nil, nil` at the end+- Update all callers to handle the new return value++### 3. Update `CreateIssue`++Location: `backend/api/v1/issue_service.go:395-415`++```go+// Trigger approval finding based on issue type+switch issue.Type {+case storepb.Issue_GRANT_REQUEST, storepb.Issue_DATABASE_EXPORT:+ approvalTemplateFound, err := approval.FindAndApplyApprovalTemplate(+ ctx, s.store, s.webhookManager, s.licenseService, issue)+ if err != nil {+ slog.Error("failed to find approval template",+ slog.Int("issue_uid", issue.UID),+ slog.String("issue_title", issue.Title),+ log.BBError(err))+ // Continue anyway - non-fatal error+ }++ // For GRANT_REQUEST without approval template, auto-complete it+ if issue.Type == storepb.Issue_GRANT_REQUEST && !approvalTemplateFound {+ issue, err = s.completeGrantRequestIssue(ctx, issue, issue.Payload.GrantRequest)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal,+ errors.Wrapf(err, "failed to complete grant request"))+ }+ }+case storepb.Issue_DATABASE_CHANGE:+ // DATABASE_CHANGE needs to wait for plan check to complete+ s.bus.ApprovalCheckChan <- int64(issue.UID)+default:+ // For other issue types, no approval finding needed+}+```++### 4. Update `ApproveIssue`++Location: `backend/api/v1/issue_service.go:595-652`++Replace existing logic:++**Before (lines 595-601):**+```go+// Grant the privilege if the issue is approved.+if approved && issue.Type == storepb.Issue_GRANT_REQUEST {+ if err := utils.UpdateProjectPolicyFromGrantIssue(ctx, s.store, issue, payload.GrantRequest); err != nil {+ return nil, err+ }+ // TODO(p0ny): Post project IAM policy update activity.+}+```++**After:**+```go+// Grant the privilege if the issue is approved (will be completed below)+// TODO(p0ny): Post project IAM policy update activity.+```++**Replace lines 619-652 with:**+```go+// If the issue is a grant request and approved, complete it+if issue.Type == storepb.Issue_GRANT_REQUEST && approved {+ var err error+ issue, err = s.completeGrantRequestIssue(ctx, issue, payload.GrantRequest)+ if err != nil {+ slog.Debug("failed to complete grant request issue", log.BBError(err))+ }+}+```++### 5. Update Runner++Location: `backend/runner/approval/runner.go`++**Remove lines 170-200** (entire grant+close block)++**Update return at line 224:**+```go+return approvalTemplate != nil, nil+```++**Update line 62** (signature):+```go+func FindAndApplyApprovalTemplate(...) (bool, error)+```++**Update line 95** (processIssue call):+```go+if _, err := findApprovalTemplateForIssue(...); err != nil {+```++## Error Handling++1. **In `completeGrantRequestIssue`**:+ - If `UpdateProjectPolicyFromGrantIssue` fails → return error (don't close issue)+ - If status update fails → return error (privilege granted, issue not closed)+ - If comment creation fails → log warning, continue (non-critical)++2. **In `CreateIssue`**:+ - If `completeGrantRequestIssue` fails → return error to user++3. **In `ApproveIssue`**:+ - If `completeGrantRequestIssue` fails → log debug, continue (matches current behavior)++## Edge Cases++- ✅ Grant request with approval template → normal approval flow+- ✅ Grant request without approval template → auto-completed in CreateIssue+- ✅ Grant request approval completes → completed in ApproveIssue+- ✅ DATABASE_EXPORT without approval → no change (doesn't need completion)++## Files Modified++1. `backend/api/v1/issue_service.go` - Add helper method, update CreateIssue and ApproveIssue+2. `backend/runner/approval/runner.go` - Remove grant+close logic, update return type++## Testing Considerations++1. **Unit tests**: Test `completeGrantRequestIssue` with various scenarios+2. **Integration tests**:+ - Create grant request without approval → should auto-complete+ - Create grant request with approval → should wait for approval+ - Approve grant request → should complete after approval+3. **Error cases**: Test failures in privilege grant and status update