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

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