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.

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