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 14KB

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