Skip to content

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

fix(azure, devops): get pull request id and get commit list if commits is empty in code push (#7391)

h3n4l868a929f63bd
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index c6d7f4df2f..69a569c694 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -705,7 +705,7 @@ func (p *Provider) getLatestCommitIDOnBranch(ctx context.Context, oauthCtx commo
// createOrUpdateFile update or create the file.
//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-5.1&tabs=HTTP
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-7.0&tabs=HTTP
func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate, create bool) error {
apiURL, err := getRepositoryAPIURL(repositoryID)
if err != nil {
@@ -1055,7 +1055,7 @@ func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContex
[]*refUpdate{
{
Name: fmt.Sprintf("refs/heads/%s", branch.Name),
- OldObjectID: "0000000000000000000000000000000000000000",
+ OldObjectID: strings.Repeat("0", 40),
NewObjectID: branch.LastCommitID,
},
},
@@ -1403,6 +1403,157 @@ func GetPushCommitsByPushID(ctx context.Context, oauthCtx common.OauthContext, r
return r, nil
}
+// PullRequest is the pull request.
+type PullRequest struct {
+ ID uint64 `json:"pullRequestId"`
+ Status string `json:"status"`
+ TargetRefName string `json:"targetRefName"`
+}
+
+// QueryPullRequest queries the pull request by the last merge commit.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-query/get?view=azure-devops-rest-7.0#gitpullrequestqueryinput
+func QueryPullRequest(ctx context.Context, oauthCtx common.OauthContext, repositoryID string, lastMergeCommit string) ([]*PullRequest, error) {
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
+ }
+
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+
+ url := fmt.Sprintf("%s/pullrequestquery?%s", apiURL, values.Encode())
+
+ client := &http.Client{}
+ type pullRequestQueryInputQuery struct {
+ Item []string `json:"items"`
+ Type string `json:"type"`
+ }
+
+ type pullRequestQueryInput struct {
+ Queries []pullRequestQueryInputQuery `json:"queries"`
+ }
+
+ b := pullRequestQueryInput{
+ Queries: []pullRequestQueryInputQuery{
+ {
+ Item: []string{
+ lastMergeCommit,
+ },
+ Type: "lastMergeCommit",
+ },
+ },
+ }
+
+ marshalBody, err := json.Marshal(b)
+ if err != nil {
+ return nil, errors.Wrap(err, "marshal pull request query input")
+ }
+
+ code, _, body, err := oauth.Post(ctx, client, url, &oauthCtx.AccessToken, bytes.NewReader(marshalBody), tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ oauthCtx.Refresher,
+ ))
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to query pull request")
+ }
+
+ if code != http.StatusCreated {
+ return nil, errors.Errorf("failed to query pull request, code: %v, body: %s", code, string(body))
+ }
+
+ type pullRequestQueryResponseMapElem struct {
+ ID uint64 `json:"pullRequestId"`
+ Status string `json:"status"`
+ TargetRefName string `json:"targetRefName"`
+ }
+ type pullRequestQueryResponseResult map[string][]pullRequestQueryResponseMapElem
+
+ type pullRequestQueryResponse struct {
+ Results []pullRequestQueryResponseResult `json:"results"`
+ }
+
+ r := new(pullRequestQueryResponse)
+ if err := json.Unmarshal([]byte(body), r); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal query pull request response body, code %v", code)
+ }
+
+ if len(r.Results) == 0 {
+ return nil, nil
+ }
+ if len(r.Results) != 1 {
+ return nil, errors.Errorf("expected one result, but got %d, body: %v", len(r.Results), string(body))
+ }
+ if len(r.Results[0]) != 1 {
+ return nil, errors.Errorf("expected one element in result, but got %d, body: %v", len(r.Results[0]), string(body))
+ }
+
+ var result []*PullRequest
+ for _, item := range r.Results[0] {
+ for _, elem := range item {
+ result = append(result, &PullRequest{
+ ID: elem.ID,
+ Status: elem.Status,
+ TargetRefName: elem.TargetRefName,
+ })
+ }
+ }
+
+ return result, nil
+}
+
+// GetPullRequestCommits gets the commits in the pull request.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-commits/get-pull-request-commits?view=azure-devops-rest-7.0
+func GetPullRequestCommits(ctx context.Context, oauthCtx common.OauthContext, repositoryID string, pullRequestID uint64) ([]ServiceHookCodePushEventResourceCommit, error) {
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
+ }
+
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+ url := fmt.Sprintf("%s/pullRequests/%d/commits?%s", apiURL, pullRequestID, values.Encode())
+
+ client := &http.Client{}
+
+ code, _, resp, err := oauth.Get(
+ ctx,
+ client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "GET %s", url)
+ }
+ if code != http.StatusOK {
+ return nil, errors.Errorf("failed to get pull request commits, code: %v, body: %s", code, string(resp))
+ }
+
+ type pullRequestCommitsResponse struct {
+ Value []ServiceHookCodePushEventResourceCommit `json:"value"`
+ }
+
+ r := new(pullRequestCommitsResponse)
+ if err := json.Unmarshal([]byte(resp), r); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal get pull request commits response body, code %v", code)
+ }
+
+ return r.Value, nil
+}
+
// oauthContext is the request context for OAuth.
type oauthContext struct {
ClientSecret string
diff --git a/backend/server/webhook.go b/backend/server/webhook.go
index c5b355c2e4..996ec0f560 100644
--- a/backend/server/webhook.go
+++ b/backend/server/webhook.go
@@ -336,23 +336,19 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)
}
- // Valite presumptions.
+ // Validate presumptions.
// This shouldn't happen as we only setup webhook to receive push event, just in case.
if pushEvent.EventType != "git.push" {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %s, want git.push", pushEvent.EventType))
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Presumption failed: invalid webhook event type, got %s, want git.push", pushEvent.EventType))
}
// All the examples on https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#code-pushed
// have only one ref update.
if len(pushEvent.Resource.RefUpdates) != 1 {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Presumption failed: the number of ref updates is not 1, got %d", len(pushEvent.Resource.RefUpdates)))
}
- // For Azure DevOps, if users create a new branch and push it to the remote. It will trigger a code push event,
- // but do not contain any commits in the event. So we do not need to consider the case that the commit id is
- // all zero.
- for _, commit := range pushEvent.Resource.Commits {
- if commit.CommitID == strings.Repeat("0", 40) {
- return echo.NewHTTPError(http.StatusBadRequest, "Presumption failed: the commit id is all zero")
- }
+ if pushEvent.Resource.RefUpdates[0].NewObjectID == strings.Repeat("0", 40) {
+ // Users delete branch will trigger a push event, but the refUpdates.NewObjectID is all zero.
+ return c.String(http.StatusOK, "Do not process the push event which is generated by deleting branch")
}
webhookEndpointID := c.Param("id")
@@ -375,33 +371,10 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
repositoryID := repositories[0].ExternalID
- // Filter out all the commits created by Bytebase(e.g. write-back the latest schema) to avoid infinite loop.
- nonBytebaseCommitList := filterAzureBytebaseCommit(pushEvent.Resource.Commits)
- if len(nonBytebaseCommitList) == 0 {
- var commitIDs []string
- for _, commit := range pushEvent.Resource.Commits {
- commitIDs = append(commitIDs, commit.CommitID)
- }
- log.Debug("all commits are created by Bytebase",
- zap.String("repoURL", pushEvent.Resource.Repository.URL),
- zap.String("repoID", repositoryID),
- zap.String("repoName", pushEvent.Resource.Repository.Name),
- zap.String("commits", strings.Join(commitIDs, ", ")),
- )
- return c.String(http.StatusOK, "OK")
- }
- pushEvent.Resource.Commits = nonBytebaseCommitList
-
// Filter out the repository which does not match the branch filter.
filter := func(repo *store.RepositoryMessage) (bool, error) {
- refUpdates := pushEvent.Resource.RefUpdates
- for _, refUpdate := range refUpdates {
- trimmed := strings.TrimPrefix(refUpdate.Name, "refs/heads/")
- if trimmed == repo.BranchFilter {
- return true, nil
- }
- }
- return false, nil
+ refUpdate := pushEvent.Resource.RefUpdates[0]
+ return s.isWebhookEventBranch(refUpdate.Name, repo.BranchFilter)
}
repositoryList, err := s.filterRepository(ctx, c.Param("id"), repositoryID, filter)
if err != nil {
@@ -417,6 +390,85 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find workspace setting").SetInternal(err)
}
+ if len(pushEvent.Resource.Commits) == 0 {
+ // If users merge one branch to our target branch, the commits list is empty in push event.
+ // And we cannot get the commits in range [refUpdates.oldObjectId, refUpdates.newObjectId] from Azure DevOps API.
+ // So, when the commit list is empty, we think it is generated by merge,
+ // then we need to query the queryPullRequest API to find out if the updateRef.newObjectId
+ // is the last commit of the Pull Request, and then we can use the PullRef.newObjectId API
+ // to find out if it is the last commit of the Pull Request. Request ID to list the corresponding commits.
+ probablePullRequests, err := azure.QueryPullRequest(ctx, common.OauthContext{
+ ClientID: repositoryList[0].vcs.ApplicationID,
+ ClientSecret: repositoryList[0].vcs.Secret,
+ AccessToken: repositoryList[0].repository.AccessToken,
+ RefreshToken: repositoryList[0].repository.RefreshToken,
+ Refresher: utils.RefreshToken(ctx, s.store, repositoryList[0].repository.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
+ }, repositoryList[0].repository.ExternalID, pushEvent.Resource.RefUpdates[0].NewObjectID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to query pull request").SetInternal(err)
+ }
+ var filterOutPullRequestList []*azure.PullRequest
+ for _, pullRequest := range probablePullRequests {
+ if pullRequest.Status != "completed" {
+ continue
+ }
+ // We only handle the pull request which is merged to the target branch.
+ // NOTE: here we should compare with the refUpdates.Name instead of the repository.BranchFilter
+ if pullRequest.TargetRefName != pushEvent.Resource.RefUpdates[0].Name {
+ continue
+ }
+ filterOutPullRequestList = append(filterOutPullRequestList, pullRequest)
+ }
+
+ if len(filterOutPullRequestList) == 0 {
+ return echo.NewHTTPError(http.StatusOK, "No pull request matched")
+ }
+ if len(filterOutPullRequestList) != 1 {
+ return echo.NewHTTPError(http.StatusInternalServerError, errors.Errorf("Expected only one pull request, but got %d, content: %+v", len(filterOutPullRequestList), filterOutPullRequestList).Error())
+ }
+ // We should backfill the commit list by the commits in the pull request.
+ pullRequest := filterOutPullRequestList[0]
+ commitsInPullRequest, err := azure.GetPullRequestCommits(ctx, common.OauthContext{
+ ClientID: repositoryList[0].vcs.ApplicationID,
+ ClientSecret: repositoryList[0].vcs.Secret,
+ AccessToken: repositoryList[0].repository.AccessToken,
+ RefreshToken: repositoryList[0].repository.RefreshToken,
+ Refresher: utils.RefreshToken(ctx, s.store, repositoryList[0].repository.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
+ }, repositoryList[0].repository.ExternalID, pullRequest.ID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get pull request commits").SetInternal(err)
+ }
+ pushEvent.Resource.Commits = commitsInPullRequest
+ }
+
+ // For Azure DevOps, if users create a new branch and push it to the remote. It will trigger a code push event,
+ // but do not contain any commits in the event. So we do not need to consider the case that the commit id is
+ // all zero.
+ for _, commit := range pushEvent.Resource.Commits {
+ if commit.CommitID == strings.Repeat("0", 40) {
+ return echo.NewHTTPError(http.StatusBadRequest, "Presumption failed: the commit id is all zero")
+ }
+ }
+
+ // Filter out all the commits created by Bytebase(e.g. write-back the latest schema) to avoid infinite loop.
+ nonBytebaseCommitList := filterAzureBytebaseCommit(pushEvent.Resource.Commits)
+ if len(nonBytebaseCommitList) == 0 {
+ var commitIDs []string
+ for _, commit := range pushEvent.Resource.Commits {
+ commitIDs = append(commitIDs, commit.CommitID)
+ }
+ log.Debug("all commits are created by Bytebase",
+ zap.String("repoURL", pushEvent.Resource.Repository.URL),
+ zap.String("repoID", repositoryID),
+ zap.String("repoName", pushEvent.Resource.Repository.Name),
+ zap.String("commits", strings.Join(commitIDs, ", ")),
+ )
+ return c.String(http.StatusOK, "OK")
+ }
+ pushEvent.Resource.Commits = nonBytebaseCommitList
+
// Azure DevOps' service hook does not contain the file diff information for each commit, so we need to backfill
// the file diff information by ourselves.
// We will use the previous commit id as the base commit id and the current commit id as the target commit id to