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.

branches.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // Copyright 2016 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 models
  5. import (
  6. "context"
  7. "fmt"
  8. "time"
  9. "code.gitea.io/gitea/modules/base"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. "github.com/unknwon/com"
  15. )
  16. const (
  17. // ProtectedBranchRepoID protected Repo ID
  18. ProtectedBranchRepoID = "GITEA_REPO_ID"
  19. // ProtectedBranchPRID protected Repo PR ID
  20. ProtectedBranchPRID = "GITEA_PR_ID"
  21. )
  22. // ProtectedBranch struct
  23. type ProtectedBranch struct {
  24. ID int64 `xorm:"pk autoincr"`
  25. RepoID int64 `xorm:"UNIQUE(s)"`
  26. BranchName string `xorm:"UNIQUE(s)"`
  27. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  28. EnableWhitelist bool
  29. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  30. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  31. EnableMergeWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  32. WhitelistDeployKeys bool `xorm:"NOT NULL DEFAULT false"`
  33. MergeWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  34. MergeWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  35. EnableStatusCheck bool `xorm:"NOT NULL DEFAULT false"`
  36. StatusCheckContexts []string `xorm:"JSON TEXT"`
  37. EnableApprovalsWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  38. ApprovalsWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  39. ApprovalsWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  40. RequiredApprovals int64 `xorm:"NOT NULL DEFAULT 0"`
  41. BlockOnRejectedReviews bool `xorm:"NOT NULL DEFAULT false"`
  42. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  43. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  44. }
  45. // IsProtected returns if the branch is protected
  46. func (protectBranch *ProtectedBranch) IsProtected() bool {
  47. return protectBranch.ID > 0
  48. }
  49. // CanUserPush returns if some user could push to this protected branch
  50. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  51. if !protectBranch.CanPush {
  52. return false
  53. }
  54. if !protectBranch.EnableWhitelist {
  55. if user, err := GetUserByID(userID); err != nil {
  56. log.Error("GetUserByID: %v", err)
  57. return false
  58. } else if repo, err := GetRepositoryByID(protectBranch.RepoID); err != nil {
  59. log.Error("GetRepositoryByID: %v", err)
  60. return false
  61. } else if writeAccess, err := HasAccessUnit(user, repo, UnitTypeCode, AccessModeWrite); err != nil {
  62. log.Error("HasAccessUnit: %v", err)
  63. return false
  64. } else {
  65. return writeAccess
  66. }
  67. }
  68. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  69. return true
  70. }
  71. if len(protectBranch.WhitelistTeamIDs) == 0 {
  72. return false
  73. }
  74. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  75. if err != nil {
  76. log.Error("IsUserInTeams: %v", err)
  77. return false
  78. }
  79. return in
  80. }
  81. // CanUserMerge returns if some user could merge a pull request to this protected branch
  82. func (protectBranch *ProtectedBranch) CanUserMerge(userID int64) bool {
  83. if !protectBranch.EnableMergeWhitelist {
  84. return true
  85. }
  86. if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
  87. return true
  88. }
  89. if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
  90. return false
  91. }
  92. in, err := IsUserInTeams(userID, protectBranch.MergeWhitelistTeamIDs)
  93. if err != nil {
  94. log.Error("IsUserInTeams: %v", err)
  95. return false
  96. }
  97. return in
  98. }
  99. // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
  100. func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64) bool {
  101. if !protectBranch.EnableMergeWhitelist {
  102. return true
  103. }
  104. if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
  105. return true
  106. }
  107. if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
  108. return false
  109. }
  110. in, err := IsUserInTeams(userID, protectBranch.MergeWhitelistTeamIDs)
  111. if err != nil {
  112. log.Error("IsUserInTeams: %v", err)
  113. return false
  114. }
  115. return in
  116. }
  117. // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
  118. func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) {
  119. return protectBranch.isUserOfficialReviewer(x, user)
  120. }
  121. func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e Engine, user *User) (bool, error) {
  122. repo, err := getRepositoryByID(e, protectBranch.RepoID)
  123. if err != nil {
  124. return false, err
  125. }
  126. if !protectBranch.EnableApprovalsWhitelist {
  127. // Anyone with write access is considered official reviewer
  128. writeAccess, err := hasAccessUnit(e, user, repo, UnitTypeCode, AccessModeWrite)
  129. if err != nil {
  130. return false, err
  131. }
  132. return writeAccess, nil
  133. }
  134. if base.Int64sContains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) {
  135. return true, nil
  136. }
  137. inTeam, err := isUserInTeams(e, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
  138. if err != nil {
  139. return false, err
  140. }
  141. return inTeam, nil
  142. }
  143. // HasEnoughApprovals returns true if pr has enough granted approvals.
  144. func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool {
  145. if protectBranch.RequiredApprovals == 0 {
  146. return true
  147. }
  148. return protectBranch.GetGrantedApprovalsCount(pr) >= protectBranch.RequiredApprovals
  149. }
  150. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
  151. func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 {
  152. approvals, err := x.Where("issue_id = ?", pr.IssueID).
  153. And("type = ?", ReviewTypeApprove).
  154. And("official = ?", true).
  155. Count(new(Review))
  156. if err != nil {
  157. log.Error("GetGrantedApprovalsCount: %v", err)
  158. return 0
  159. }
  160. return approvals
  161. }
  162. // MergeBlockedByRejectedReview returns true if merge is blocked by rejected reviews
  163. func (protectBranch *ProtectedBranch) MergeBlockedByRejectedReview(pr *PullRequest) bool {
  164. if !protectBranch.BlockOnRejectedReviews {
  165. return false
  166. }
  167. rejectExist, err := x.Where("issue_id = ?", pr.IssueID).
  168. And("type = ?", ReviewTypeReject).
  169. And("official = ?", true).
  170. Exist(new(Review))
  171. if err != nil {
  172. log.Error("MergeBlockedByRejectedReview: %v", err)
  173. return true
  174. }
  175. return rejectExist
  176. }
  177. // GetProtectedBranchByRepoID getting protected branch by repo ID
  178. func GetProtectedBranchByRepoID(repoID int64) ([]*ProtectedBranch, error) {
  179. protectedBranches := make([]*ProtectedBranch, 0)
  180. return protectedBranches, x.Where("repo_id = ?", repoID).Desc("updated_unix").Find(&protectedBranches)
  181. }
  182. // GetProtectedBranchBy getting protected branch by ID/Name
  183. func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
  184. return getProtectedBranchBy(x, repoID, branchName)
  185. }
  186. func getProtectedBranchBy(e Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
  187. rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
  188. has, err := e.Get(rel)
  189. if err != nil {
  190. return nil, err
  191. }
  192. if !has {
  193. return nil, nil
  194. }
  195. return rel, nil
  196. }
  197. // GetProtectedBranchByID getting protected branch by ID
  198. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  199. rel := &ProtectedBranch{}
  200. has, err := x.ID(id).Get(rel)
  201. if err != nil {
  202. return nil, err
  203. }
  204. if !has {
  205. return nil, nil
  206. }
  207. return rel, nil
  208. }
  209. // WhitelistOptions represent all sorts of whitelists used for protected branches
  210. type WhitelistOptions struct {
  211. UserIDs []int64
  212. TeamIDs []int64
  213. MergeUserIDs []int64
  214. MergeTeamIDs []int64
  215. ApprovalsUserIDs []int64
  216. ApprovalsTeamIDs []int64
  217. }
  218. // UpdateProtectBranch saves branch protection options of repository.
  219. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  220. // This function also performs check if whitelist user and team's IDs have been changed
  221. // to avoid unnecessary whitelist delete and regenerate.
  222. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  223. if err = repo.GetOwner(); err != nil {
  224. return fmt.Errorf("GetOwner: %v", err)
  225. }
  226. whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  227. if err != nil {
  228. return err
  229. }
  230. protectBranch.WhitelistUserIDs = whitelist
  231. whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  232. if err != nil {
  233. return err
  234. }
  235. protectBranch.MergeWhitelistUserIDs = whitelist
  236. whitelist, err = updateApprovalWhitelist(repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  237. if err != nil {
  238. return err
  239. }
  240. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  241. // if the repo is in an organization
  242. whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  243. if err != nil {
  244. return err
  245. }
  246. protectBranch.WhitelistTeamIDs = whitelist
  247. whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  248. if err != nil {
  249. return err
  250. }
  251. protectBranch.MergeWhitelistTeamIDs = whitelist
  252. whitelist, err = updateTeamWhitelist(repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  253. if err != nil {
  254. return err
  255. }
  256. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  257. // Make sure protectBranch.ID is not 0 for whitelists
  258. if protectBranch.ID == 0 {
  259. if _, err = x.Insert(protectBranch); err != nil {
  260. return fmt.Errorf("Insert: %v", err)
  261. }
  262. return nil
  263. }
  264. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  265. return fmt.Errorf("Update: %v", err)
  266. }
  267. return nil
  268. }
  269. // GetProtectedBranches get all protected branches
  270. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  271. protectedBranches := make([]*ProtectedBranch, 0)
  272. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  273. }
  274. // GetBranchProtection get the branch protection of a branch
  275. func (repo *Repository) GetBranchProtection(branchName string) (*ProtectedBranch, error) {
  276. return GetProtectedBranchBy(repo.ID, branchName)
  277. }
  278. // IsProtectedBranch checks if branch is protected
  279. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  280. if doer == nil {
  281. return true, nil
  282. }
  283. protectedBranch := &ProtectedBranch{
  284. RepoID: repo.ID,
  285. BranchName: branchName,
  286. }
  287. has, err := x.Exist(protectedBranch)
  288. if err != nil {
  289. return true, err
  290. }
  291. return has, nil
  292. }
  293. // IsProtectedBranchForPush checks if branch is protected for push
  294. func (repo *Repository) IsProtectedBranchForPush(branchName string, doer *User) (bool, error) {
  295. if doer == nil {
  296. return true, nil
  297. }
  298. protectedBranch := &ProtectedBranch{
  299. RepoID: repo.ID,
  300. BranchName: branchName,
  301. }
  302. has, err := x.Get(protectedBranch)
  303. if err != nil {
  304. return true, err
  305. } else if has {
  306. return !protectedBranch.CanUserPush(doer.ID), nil
  307. }
  308. return false, nil
  309. }
  310. // IsProtectedBranchForMerging checks if branch is protected for merging
  311. func (repo *Repository) IsProtectedBranchForMerging(pr *PullRequest, branchName string, doer *User) (bool, error) {
  312. if doer == nil {
  313. return true, nil
  314. }
  315. protectedBranch := &ProtectedBranch{
  316. RepoID: repo.ID,
  317. BranchName: branchName,
  318. }
  319. has, err := x.Get(protectedBranch)
  320. if err != nil {
  321. return true, err
  322. } else if has {
  323. return !protectedBranch.CanUserMerge(doer.ID) || !protectedBranch.HasEnoughApprovals(pr) || protectedBranch.MergeBlockedByRejectedReview(pr), nil
  324. }
  325. return false, nil
  326. }
  327. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  328. // the users from newWhitelist which have explicit read or write access to the repo.
  329. func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  330. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  331. if !hasUsersChanged {
  332. return currentWhitelist, nil
  333. }
  334. whitelist = make([]int64, 0, len(newWhitelist))
  335. for _, userID := range newWhitelist {
  336. if reader, err := repo.IsReader(userID); err != nil {
  337. return nil, err
  338. } else if !reader {
  339. continue
  340. }
  341. whitelist = append(whitelist, userID)
  342. }
  343. return
  344. }
  345. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  346. // the users from newWhitelist which have write access to the repo.
  347. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  348. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  349. if !hasUsersChanged {
  350. return currentWhitelist, nil
  351. }
  352. whitelist = make([]int64, 0, len(newWhitelist))
  353. for _, userID := range newWhitelist {
  354. user, err := GetUserByID(userID)
  355. if err != nil {
  356. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  357. }
  358. perm, err := GetUserRepoPermission(repo, user)
  359. if err != nil {
  360. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  361. }
  362. if !perm.CanWrite(UnitTypeCode) {
  363. continue // Drop invalid user ID
  364. }
  365. whitelist = append(whitelist, userID)
  366. }
  367. return
  368. }
  369. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  370. // the teams from newWhitelist which have write access to the repo.
  371. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  372. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  373. if !hasTeamsChanged {
  374. return currentWhitelist, nil
  375. }
  376. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeRead)
  377. if err != nil {
  378. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  379. }
  380. whitelist = make([]int64, 0, len(teams))
  381. for i := range teams {
  382. if com.IsSliceContainsInt64(newWhitelist, teams[i].ID) {
  383. whitelist = append(whitelist, teams[i].ID)
  384. }
  385. }
  386. return
  387. }
  388. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  389. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  390. protectedBranch := &ProtectedBranch{
  391. RepoID: repo.ID,
  392. ID: id,
  393. }
  394. sess := x.NewSession()
  395. defer sess.Close()
  396. if err = sess.Begin(); err != nil {
  397. return err
  398. }
  399. if affected, err := sess.Delete(protectedBranch); err != nil {
  400. return err
  401. } else if affected != 1 {
  402. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  403. }
  404. return sess.Commit()
  405. }
  406. // DeletedBranch struct
  407. type DeletedBranch struct {
  408. ID int64 `xorm:"pk autoincr"`
  409. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  410. Name string `xorm:"UNIQUE(s) NOT NULL"`
  411. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  412. DeletedByID int64 `xorm:"INDEX"`
  413. DeletedBy *User `xorm:"-"`
  414. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  415. }
  416. // AddDeletedBranch adds a deleted branch to the database
  417. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  418. deletedBranch := &DeletedBranch{
  419. RepoID: repo.ID,
  420. Name: branchName,
  421. Commit: commit,
  422. DeletedByID: deletedByID,
  423. }
  424. sess := x.NewSession()
  425. defer sess.Close()
  426. if err := sess.Begin(); err != nil {
  427. return err
  428. }
  429. if _, err := sess.InsertOne(deletedBranch); err != nil {
  430. return err
  431. }
  432. return sess.Commit()
  433. }
  434. // GetDeletedBranches returns all the deleted branches
  435. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  436. deletedBranches := make([]*DeletedBranch, 0)
  437. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  438. }
  439. // GetDeletedBranchByID get a deleted branch by its ID
  440. func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) {
  441. deletedBranch := &DeletedBranch{}
  442. has, err := x.ID(id).Get(deletedBranch)
  443. if err != nil {
  444. return nil, err
  445. }
  446. if !has {
  447. return nil, nil
  448. }
  449. return deletedBranch, nil
  450. }
  451. // RemoveDeletedBranch removes a deleted branch from the database
  452. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  453. deletedBranch := &DeletedBranch{
  454. RepoID: repo.ID,
  455. ID: id,
  456. }
  457. sess := x.NewSession()
  458. defer sess.Close()
  459. if err = sess.Begin(); err != nil {
  460. return err
  461. }
  462. if affected, err := sess.Delete(deletedBranch); err != nil {
  463. return err
  464. } else if affected != 1 {
  465. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  466. }
  467. return sess.Commit()
  468. }
  469. // LoadUser loads the user that deleted the branch
  470. // When there's no user found it returns a NewGhostUser
  471. func (deletedBranch *DeletedBranch) LoadUser() {
  472. user, err := GetUserByID(deletedBranch.DeletedByID)
  473. if err != nil {
  474. user = NewGhostUser()
  475. }
  476. deletedBranch.DeletedBy = user
  477. }
  478. // RemoveDeletedBranch removes all deleted branches
  479. func RemoveDeletedBranch(repoID int64, branch string) error {
  480. _, err := x.Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
  481. return err
  482. }
  483. // RemoveOldDeletedBranches removes old deleted branches
  484. func RemoveOldDeletedBranches(ctx context.Context) {
  485. // Nothing to do for shutdown or terminate
  486. log.Trace("Doing: DeletedBranchesCleanup")
  487. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  488. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  489. if err != nil {
  490. log.Error("DeletedBranchesCleanup: %v", err)
  491. }
  492. }