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

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