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.

402 lines
11 KiB

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