本站源代码
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.

494 lines
14KB

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