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

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