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

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