Skip to content

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

5.4 KB
Raw Blame
package v1

import (
	"context"
	"log/slog"

	"github.com/pkg/errors"

	"github.com/bytebase/bytebase/backend/common"
	"github.com/bytebase/bytebase/backend/common/log"
	"github.com/bytebase/bytebase/backend/component/bus"
	"github.com/bytebase/bytebase/backend/component/review"
	"github.com/bytebase/bytebase/backend/component/webhook"
	"github.com/bytebase/bytebase/backend/enterprise"
	storepb "github.com/bytebase/bytebase/backend/generated-go/store"
	"github.com/bytebase/bytebase/backend/store"
	"github.com/bytebase/bytebase/backend/utils"
)

// startIssueWorkflow starts webhook, approval-finding, and auto-approval work
// after direct creation or draft submission.
func startIssueWorkflow(
	ctx context.Context,
	stores *store.Store,
	webhookManager *webhook.Manager,
	licenseService *enterprise.LicenseService,
	b *bus.Bus,
	project *store.ProjectMessage,
	creatorName string,
	creatorEmail string,
	issue *store.IssueMessage,
) (*store.IssueMessage, error) {
	if issue.Type == storepb.Issue_DATABASE_CHANGE {
		recordReviewSubmission(ctx, stores, creatorEmail, issue)
	}
	emitIssueCreated(ctx, webhookManager, project, creatorName, creatorEmail, issue)

	// Trigger approval finding based on issue type.
	switch issue.Type {
	case
		storepb.Issue_ACCESS_GRANT,
		storepb.Issue_ROLE_GRANT:

		result, err := review.FindAndApplyApprovalTemplate(ctx, stores, licenseService, issue)
		if err != nil {
			slog.Error("failed to find approval template",
				slog.String("project", issue.ProjectID), slog.Int64("issue_uid", issue.UID),
				slog.String("issue_title", issue.Title),
				log.BBError(err))
		} else {
			review.DispatchApprovalEvents(ctx, stores, webhookManager, result)
		}

		// Refresh issue to get updated approval payload.
		uid := issue.UID
		issue, err = stores.GetIssue(ctx, &store.FindIssueMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectIDs: []string{issue.ProjectID}, UID: &uid})
		if err != nil {
			return nil, errors.Wrapf(err, "failed to refresh issue")
		}

		// For ACCESS_GRANT/ROLE_GRANT that is auto-approved (no approval template), complete it.
		approved, err := utils.CheckApprovalApproved(issue.Payload.Approval)
		if err != nil {
			return nil, errors.Wrapf(err, "failed to check if approval is approved")
		}
		if !approved {
			return issue, nil
		}
		issue, err = completeAccessRequestIssue(ctx, stores, creatorEmail, issue)
		if err != nil {
			return nil, errors.Wrapf(err, "failed to complete role grant")
		}
	case storepb.Issue_DATABASE_CHANGE:
		b.ApprovalCheckChan <- bus.IssueRef{ProjectID: issue.ProjectID, UID: issue.UID}
	default:
	}

	return issue, nil
}

func recordReviewSubmission(ctx context.Context, stores *store.Store, creatorEmail string, issue *store.IssueMessage) {
	if _, err := stores.CreateIssueComments(ctx, creatorEmail, &store.IssueCommentMessage{
		ProjectID: issue.ProjectID,
		IssueUID:  issue.UID,
		Payload: &storepb.IssueCommentPayload{
			Event: &storepb.IssueCommentPayload_ReviewSubmission_{
				ReviewSubmission: &storepb.IssueCommentPayload_ReviewSubmission{},
			},
		},
	}); err != nil {
		slog.Warn("failed to create review submission activity",
			slog.String("project", issue.ProjectID), slog.Int64("issue_uid", issue.UID), log.BBError(err))
	}
}

func emitIssueCreated(ctx context.Context, webhookManager *webhook.Manager, project *store.ProjectMessage, creatorName, creatorEmail string, issue *store.IssueMessage) {
	webhookManager.CreateEvent(ctx, &webhook.Event{
		Type:    storepb.Activity_ISSUE_CREATED,
		Project: webhook.NewProject(project),
		IssueCreated: &webhook.EventIssueCreated{
			Creator: &webhook.User{
				Name:  creatorName,
				Email: creatorEmail,
			},
			Issue: webhook.NewIssue(issue),
		},
	})
}

// completeAccessRequestIssue completes the ACCESS_GRANT/ROLE_GRANT issue.
// For ROLE_GRANT issue: grant the privilege and update the status.
// For ACCESS_GRANT issue: mark the status as ACTIVE.
func completeAccessRequestIssue(ctx context.Context, stores *store.Store, userEmail string, issue *store.IssueMessage) (*store.IssueMessage, error) {
	switch issue.Type {
	case storepb.Issue_ACCESS_GRANT:
		if issue.Payload.AccessGrantId == "" {
			return nil, errors.Errorf("invalid access grant id for issue %d", issue.UID)
		}
		accessGrantName := common.FormatAccessGrant(issue.ProjectID, issue.Payload.AccessGrantId)
		if _, err := activateAccessGrant(ctx, stores, accessGrantName, true /* refresh expire time */); err != nil {
			return nil, errors.Wrapf(err, "failed to activate access grant %v", accessGrantName)
		}
	case storepb.Issue_ROLE_GRANT:
		if err := utils.UpdateProjectPolicyFromRoleGrantIssue(ctx, stores, common.GetWorkspaceIDFromContext(ctx), issue, issue.Payload.RoleGrant); err != nil {
			return nil, err
		}
	default:
		return issue, nil
	}

	updatedIssue, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{Status: new(storepb.Issue_DONE)})
	if err != nil {
		return nil, errors.Wrapf(err, "failed to update issue %q's status", issue.Title)
	}

	if _, err := stores.CreateIssueComments(ctx, userEmail, &store.IssueCommentMessage{
		ProjectID: issue.ProjectID,
		IssueUID:  issue.UID,
		Payload: &storepb.IssueCommentPayload{
			Event: &storepb.IssueCommentPayload_IssueUpdate_{
				IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{
					FromStatus: &issue.Status,
					ToStatus:   &updatedIssue.Status,
				},
			},
		},
	}); err != nil {
		slog.Warn("failed to create issue comment after changing the issue status", log.BBError(err))
	}

	return updatedIssue, nil
}