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.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // 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.
  5. package private
  6. import (
  7. "bufio"
  8. "context"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "os"
  13. "strings"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/private"
  18. "code.gitea.io/gitea/modules/repofiles"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/util"
  21. pull_service "code.gitea.io/gitea/services/pull"
  22. "gopkg.in/src-d/go-git.v4/plumbing"
  23. "gitea.com/macaron/macaron"
  24. )
  25. func verifyCommits(oldCommitID, newCommitID string, repo *git.Repository, env []string) error {
  26. stdoutReader, stdoutWriter, err := os.Pipe()
  27. if err != nil {
  28. log.Error("Unable to create os.Pipe for %s", repo.Path)
  29. return err
  30. }
  31. defer func() {
  32. _ = stdoutReader.Close()
  33. _ = stdoutWriter.Close()
  34. }()
  35. err = git.NewCommand("rev-list", oldCommitID+"..."+newCommitID).
  36. RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
  37. stdoutWriter, nil, nil,
  38. func(ctx context.Context, cancel context.CancelFunc) error {
  39. _ = stdoutWriter.Close()
  40. err := readAndVerifyCommitsFromShaReader(stdoutReader, repo, env)
  41. if err != nil {
  42. log.Error("%v", err)
  43. cancel()
  44. }
  45. _ = stdoutReader.Close()
  46. return err
  47. })
  48. if err != nil && !isErrUnverifiedCommit(err) {
  49. log.Error("Unable to check commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err)
  50. }
  51. return err
  52. }
  53. func readAndVerifyCommitsFromShaReader(input io.ReadCloser, repo *git.Repository, env []string) error {
  54. scanner := bufio.NewScanner(input)
  55. for scanner.Scan() {
  56. line := scanner.Text()
  57. err := readAndVerifyCommit(line, repo, env)
  58. if err != nil {
  59. log.Error("%v", err)
  60. return err
  61. }
  62. }
  63. return scanner.Err()
  64. }
  65. func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error {
  66. stdoutReader, stdoutWriter, err := os.Pipe()
  67. if err != nil {
  68. log.Error("Unable to create pipe for %s: %v", repo.Path, err)
  69. return err
  70. }
  71. defer func() {
  72. _ = stdoutReader.Close()
  73. _ = stdoutWriter.Close()
  74. }()
  75. hash := plumbing.NewHash(sha)
  76. return git.NewCommand("cat-file", "commit", sha).
  77. RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
  78. stdoutWriter, nil, nil,
  79. func(ctx context.Context, cancel context.CancelFunc) error {
  80. _ = stdoutWriter.Close()
  81. commit, err := git.CommitFromReader(repo, hash, stdoutReader)
  82. if err != nil {
  83. return err
  84. }
  85. verification := models.ParseCommitWithSignature(commit)
  86. if !verification.Verified {
  87. cancel()
  88. return &errUnverifiedCommit{
  89. commit.ID.String(),
  90. }
  91. }
  92. return nil
  93. })
  94. }
  95. type errUnverifiedCommit struct {
  96. sha string
  97. }
  98. func (e *errUnverifiedCommit) Error() string {
  99. return fmt.Sprintf("Unverified commit: %s", e.sha)
  100. }
  101. func isErrUnverifiedCommit(err error) bool {
  102. _, ok := err.(*errUnverifiedCommit)
  103. return ok
  104. }
  105. // HookPreReceive checks whether a individual commit is acceptable
  106. func HookPreReceive(ctx *macaron.Context, opts private.HookOptions) {
  107. ownerName := ctx.Params(":owner")
  108. repoName := ctx.Params(":repo")
  109. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  110. if err != nil {
  111. log.Error("Unable to get repository: %s/%s Error: %v", ownerName, repoName, err)
  112. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  113. "err": err.Error(),
  114. })
  115. return
  116. }
  117. repo.OwnerName = ownerName
  118. gitRepo, err := git.OpenRepository(repo.RepoPath())
  119. if err != nil {
  120. log.Error("Unable to get git repository for: %s/%s Error: %v", ownerName, repoName, err)
  121. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  122. "err": err.Error(),
  123. })
  124. return
  125. }
  126. defer gitRepo.Close()
  127. // Generate git environment for checking commits
  128. env := os.Environ()
  129. if opts.GitAlternativeObjectDirectories != "" {
  130. env = append(env,
  131. private.GitAlternativeObjectDirectories+"="+opts.GitAlternativeObjectDirectories)
  132. }
  133. if opts.GitObjectDirectory != "" {
  134. env = append(env,
  135. private.GitObjectDirectory+"="+opts.GitObjectDirectory)
  136. }
  137. if opts.GitQuarantinePath != "" {
  138. env = append(env,
  139. private.GitQuarantinePath+"="+opts.GitQuarantinePath)
  140. }
  141. for i := range opts.OldCommitIDs {
  142. oldCommitID := opts.OldCommitIDs[i]
  143. newCommitID := opts.NewCommitIDs[i]
  144. refFullName := opts.RefFullNames[i]
  145. branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
  146. protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
  147. if err != nil {
  148. log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
  149. ctx.JSON(500, map[string]interface{}{
  150. "err": err.Error(),
  151. })
  152. return
  153. }
  154. if protectBranch != nil && protectBranch.IsProtected() {
  155. // detect and prevent deletion
  156. if newCommitID == git.EmptySHA {
  157. log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo)
  158. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  159. "err": fmt.Sprintf("branch %s is protected from deletion", branchName),
  160. })
  161. return
  162. }
  163. // detect force push
  164. if git.EmptySHA != oldCommitID {
  165. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), env)
  166. if err != nil {
  167. log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
  168. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  169. "err": fmt.Sprintf("Fail to detect force push: %v", err),
  170. })
  171. return
  172. } else if len(output) > 0 {
  173. log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo)
  174. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  175. "err": fmt.Sprintf("branch %s is protected from force push", branchName),
  176. })
  177. return
  178. }
  179. }
  180. // Require signed commits
  181. if protectBranch.RequireSignedCommits {
  182. err := verifyCommits(oldCommitID, newCommitID, gitRepo, env)
  183. if err != nil {
  184. if !isErrUnverifiedCommit(err) {
  185. log.Error("Unable to check commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  186. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  187. "err": fmt.Sprintf("Unable to check commits from %s to %s: %v", oldCommitID, newCommitID, err),
  188. })
  189. return
  190. }
  191. unverifiedCommit := err.(*errUnverifiedCommit).sha
  192. log.Warn("Forbidden: Branch: %s in %-v is protected from unverified commit %s", branchName, repo, unverifiedCommit)
  193. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  194. "err": fmt.Sprintf("branch %s is protected from unverified commit %s", branchName, unverifiedCommit),
  195. })
  196. return
  197. }
  198. }
  199. canPush := false
  200. if opts.IsDeployKey {
  201. canPush = protectBranch.CanPush && (!protectBranch.EnableWhitelist || protectBranch.WhitelistDeployKeys)
  202. } else {
  203. canPush = protectBranch.CanUserPush(opts.UserID)
  204. }
  205. if !canPush && opts.ProtectedBranchID > 0 {
  206. // Merge (from UI or API)
  207. pr, err := models.GetPullRequestByID(opts.ProtectedBranchID)
  208. if err != nil {
  209. log.Error("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err)
  210. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  211. "err": fmt.Sprintf("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err),
  212. })
  213. return
  214. }
  215. user, err := models.GetUserByID(opts.UserID)
  216. if err != nil {
  217. log.Error("Unable to get User id %d Error: %v", opts.UserID, err)
  218. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  219. "err": fmt.Sprintf("Unable to get User id %d Error: %v", opts.UserID, err),
  220. })
  221. return
  222. }
  223. perm, err := models.GetUserRepoPermission(repo, user)
  224. if err != nil {
  225. log.Error("Unable to get Repo permission of repo %s/%s of User %s", repo.OwnerName, repo.Name, user.Name, err)
  226. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  227. "err": fmt.Sprintf("Unable to get Repo permission of repo %s/%s of User %s: %v", repo.OwnerName, repo.Name, user.Name, err),
  228. })
  229. return
  230. }
  231. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, perm, user)
  232. if err != nil {
  233. log.Error("Error calculating if allowed to merge: %v", err)
  234. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  235. "err": fmt.Sprintf("Error calculating if allowed to merge: %v", err),
  236. })
  237. return
  238. }
  239. if !allowedMerge {
  240. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v and is not allowed to merge pr #%d", opts.UserID, branchName, repo, pr.Index)
  241. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  242. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  243. })
  244. return
  245. }
  246. // Check all status checks and reviews is ok, unless repo admin which can bypass this.
  247. if !perm.IsAdmin() {
  248. if err := pull_service.CheckPRReadyToMerge(pr); err != nil {
  249. if models.IsErrNotAllowedToMerge(err) {
  250. 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", opts.UserID, branchName, repo, pr.Index, err.Error())
  251. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  252. "err": fmt.Sprintf("Not allowed to push to protected branch %s and pr #%d is not ready to be merged: %s", branchName, opts.ProtectedBranchID, err.Error()),
  253. })
  254. return
  255. }
  256. log.Error("Unable to check if mergable: protected branch %s in %-v and pr #%d. Error: %v", opts.UserID, branchName, repo, pr.Index, err)
  257. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  258. "err": fmt.Sprintf("Unable to get status of pull request %d. Error: %v", opts.ProtectedBranchID, err),
  259. })
  260. }
  261. }
  262. } else if !canPush {
  263. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", opts.UserID, branchName, repo)
  264. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  265. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  266. })
  267. return
  268. }
  269. }
  270. }
  271. ctx.PlainText(http.StatusOK, []byte("ok"))
  272. }
  273. // HookPostReceive updates services and users
  274. func HookPostReceive(ctx *macaron.Context, opts private.HookOptions) {
  275. ownerName := ctx.Params(":owner")
  276. repoName := ctx.Params(":repo")
  277. var repo *models.Repository
  278. updates := make([]*repofiles.PushUpdateOptions, 0, len(opts.OldCommitIDs))
  279. wasEmpty := false
  280. for i := range opts.OldCommitIDs {
  281. refFullName := opts.RefFullNames[i]
  282. // Only trigger activity updates for changes to branches or
  283. // tags. Updates to other refs (eg, refs/notes, refs/changes,
  284. // or other less-standard refs spaces are ignored since there
  285. // may be a very large number of them).
  286. if strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
  287. if repo == nil {
  288. var err error
  289. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  290. if err != nil {
  291. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  292. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  293. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  294. })
  295. return
  296. }
  297. if repo.OwnerName == "" {
  298. repo.OwnerName = ownerName
  299. }
  300. wasEmpty = repo.IsEmpty
  301. }
  302. option := repofiles.PushUpdateOptions{
  303. RefFullName: refFullName,
  304. OldCommitID: opts.OldCommitIDs[i],
  305. NewCommitID: opts.NewCommitIDs[i],
  306. PusherID: opts.UserID,
  307. PusherName: opts.UserName,
  308. RepoUserName: ownerName,
  309. RepoName: repoName,
  310. }
  311. updates = append(updates, &option)
  312. if repo.IsEmpty && option.IsBranch() && option.BranchName() == "master" {
  313. // put the master branch first
  314. copy(updates[1:], updates)
  315. updates[0] = &option
  316. }
  317. }
  318. }
  319. if repo != nil && len(updates) > 0 {
  320. if err := repofiles.PushUpdates(repo, updates); err != nil {
  321. log.Error("Failed to Update: %s/%s Total Updates: %d", ownerName, repoName, len(updates))
  322. for i, update := range updates {
  323. log.Error("Failed to Update: %s/%s Update: %d/%d: Branch: %s", ownerName, repoName, i, len(updates), update.BranchName())
  324. }
  325. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  326. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  327. Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
  328. })
  329. return
  330. }
  331. }
  332. results := make([]private.HookPostReceiveBranchResult, 0, len(opts.OldCommitIDs))
  333. // We have to reload the repo in case its state is changed above
  334. repo = nil
  335. var baseRepo *models.Repository
  336. for i := range opts.OldCommitIDs {
  337. refFullName := opts.RefFullNames[i]
  338. newCommitID := opts.NewCommitIDs[i]
  339. branch := git.RefEndName(opts.RefFullNames[i])
  340. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  341. if repo == nil {
  342. var err error
  343. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  344. if err != nil {
  345. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  346. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  347. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  348. RepoWasEmpty: wasEmpty,
  349. })
  350. return
  351. }
  352. if repo.OwnerName == "" {
  353. repo.OwnerName = ownerName
  354. }
  355. if !repo.AllowsPulls() {
  356. // We can stop there's no need to go any further
  357. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  358. RepoWasEmpty: wasEmpty,
  359. })
  360. return
  361. }
  362. baseRepo = repo
  363. if repo.IsFork {
  364. if err := repo.GetBaseRepo(); err != nil {
  365. log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
  366. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  367. Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),
  368. RepoWasEmpty: wasEmpty,
  369. })
  370. return
  371. }
  372. baseRepo = repo.BaseRepo
  373. }
  374. }
  375. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  376. results = append(results, private.HookPostReceiveBranchResult{})
  377. continue
  378. }
  379. pr, err := models.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch)
  380. if err != nil && !models.IsErrPullRequestNotExist(err) {
  381. log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
  382. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  383. Err: fmt.Sprintf(
  384. "Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err),
  385. RepoWasEmpty: wasEmpty,
  386. })
  387. return
  388. }
  389. if pr == nil {
  390. if repo.IsFork {
  391. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  392. }
  393. results = append(results, private.HookPostReceiveBranchResult{
  394. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  395. Create: true,
  396. Branch: branch,
  397. URL: fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
  398. })
  399. } else {
  400. results = append(results, private.HookPostReceiveBranchResult{
  401. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  402. Create: false,
  403. Branch: branch,
  404. URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
  405. })
  406. }
  407. }
  408. }
  409. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  410. Results: results,
  411. RepoWasEmpty: wasEmpty,
  412. })
  413. }
  414. // SetDefaultBranch updates the default branch
  415. func SetDefaultBranch(ctx *macaron.Context) {
  416. ownerName := ctx.Params(":owner")
  417. repoName := ctx.Params(":repo")
  418. branch := ctx.Params(":branch")
  419. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  420. if err != nil {
  421. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  422. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  423. "Err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  424. })
  425. return
  426. }
  427. if repo.OwnerName == "" {
  428. repo.OwnerName = ownerName
  429. }
  430. repo.DefaultBranch = branch
  431. gitRepo, err := git.OpenRepository(repo.RepoPath())
  432. if err != nil {
  433. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  434. "Err": fmt.Sprintf("Failed to get git repository: %s/%s Error: %v", ownerName, repoName, err),
  435. })
  436. return
  437. }
  438. if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  439. if !git.IsErrUnsupportedVersion(err) {
  440. gitRepo.Close()
  441. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  442. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  443. })
  444. return
  445. }
  446. }
  447. gitRepo.Close()
  448. if err := repo.UpdateDefaultBranch(); err != nil {
  449. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  450. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  451. })
  452. return
  453. }
  454. ctx.PlainText(200, []byte("success"))
  455. }