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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. // Manual merge
  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. // Manual merge only allowed if PR is ready (even if admin)
  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. } else if !canPush {
  262. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", opts.UserID, branchName, repo)
  263. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  264. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  265. })
  266. return
  267. }
  268. }
  269. }
  270. ctx.PlainText(http.StatusOK, []byte("ok"))
  271. }
  272. // HookPostReceive updates services and users
  273. func HookPostReceive(ctx *macaron.Context, opts private.HookOptions) {
  274. ownerName := ctx.Params(":owner")
  275. repoName := ctx.Params(":repo")
  276. var repo *models.Repository
  277. updates := make([]*repofiles.PushUpdateOptions, 0, len(opts.OldCommitIDs))
  278. wasEmpty := false
  279. for i := range opts.OldCommitIDs {
  280. refFullName := opts.RefFullNames[i]
  281. branch := opts.RefFullNames[i]
  282. if strings.HasPrefix(branch, git.BranchPrefix) {
  283. branch = strings.TrimPrefix(branch, git.BranchPrefix)
  284. } else {
  285. branch = strings.TrimPrefix(branch, git.TagPrefix)
  286. }
  287. // Only trigger activity updates for changes to branches or
  288. // tags. Updates to other refs (eg, refs/notes, refs/changes,
  289. // or other less-standard refs spaces are ignored since there
  290. // may be a very large number of them).
  291. if strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
  292. if repo == nil {
  293. var err error
  294. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  295. if err != nil {
  296. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  297. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  298. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  299. })
  300. return
  301. }
  302. if repo.OwnerName == "" {
  303. repo.OwnerName = ownerName
  304. }
  305. wasEmpty = repo.IsEmpty
  306. }
  307. option := repofiles.PushUpdateOptions{
  308. RefFullName: refFullName,
  309. OldCommitID: opts.OldCommitIDs[i],
  310. NewCommitID: opts.NewCommitIDs[i],
  311. Branch: branch,
  312. PusherID: opts.UserID,
  313. PusherName: opts.UserName,
  314. RepoUserName: ownerName,
  315. RepoName: repoName,
  316. }
  317. updates = append(updates, &option)
  318. if repo.IsEmpty && branch == "master" && strings.HasPrefix(refFullName, git.BranchPrefix) {
  319. // put the master branch first
  320. copy(updates[1:], updates)
  321. updates[0] = &option
  322. }
  323. }
  324. }
  325. if repo != nil && len(updates) > 0 {
  326. if err := repofiles.PushUpdates(repo, updates); err != nil {
  327. log.Error("Failed to Update: %s/%s Total Updates: %d", ownerName, repoName, len(updates))
  328. for i, update := range updates {
  329. log.Error("Failed to Update: %s/%s Update: %d/%d: Branch: %s", ownerName, repoName, i, len(updates), update.Branch)
  330. }
  331. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  332. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  333. Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
  334. })
  335. return
  336. }
  337. }
  338. results := make([]private.HookPostReceiveBranchResult, 0, len(opts.OldCommitIDs))
  339. // We have to reload the repo in case its state is changed above
  340. repo = nil
  341. var baseRepo *models.Repository
  342. for i := range opts.OldCommitIDs {
  343. refFullName := opts.RefFullNames[i]
  344. newCommitID := opts.NewCommitIDs[i]
  345. branch := git.RefEndName(opts.RefFullNames[i])
  346. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  347. if repo == nil {
  348. var err error
  349. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  350. if err != nil {
  351. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  352. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  353. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  354. RepoWasEmpty: wasEmpty,
  355. })
  356. return
  357. }
  358. if repo.OwnerName == "" {
  359. repo.OwnerName = ownerName
  360. }
  361. if !repo.AllowsPulls() {
  362. // We can stop there's no need to go any further
  363. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  364. RepoWasEmpty: wasEmpty,
  365. })
  366. return
  367. }
  368. baseRepo = repo
  369. if repo.IsFork {
  370. if err := repo.GetBaseRepo(); err != nil {
  371. log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
  372. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  373. Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),
  374. RepoWasEmpty: wasEmpty,
  375. })
  376. return
  377. }
  378. baseRepo = repo.BaseRepo
  379. }
  380. }
  381. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  382. results = append(results, private.HookPostReceiveBranchResult{})
  383. continue
  384. }
  385. pr, err := models.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch)
  386. if err != nil && !models.IsErrPullRequestNotExist(err) {
  387. log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
  388. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  389. Err: fmt.Sprintf(
  390. "Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err),
  391. RepoWasEmpty: wasEmpty,
  392. })
  393. return
  394. }
  395. if pr == nil {
  396. if repo.IsFork {
  397. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  398. }
  399. results = append(results, private.HookPostReceiveBranchResult{
  400. Message: true,
  401. Create: true,
  402. Branch: branch,
  403. URL: fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
  404. })
  405. } else {
  406. results = append(results, private.HookPostReceiveBranchResult{
  407. Message: true,
  408. Create: false,
  409. Branch: branch,
  410. URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
  411. })
  412. }
  413. }
  414. }
  415. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  416. Results: results,
  417. RepoWasEmpty: wasEmpty,
  418. })
  419. }
  420. // SetDefaultBranch updates the default branch
  421. func SetDefaultBranch(ctx *macaron.Context) {
  422. ownerName := ctx.Params(":owner")
  423. repoName := ctx.Params(":repo")
  424. branch := ctx.Params(":branch")
  425. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  426. if err != nil {
  427. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  428. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  429. "Err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  430. })
  431. return
  432. }
  433. if repo.OwnerName == "" {
  434. repo.OwnerName = ownerName
  435. }
  436. repo.DefaultBranch = branch
  437. gitRepo, err := git.OpenRepository(repo.RepoPath())
  438. if err != nil {
  439. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  440. "Err": fmt.Sprintf("Failed to get git repository: %s/%s Error: %v", ownerName, repoName, err),
  441. })
  442. return
  443. }
  444. if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  445. if !git.IsErrUnsupportedVersion(err) {
  446. gitRepo.Close()
  447. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  448. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  449. })
  450. return
  451. }
  452. }
  453. gitRepo.Close()
  454. if err := repo.UpdateDefaultBranch(); err != nil {
  455. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  456. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  457. })
  458. return
  459. }
  460. ctx.PlainText(200, []byte("success"))
  461. }