gitea源码

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