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

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