summaryrefslogtreecommitdiffstats
path: root/routers/private/hook.go
blob: 1071c57bc0753448041e7c369b3270628a82a124 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead.
package private

import (
	"fmt"
	"net/http"
	"os"
	"strings"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/private"
	"code.gitea.io/gitea/modules/repofiles"
	"code.gitea.io/gitea/modules/util"

	macaron "gopkg.in/macaron.v1"
)

// HookPreReceive checks whether a individual commit is acceptable
func HookPreReceive(ctx *macaron.Context) {
	ownerName := ctx.Params(":owner")
	repoName := ctx.Params(":repo")
	oldCommitID := ctx.QueryTrim("old")
	newCommitID := ctx.QueryTrim("new")
	refFullName := ctx.QueryTrim("ref")
	userID := ctx.QueryInt64("userID")
	gitObjectDirectory := ctx.QueryTrim("gitObjectDirectory")
	gitAlternativeObjectDirectories := ctx.QueryTrim("gitAlternativeObjectDirectories")
	prID := ctx.QueryInt64("prID")

	branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
	repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
	if err != nil {
		log.Error("Unable to get repository: %s/%s Error: %v", ownerName, repoName, err)
		ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
			"err": err.Error(),
		})
		return
	}
	repo.OwnerName = ownerName
	protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
	if err != nil {
		log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
		ctx.JSON(500, map[string]interface{}{
			"err": err.Error(),
		})
		return
	}
	if protectBranch != nil && protectBranch.IsProtected() {
		// check and deletion
		if newCommitID == git.EmptySHA {
			log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo)
			ctx.JSON(http.StatusForbidden, map[string]interface{}{
				"err": fmt.Sprintf("branch %s is protected from deletion", branchName),
			})
			return
		}

		// detect force push
		if git.EmptySHA != oldCommitID {
			env := append(os.Environ(),
				private.GitAlternativeObjectDirectories+"="+gitAlternativeObjectDirectories,
				private.GitObjectDirectory+"="+gitObjectDirectory,
				private.GitQuarantinePath+"="+gitObjectDirectory,
			)

			output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), env)
			if err != nil {
				log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
				ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
					"err": fmt.Sprintf("Fail to detect force push: %v", err),
				})
				return
			} else if len(output) > 0 {
				log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo)
				ctx.JSON(http.StatusForbidden, map[string]interface{}{
					"err": fmt.Sprintf("branch %s is protected from force push", branchName),
				})
				return

			}
		}

		canPush := protectBranch.CanUserPush(userID)
		if !canPush && prID > 0 {
			pr, err := models.GetPullRequestByID(prID)
			if err != nil {
				log.Error("Unable to get PullRequest %d Error: %v", prID, err)
				ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
					"err": fmt.Sprintf("Unable to get PullRequest %d Error: %v", prID, err),
				})
				return
			}
			if !protectBranch.HasEnoughApprovals(pr) {
				log.Warn("Forbidden: User %d cannot push to protected branch: %s in %-v and pr #%d does not have enough approvals", userID, branchName, repo, pr.Index)
				ctx.JSON(http.StatusForbidden, map[string]interface{}{
					"err": fmt.Sprintf("protected branch %s can not be pushed to and pr #%d does not have enough approvals", branchName, prID),
				})
				return
			}
		} else if !canPush {
			log.Warn("Forbidden: User %d cannot push to protected branch: %s in %-v", userID, branchName, repo)
			ctx.JSON(http.StatusForbidden, map[string]interface{}{
				"err": fmt.Sprintf("protected branch %s can not be pushed to", branchName),
			})
			return
		}
	}
	ctx.PlainText(http.StatusOK, []byte("ok"))
}

// HookPostReceive updates services and users
func HookPostReceive(ctx *macaron.Context) {
	ownerName := ctx.Params(":owner")
	repoName := ctx.Params(":repo")
	oldCommitID := ctx.Query("old")
	newCommitID := ctx.Query("new")
	refFullName := ctx.Query("ref")
	userID := ctx.QueryInt64("userID")
	userName := ctx.Query("username")

	branch := refFullName
	if strings.HasPrefix(refFullName, git.BranchPrefix) {
		branch = strings.TrimPrefix(refFullName, git.BranchPrefix)
	} else if strings.HasPrefix(refFullName, git.TagPrefix) {
		branch = strings.TrimPrefix(refFullName, git.TagPrefix)
	}

	// Only trigger activity updates for changes to branches or
	// tags.  Updates to other refs (eg, refs/notes, refs/changes,
	// or other less-standard refs spaces are ignored since there
	// may be a very large number of them).
	if strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
		repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
		if err != nil {
			log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
			ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
				"err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
			})
			return
		}
		if err := repofiles.PushUpdate(repo, branch, models.PushUpdateOptions{
			RefFullName:  refFullName,
			OldCommitID:  oldCommitID,
			NewCommitID:  newCommitID,
			PusherID:     userID,
			PusherName:   userName,
			RepoUserName: ownerName,
			RepoName:     repoName,
		}); err != nil {
			log.Error("Failed to Update: %s/%s Branch: %s Error: %v", ownerName, repoName, branch, err)
			ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
				"err": fmt.Sprintf("Failed to Update: %s/%s Branch: %s Error: %v", ownerName, repoName, branch, err),
			})
			return
		}
	}

	if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
		repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
		if err != nil {
			log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
			ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
				"err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
			})
			return
		}
		repo.OwnerName = ownerName

		pullRequestAllowed := repo.AllowsPulls()
		if !pullRequestAllowed {
			ctx.JSON(http.StatusOK, map[string]interface{}{
				"message": false,
			})
			return
		}

		baseRepo := repo
		if repo.IsFork {
			if err := repo.GetBaseRepo(); err != nil {
				log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
				ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
					"err": fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),
				})
				return
			}
			baseRepo = repo.BaseRepo
		}

		if !repo.IsFork && branch == baseRepo.DefaultBranch {
			ctx.JSON(http.StatusOK, map[string]interface{}{
				"message": false,
			})
			return
		}

		pr, err := models.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch)
		if err != nil && !models.IsErrPullRequestNotExist(err) {
			log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
			ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
				"err": fmt.Sprintf(
					"Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err),
			})
			return
		}

		if pr == nil {
			if repo.IsFork {
				branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
			}
			ctx.JSON(http.StatusOK, map[string]interface{}{
				"message": true,
				"create":  true,
				"branch":  branch,
				"url":     fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
			})
		} else {
			ctx.JSON(http.StatusOK, map[string]interface{}{
				"message": true,
				"create":  false,
				"branch":  branch,
				"url":     fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
			})
		}
		return
	}
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"message": false,
	})
}