You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hook_pre_receive.go 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package private
  4. import (
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "code.gitea.io/gitea/models"
  9. asymkey_model "code.gitea.io/gitea/models/asymkey"
  10. git_model "code.gitea.io/gitea/models/git"
  11. issues_model "code.gitea.io/gitea/models/issues"
  12. perm_model "code.gitea.io/gitea/models/perm"
  13. access_model "code.gitea.io/gitea/models/perm/access"
  14. "code.gitea.io/gitea/models/unit"
  15. user_model "code.gitea.io/gitea/models/user"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/private"
  19. "code.gitea.io/gitea/modules/web"
  20. gitea_context "code.gitea.io/gitea/services/context"
  21. pull_service "code.gitea.io/gitea/services/pull"
  22. )
  23. type preReceiveContext struct {
  24. *gitea_context.PrivateContext
  25. // loadedPusher indicates that where the following information are loaded
  26. loadedPusher bool
  27. user *user_model.User // it's the org user if a DeployKey is used
  28. userPerm access_model.Permission
  29. deployKeyAccessMode perm_model.AccessMode
  30. canCreatePullRequest bool
  31. checkedCanCreatePullRequest bool
  32. canWriteCode bool
  33. checkedCanWriteCode bool
  34. protectedTags []*git_model.ProtectedTag
  35. gotProtectedTags bool
  36. env []string
  37. opts *private.HookOptions
  38. branchName string
  39. }
  40. // CanWriteCode returns true if pusher can write code
  41. func (ctx *preReceiveContext) CanWriteCode() bool {
  42. if !ctx.checkedCanWriteCode {
  43. if !ctx.loadPusherAndPermission() {
  44. return false
  45. }
  46. ctx.canWriteCode = issues_model.CanMaintainerWriteToBranch(ctx, ctx.userPerm, ctx.branchName, ctx.user) || ctx.deployKeyAccessMode >= perm_model.AccessModeWrite
  47. ctx.checkedCanWriteCode = true
  48. }
  49. return ctx.canWriteCode
  50. }
  51. // AssertCanWriteCode returns true if pusher can write code
  52. func (ctx *preReceiveContext) AssertCanWriteCode() bool {
  53. if !ctx.CanWriteCode() {
  54. if ctx.Written() {
  55. return false
  56. }
  57. ctx.JSON(http.StatusForbidden, private.Response{
  58. UserMsg: "User permission denied for writing.",
  59. })
  60. return false
  61. }
  62. return true
  63. }
  64. // CanCreatePullRequest returns true if pusher can create pull requests
  65. func (ctx *preReceiveContext) CanCreatePullRequest() bool {
  66. if !ctx.checkedCanCreatePullRequest {
  67. if !ctx.loadPusherAndPermission() {
  68. return false
  69. }
  70. ctx.canCreatePullRequest = ctx.userPerm.CanRead(unit.TypePullRequests)
  71. ctx.checkedCanCreatePullRequest = true
  72. }
  73. return ctx.canCreatePullRequest
  74. }
  75. // AssertCreatePullRequest returns true if can create pull requests
  76. func (ctx *preReceiveContext) AssertCreatePullRequest() bool {
  77. if !ctx.CanCreatePullRequest() {
  78. if ctx.Written() {
  79. return false
  80. }
  81. ctx.JSON(http.StatusForbidden, private.Response{
  82. UserMsg: "User permission denied for creating pull-request.",
  83. })
  84. return false
  85. }
  86. return true
  87. }
  88. // HookPreReceive checks whether a individual commit is acceptable
  89. func HookPreReceive(ctx *gitea_context.PrivateContext) {
  90. opts := web.GetForm(ctx).(*private.HookOptions)
  91. ourCtx := &preReceiveContext{
  92. PrivateContext: ctx,
  93. env: generateGitEnv(opts), // Generate git environment for checking commits
  94. opts: opts,
  95. }
  96. // Iterate across the provided old commit IDs
  97. for i := range opts.OldCommitIDs {
  98. oldCommitID := opts.OldCommitIDs[i]
  99. newCommitID := opts.NewCommitIDs[i]
  100. refFullName := opts.RefFullNames[i]
  101. switch {
  102. case refFullName.IsBranch():
  103. preReceiveBranch(ourCtx, oldCommitID, newCommitID, refFullName)
  104. case refFullName.IsTag():
  105. preReceiveTag(ourCtx, oldCommitID, newCommitID, refFullName)
  106. case git.DefaultFeatures.SupportProcReceive && refFullName.IsFor():
  107. preReceiveFor(ourCtx, oldCommitID, newCommitID, refFullName)
  108. default:
  109. ourCtx.AssertCanWriteCode()
  110. }
  111. if ctx.Written() {
  112. return
  113. }
  114. }
  115. ctx.PlainText(http.StatusOK, "ok")
  116. }
  117. func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID string, refFullName git.RefName) {
  118. branchName := refFullName.BranchName()
  119. ctx.branchName = branchName
  120. if !ctx.AssertCanWriteCode() {
  121. return
  122. }
  123. repo := ctx.Repo.Repository
  124. gitRepo := ctx.Repo.GitRepo
  125. objectFormat := ctx.Repo.GetObjectFormat()
  126. if branchName == repo.DefaultBranch && newCommitID == objectFormat.EmptyObjectID().String() {
  127. log.Warn("Forbidden: Branch: %s is the default branch in %-v and cannot be deleted", branchName, repo)
  128. ctx.JSON(http.StatusForbidden, private.Response{
  129. UserMsg: fmt.Sprintf("branch %s is the default branch and cannot be deleted", branchName),
  130. })
  131. return
  132. }
  133. protectBranch, err := git_model.GetFirstMatchProtectedBranchRule(ctx, repo.ID, branchName)
  134. if err != nil {
  135. log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
  136. ctx.JSON(http.StatusInternalServerError, private.Response{
  137. Err: err.Error(),
  138. })
  139. return
  140. }
  141. // Allow pushes to non-protected branches
  142. if protectBranch == nil {
  143. return
  144. }
  145. protectBranch.Repo = repo
  146. // This ref is a protected branch.
  147. //
  148. // First of all we need to enforce absolutely:
  149. //
  150. // 1. Detect and prevent deletion of the branch
  151. if newCommitID == objectFormat.EmptyObjectID().String() {
  152. log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo)
  153. ctx.JSON(http.StatusForbidden, private.Response{
  154. UserMsg: fmt.Sprintf("branch %s is protected from deletion", branchName),
  155. })
  156. return
  157. }
  158. // 2. Disallow force pushes to protected branches
  159. if oldCommitID != objectFormat.EmptyObjectID().String() {
  160. output, _, err := git.NewCommand(ctx, "rev-list", "--max-count=1").AddDynamicArguments(oldCommitID, "^"+newCommitID).RunStdString(&git.RunOpts{Dir: repo.RepoPath(), Env: ctx.env})
  161. if err != nil {
  162. log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
  163. ctx.JSON(http.StatusInternalServerError, private.Response{
  164. Err: fmt.Sprintf("Fail to detect force push: %v", err),
  165. })
  166. return
  167. } else if len(output) > 0 {
  168. log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo)
  169. ctx.JSON(http.StatusForbidden, private.Response{
  170. UserMsg: fmt.Sprintf("branch %s is protected from force push", branchName),
  171. })
  172. return
  173. }
  174. }
  175. // 3. Enforce require signed commits
  176. if protectBranch.RequireSignedCommits {
  177. err := verifyCommits(oldCommitID, newCommitID, gitRepo, ctx.env)
  178. if err != nil {
  179. if !isErrUnverifiedCommit(err) {
  180. log.Error("Unable to check commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  181. ctx.JSON(http.StatusInternalServerError, private.Response{
  182. Err: fmt.Sprintf("Unable to check commits from %s to %s: %v", oldCommitID, newCommitID, err),
  183. })
  184. return
  185. }
  186. unverifiedCommit := err.(*errUnverifiedCommit).sha
  187. log.Warn("Forbidden: Branch: %s in %-v is protected from unverified commit %s", branchName, repo, unverifiedCommit)
  188. ctx.JSON(http.StatusForbidden, private.Response{
  189. UserMsg: fmt.Sprintf("branch %s is protected from unverified commit %s", branchName, unverifiedCommit),
  190. })
  191. return
  192. }
  193. }
  194. // Now there are several tests which can be overridden:
  195. //
  196. // 4. Check protected file patterns - this is overridable from the UI
  197. changedProtectedfiles := false
  198. protectedFilePath := ""
  199. globs := protectBranch.GetProtectedFilePatterns()
  200. if len(globs) > 0 {
  201. _, err := pull_service.CheckFileProtection(gitRepo, oldCommitID, newCommitID, globs, 1, ctx.env)
  202. if err != nil {
  203. if !models.IsErrFilePathProtected(err) {
  204. log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  205. ctx.JSON(http.StatusInternalServerError, private.Response{
  206. Err: fmt.Sprintf("Unable to check file protection for commits from %s to %s: %v", oldCommitID, newCommitID, err),
  207. })
  208. return
  209. }
  210. changedProtectedfiles = true
  211. protectedFilePath = err.(models.ErrFilePathProtected).Path
  212. }
  213. }
  214. // 5. Check if the doer is allowed to push
  215. var canPush bool
  216. if ctx.opts.DeployKeyID != 0 {
  217. canPush = !changedProtectedfiles && protectBranch.CanPush && (!protectBranch.EnableWhitelist || protectBranch.WhitelistDeployKeys)
  218. } else {
  219. user, err := user_model.GetUserByID(ctx, ctx.opts.UserID)
  220. if err != nil {
  221. log.Error("Unable to GetUserByID for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  222. ctx.JSON(http.StatusInternalServerError, private.Response{
  223. Err: fmt.Sprintf("Unable to GetUserByID for commits from %s to %s: %v", oldCommitID, newCommitID, err),
  224. })
  225. return
  226. }
  227. canPush = !changedProtectedfiles && protectBranch.CanUserPush(ctx, user)
  228. }
  229. // 6. If we're not allowed to push directly
  230. if !canPush {
  231. // Is this is a merge from the UI/API?
  232. if ctx.opts.PullRequestID == 0 {
  233. // 6a. If we're not merging from the UI/API then there are two ways we got here:
  234. //
  235. // We are changing a protected file and we're not allowed to do that
  236. if changedProtectedfiles {
  237. log.Warn("Forbidden: Branch: %s in %-v is protected from changing file %s", branchName, repo, protectedFilePath)
  238. ctx.JSON(http.StatusForbidden, private.Response{
  239. UserMsg: fmt.Sprintf("branch %s is protected from changing file %s", branchName, protectedFilePath),
  240. })
  241. return
  242. }
  243. // Allow commits that only touch unprotected files
  244. globs := protectBranch.GetUnprotectedFilePatterns()
  245. if len(globs) > 0 {
  246. unprotectedFilesOnly, err := pull_service.CheckUnprotectedFiles(gitRepo, oldCommitID, newCommitID, globs, ctx.env)
  247. if err != nil {
  248. log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  249. ctx.JSON(http.StatusInternalServerError, private.Response{
  250. Err: fmt.Sprintf("Unable to check file protection for commits from %s to %s: %v", oldCommitID, newCommitID, err),
  251. })
  252. return
  253. }
  254. if unprotectedFilesOnly {
  255. // Commit only touches unprotected files, this is allowed
  256. return
  257. }
  258. }
  259. // Or we're simply not able to push to this protected branch
  260. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", ctx.opts.UserID, branchName, repo)
  261. ctx.JSON(http.StatusForbidden, private.Response{
  262. UserMsg: fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  263. })
  264. return
  265. }
  266. // 6b. Merge (from UI or API)
  267. // Get the PR, user and permissions for the user in the repository
  268. pr, err := issues_model.GetPullRequestByID(ctx, ctx.opts.PullRequestID)
  269. if err != nil {
  270. log.Error("Unable to get PullRequest %d Error: %v", ctx.opts.PullRequestID, err)
  271. ctx.JSON(http.StatusInternalServerError, private.Response{
  272. Err: fmt.Sprintf("Unable to get PullRequest %d Error: %v", ctx.opts.PullRequestID, err),
  273. })
  274. return
  275. }
  276. // although we should have called `loadPusherAndPermission` before, here we call it explicitly again because we need to access ctx.user below
  277. if !ctx.loadPusherAndPermission() {
  278. // if error occurs, loadPusherAndPermission had written the error response
  279. return
  280. }
  281. // Now check if the user is allowed to merge PRs for this repository
  282. // Note: we can use ctx.perm and ctx.user directly as they will have been loaded above
  283. allowedMerge, err := pull_service.IsUserAllowedToMerge(ctx, pr, ctx.userPerm, ctx.user)
  284. if err != nil {
  285. log.Error("Error calculating if allowed to merge: %v", err)
  286. ctx.JSON(http.StatusInternalServerError, private.Response{
  287. Err: fmt.Sprintf("Error calculating if allowed to merge: %v", err),
  288. })
  289. return
  290. }
  291. if !allowedMerge {
  292. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v and is not allowed to merge pr #%d", ctx.opts.UserID, branchName, repo, pr.Index)
  293. ctx.JSON(http.StatusForbidden, private.Response{
  294. UserMsg: fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  295. })
  296. return
  297. }
  298. // If we're an admin for the repository we can ignore status checks, reviews and override protected files
  299. if ctx.userPerm.IsAdmin() {
  300. return
  301. }
  302. // Now if we're not an admin - we can't overwrite protected files so fail now
  303. if changedProtectedfiles {
  304. log.Warn("Forbidden: Branch: %s in %-v is protected from changing file %s", branchName, repo, protectedFilePath)
  305. ctx.JSON(http.StatusForbidden, private.Response{
  306. UserMsg: fmt.Sprintf("branch %s is protected from changing file %s", branchName, protectedFilePath),
  307. })
  308. return
  309. }
  310. // Check all status checks and reviews are ok
  311. if err := pull_service.CheckPullBranchProtections(ctx, pr, true); err != nil {
  312. if models.IsErrDisallowedToMerge(err) {
  313. log.Warn("Forbidden: User %d is not allowed push to protected branch %s in %-v and pr #%d is not ready to be merged: %s", ctx.opts.UserID, branchName, repo, pr.Index, err.Error())
  314. ctx.JSON(http.StatusForbidden, private.Response{
  315. UserMsg: fmt.Sprintf("Not allowed to push to protected branch %s and pr #%d is not ready to be merged: %s", branchName, ctx.opts.PullRequestID, err.Error()),
  316. })
  317. return
  318. }
  319. log.Error("Unable to check if mergable: protected branch %s in %-v and pr #%d. Error: %v", ctx.opts.UserID, branchName, repo, pr.Index, err)
  320. ctx.JSON(http.StatusInternalServerError, private.Response{
  321. Err: fmt.Sprintf("Unable to get status of pull request %d. Error: %v", ctx.opts.PullRequestID, err),
  322. })
  323. return
  324. }
  325. }
  326. }
  327. func preReceiveTag(ctx *preReceiveContext, oldCommitID, newCommitID string, refFullName git.RefName) {
  328. if !ctx.AssertCanWriteCode() {
  329. return
  330. }
  331. tagName := refFullName.TagName()
  332. if !ctx.gotProtectedTags {
  333. var err error
  334. ctx.protectedTags, err = git_model.GetProtectedTags(ctx, ctx.Repo.Repository.ID)
  335. if err != nil {
  336. log.Error("Unable to get protected tags for %-v Error: %v", ctx.Repo.Repository, err)
  337. ctx.JSON(http.StatusInternalServerError, private.Response{
  338. Err: err.Error(),
  339. })
  340. return
  341. }
  342. ctx.gotProtectedTags = true
  343. }
  344. isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, ctx.protectedTags, tagName, ctx.opts.UserID)
  345. if err != nil {
  346. ctx.JSON(http.StatusInternalServerError, private.Response{
  347. Err: err.Error(),
  348. })
  349. return
  350. }
  351. if !isAllowed {
  352. log.Warn("Forbidden: Tag %s in %-v is protected", tagName, ctx.Repo.Repository)
  353. ctx.JSON(http.StatusForbidden, private.Response{
  354. UserMsg: fmt.Sprintf("Tag %s is protected", tagName),
  355. })
  356. return
  357. }
  358. }
  359. func preReceiveFor(ctx *preReceiveContext, oldCommitID, newCommitID string, refFullName git.RefName) {
  360. if !ctx.AssertCreatePullRequest() {
  361. return
  362. }
  363. if ctx.Repo.Repository.IsEmpty {
  364. ctx.JSON(http.StatusForbidden, private.Response{
  365. UserMsg: "Can't create pull request for an empty repository.",
  366. })
  367. return
  368. }
  369. if ctx.opts.IsWiki {
  370. ctx.JSON(http.StatusForbidden, private.Response{
  371. UserMsg: "Pull requests are not supported on the wiki.",
  372. })
  373. return
  374. }
  375. baseBranchName := refFullName.ForBranchName()
  376. baseBranchExist := false
  377. if ctx.Repo.GitRepo.IsBranchExist(baseBranchName) {
  378. baseBranchExist = true
  379. }
  380. if !baseBranchExist {
  381. for p, v := range baseBranchName {
  382. if v == '/' && ctx.Repo.GitRepo.IsBranchExist(baseBranchName[:p]) && p != len(baseBranchName)-1 {
  383. baseBranchExist = true
  384. break
  385. }
  386. }
  387. }
  388. if !baseBranchExist {
  389. ctx.JSON(http.StatusForbidden, private.Response{
  390. UserMsg: fmt.Sprintf("Unexpected ref: %s", refFullName),
  391. })
  392. return
  393. }
  394. }
  395. func generateGitEnv(opts *private.HookOptions) (env []string) {
  396. env = os.Environ()
  397. if opts.GitAlternativeObjectDirectories != "" {
  398. env = append(env,
  399. private.GitAlternativeObjectDirectories+"="+opts.GitAlternativeObjectDirectories)
  400. }
  401. if opts.GitObjectDirectory != "" {
  402. env = append(env,
  403. private.GitObjectDirectory+"="+opts.GitObjectDirectory)
  404. }
  405. if opts.GitQuarantinePath != "" {
  406. env = append(env,
  407. private.GitQuarantinePath+"="+opts.GitQuarantinePath)
  408. }
  409. return env
  410. }
  411. // loadPusherAndPermission returns false if an error occurs, and it writes the error response
  412. func (ctx *preReceiveContext) loadPusherAndPermission() bool {
  413. if ctx.loadedPusher {
  414. return true
  415. }
  416. if ctx.opts.UserID == user_model.ActionsUserID {
  417. ctx.user = user_model.NewActionsUser()
  418. ctx.userPerm.AccessMode = perm_model.AccessMode(ctx.opts.ActionPerm)
  419. if err := ctx.Repo.Repository.LoadUnits(ctx); err != nil {
  420. log.Error("Unable to get User id %d Error: %v", ctx.opts.UserID, err)
  421. ctx.JSON(http.StatusInternalServerError, private.Response{
  422. Err: fmt.Sprintf("Unable to get User id %d Error: %v", ctx.opts.UserID, err),
  423. })
  424. return false
  425. }
  426. ctx.userPerm.SetUnitsWithDefaultAccessMode(ctx.Repo.Repository.Units, ctx.userPerm.AccessMode)
  427. } else {
  428. user, err := user_model.GetUserByID(ctx, ctx.opts.UserID)
  429. if err != nil {
  430. log.Error("Unable to get User id %d Error: %v", ctx.opts.UserID, err)
  431. ctx.JSON(http.StatusInternalServerError, private.Response{
  432. Err: fmt.Sprintf("Unable to get User id %d Error: %v", ctx.opts.UserID, err),
  433. })
  434. return false
  435. }
  436. ctx.user = user
  437. userPerm, err := access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, user)
  438. if err != nil {
  439. log.Error("Unable to get Repo permission of repo %s/%s of User %s: %v", ctx.Repo.Repository.OwnerName, ctx.Repo.Repository.Name, user.Name, err)
  440. ctx.JSON(http.StatusInternalServerError, private.Response{
  441. Err: fmt.Sprintf("Unable to get Repo permission of repo %s/%s of User %s: %v", ctx.Repo.Repository.OwnerName, ctx.Repo.Repository.Name, user.Name, err),
  442. })
  443. return false
  444. }
  445. ctx.userPerm = userPerm
  446. }
  447. if ctx.opts.DeployKeyID != 0 {
  448. deployKey, err := asymkey_model.GetDeployKeyByID(ctx, ctx.opts.DeployKeyID)
  449. if err != nil {
  450. log.Error("Unable to get DeployKey id %d Error: %v", ctx.opts.DeployKeyID, err)
  451. ctx.JSON(http.StatusInternalServerError, private.Response{
  452. Err: fmt.Sprintf("Unable to get DeployKey id %d Error: %v", ctx.opts.DeployKeyID, err),
  453. })
  454. return false
  455. }
  456. ctx.deployKeyAccessMode = deployKey.Mode
  457. }
  458. ctx.loadedPusher = true
  459. return true
  460. }