gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package integration
  4. import (
  5. "net/http"
  6. "net/http/httptest"
  7. "net/url"
  8. "testing"
  9. auth_model "code.gitea.io/gitea/models/auth"
  10. "code.gitea.io/gitea/models/db"
  11. git_model "code.gitea.io/gitea/models/git"
  12. api "code.gitea.io/gitea/modules/structs"
  13. "code.gitea.io/gitea/tests"
  14. "github.com/stretchr/testify/assert"
  15. )
  16. func testAPIGetBranch(t *testing.T, branchName string, exists bool) {
  17. token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository)
  18. req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s", branchName).
  19. AddTokenAuth(token)
  20. resp := MakeRequest(t, req, NoExpectedStatus)
  21. if !exists {
  22. assert.Equal(t, http.StatusNotFound, resp.Code)
  23. return
  24. }
  25. assert.Equal(t, http.StatusOK, resp.Code)
  26. var branch api.Branch
  27. DecodeJSON(t, resp, &branch)
  28. assert.Equal(t, branchName, branch.Name)
  29. assert.True(t, branch.UserCanPush)
  30. assert.True(t, branch.UserCanMerge)
  31. }
  32. func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) *api.BranchProtection {
  33. token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository)
  34. req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s", branchName).
  35. AddTokenAuth(token)
  36. resp := MakeRequest(t, req, expectedHTTPStatus)
  37. if resp.Code == http.StatusOK {
  38. var branchProtection api.BranchProtection
  39. DecodeJSON(t, resp, &branchProtection)
  40. assert.Equal(t, branchName, branchProtection.RuleName)
  41. return &branchProtection
  42. }
  43. return nil
  44. }
  45. func testAPICreateBranchProtection(t *testing.T, branchName string, expectedPriority, expectedHTTPStatus int) {
  46. token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository)
  47. req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections", &api.BranchProtection{
  48. RuleName: branchName,
  49. }).AddTokenAuth(token)
  50. resp := MakeRequest(t, req, expectedHTTPStatus)
  51. if resp.Code == http.StatusCreated {
  52. var branchProtection api.BranchProtection
  53. DecodeJSON(t, resp, &branchProtection)
  54. assert.Equal(t, branchName, branchProtection.RuleName)
  55. assert.EqualValues(t, expectedPriority, branchProtection.Priority)
  56. }
  57. }
  58. func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) {
  59. token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository)
  60. req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName, body).
  61. AddTokenAuth(token)
  62. resp := MakeRequest(t, req, expectedHTTPStatus)
  63. if resp.Code == http.StatusOK {
  64. var branchProtection api.BranchProtection
  65. DecodeJSON(t, resp, &branchProtection)
  66. assert.Equal(t, branchName, branchProtection.RuleName)
  67. }
  68. }
  69. func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) {
  70. token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository)
  71. req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s", branchName).
  72. AddTokenAuth(token)
  73. MakeRequest(t, req, expectedHTTPStatus)
  74. }
  75. func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) {
  76. token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository)
  77. req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s", branchName).
  78. AddTokenAuth(token)
  79. MakeRequest(t, req, expectedHTTPStatus)
  80. }
  81. func TestAPIGetBranch(t *testing.T) {
  82. defer tests.PrepareTestEnv(t)()
  83. for _, test := range []struct {
  84. BranchName string
  85. Exists bool
  86. }{
  87. {"master", true},
  88. {"master/doesnotexist", false},
  89. {"feature/1", true},
  90. {"feature/1/doesnotexist", false},
  91. } {
  92. testAPIGetBranch(t, test.BranchName, test.Exists)
  93. }
  94. }
  95. func TestAPICreateBranch(t *testing.T) {
  96. onGiteaRun(t, testAPICreateBranches)
  97. }
  98. func testAPICreateBranches(t *testing.T, giteaURL *url.URL) {
  99. username := "user2"
  100. ctx := NewAPITestContext(t, username, "my-noo-repo", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
  101. giteaURL.Path = ctx.GitPath()
  102. t.Run("CreateRepo", doAPICreateRepository(ctx, false))
  103. testCases := []struct {
  104. OldBranch string
  105. NewBranch string
  106. ExpectedHTTPStatus int
  107. }{
  108. // Creating branch from default branch
  109. {
  110. OldBranch: "",
  111. NewBranch: "new_branch_from_default_branch",
  112. ExpectedHTTPStatus: http.StatusCreated,
  113. },
  114. // Creating branch from master
  115. {
  116. OldBranch: "master",
  117. NewBranch: "new_branch_from_master_1",
  118. ExpectedHTTPStatus: http.StatusCreated,
  119. },
  120. // Trying to create from master but already exists
  121. {
  122. OldBranch: "master",
  123. NewBranch: "new_branch_from_master_1",
  124. ExpectedHTTPStatus: http.StatusConflict,
  125. },
  126. // Trying to create from other branch (not default branch)
  127. // ps: it can't test the case-sensitive behavior here: the "BRANCH_2" can't be created by git on a case-insensitive filesystem, it makes the test fail quickly before the database code.
  128. // Suppose some users are running Gitea on a case-insensitive filesystem, it seems that it's unable to support case-sensitive branch names.
  129. {
  130. OldBranch: "new_branch_from_master_1",
  131. NewBranch: "branch_2",
  132. ExpectedHTTPStatus: http.StatusCreated,
  133. },
  134. // Trying to create from a branch which does not exist
  135. {
  136. OldBranch: "does_not_exist",
  137. NewBranch: "new_branch_from_non_existent",
  138. ExpectedHTTPStatus: http.StatusNotFound,
  139. },
  140. // Trying to create a branch with UTF8
  141. {
  142. OldBranch: "master",
  143. NewBranch: "test-👀",
  144. ExpectedHTTPStatus: http.StatusCreated,
  145. },
  146. }
  147. for _, test := range testCases {
  148. session := ctx.Session
  149. t.Run(test.NewBranch, func(t *testing.T) {
  150. testAPICreateBranch(t, session, "user2", "my-noo-repo", test.OldBranch, test.NewBranch, test.ExpectedHTTPStatus)
  151. })
  152. }
  153. }
  154. func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool {
  155. token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
  156. req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches", &api.CreateBranchRepoOption{
  157. BranchName: newBranch,
  158. OldBranchName: oldBranch,
  159. }).AddTokenAuth(token)
  160. resp := MakeRequest(t, req, status)
  161. var branch api.Branch
  162. DecodeJSON(t, resp, &branch)
  163. if resp.Result().StatusCode == http.StatusCreated {
  164. assert.Equal(t, newBranch, branch.Name)
  165. }
  166. return resp.Result().StatusCode == status
  167. }
  168. func TestAPIRenameBranch(t *testing.T) {
  169. onGiteaRun(t, func(t *testing.T, _ *url.URL) {
  170. t.Run("RenameBranchWithEmptyRepo", func(t *testing.T) {
  171. testAPIRenameBranch(t, "user10", "user10", "repo6", "master", "test", http.StatusNotFound)
  172. })
  173. t.Run("RenameBranchWithSameBranchNames", func(t *testing.T) {
  174. resp := testAPIRenameBranch(t, "user2", "user2", "repo1", "master", "master", http.StatusUnprocessableEntity)
  175. assert.Contains(t, resp.Body.String(), "Cannot rename a branch using the same name or rename to a branch that already exists.")
  176. })
  177. t.Run("RenameBranchThatAlreadyExists", func(t *testing.T) {
  178. resp := testAPIRenameBranch(t, "user2", "user2", "repo1", "master", "branch2", http.StatusUnprocessableEntity)
  179. assert.Contains(t, resp.Body.String(), "Cannot rename a branch using the same name or rename to a branch that already exists.")
  180. })
  181. t.Run("RenameBranchWithNonExistentBranch", func(t *testing.T) {
  182. resp := testAPIRenameBranch(t, "user2", "user2", "repo1", "i-dont-exist", "new-branch-name", http.StatusNotFound)
  183. assert.Contains(t, resp.Body.String(), "Branch doesn't exist.")
  184. })
  185. t.Run("RenameBranchWithNonAdminDoer", func(t *testing.T) {
  186. // don't allow default branch renaming
  187. resp := testAPIRenameBranch(t, "user40", "user2", "repo1", "master", "new-branch-name", http.StatusForbidden)
  188. assert.Contains(t, resp.Body.String(), "User must be a repo or site admin to rename default or protected branches.")
  189. // don't allow protected branch renaming
  190. token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository)
  191. req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branches", &api.CreateBranchRepoOption{
  192. BranchName: "protected-branch",
  193. }).AddTokenAuth(token)
  194. MakeRequest(t, req, http.StatusCreated)
  195. testAPICreateBranchProtection(t, "protected-branch", 1, http.StatusCreated)
  196. resp = testAPIRenameBranch(t, "user40", "user2", "repo1", "protected-branch", "new-branch-name", http.StatusForbidden)
  197. assert.Contains(t, resp.Body.String(), "User must be a repo or site admin to rename default or protected branches.")
  198. })
  199. t.Run("RenameBranchWithGlobedBasedProtectionRulesAndAdminAccess", func(t *testing.T) {
  200. // don't allow branch that falls under glob-based protection rules to be renamed
  201. token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository)
  202. req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections", &api.BranchProtection{
  203. RuleName: "protected/**",
  204. EnablePush: true,
  205. }).AddTokenAuth(token)
  206. MakeRequest(t, req, http.StatusCreated)
  207. from := "protected/1"
  208. req = NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branches", &api.CreateBranchRepoOption{
  209. BranchName: from,
  210. }).AddTokenAuth(token)
  211. MakeRequest(t, req, http.StatusCreated)
  212. resp := testAPIRenameBranch(t, "user2", "user2", "repo1", from, "new-branch-name", http.StatusForbidden)
  213. assert.Contains(t, resp.Body.String(), "Branch is protected by glob-based protection rules.")
  214. })
  215. t.Run("RenameBranchNormalScenario", func(t *testing.T) {
  216. testAPIRenameBranch(t, "user2", "user2", "repo1", "branch2", "new-branch-name", http.StatusNoContent)
  217. })
  218. })
  219. }
  220. func testAPIRenameBranch(t *testing.T, doerName, ownerName, repoName, from, to string, expectedHTTPStatus int) *httptest.ResponseRecorder {
  221. token := getUserToken(t, doerName, auth_model.AccessTokenScopeWriteRepository)
  222. req := NewRequestWithJSON(t, "PATCH", "api/v1/repos/"+ownerName+"/"+repoName+"/branches/"+from, &api.RenameBranchRepoOption{
  223. Name: to,
  224. }).AddTokenAuth(token)
  225. return MakeRequest(t, req, expectedHTTPStatus)
  226. }
  227. func TestAPIBranchProtection(t *testing.T) {
  228. defer tests.PrepareTestEnv(t)()
  229. // Branch protection on branch that not exist
  230. testAPICreateBranchProtection(t, "master/doesnotexist", 1, http.StatusCreated)
  231. // Get branch protection on branch that exist but not branch protection
  232. testAPIGetBranchProtection(t, "master", http.StatusNotFound)
  233. testAPICreateBranchProtection(t, "master", 2, http.StatusCreated)
  234. // Can only create once
  235. testAPICreateBranchProtection(t, "master", 0, http.StatusForbidden)
  236. // Can't delete a protected branch
  237. testAPIDeleteBranch(t, "master", http.StatusForbidden)
  238. testAPIGetBranchProtection(t, "master", http.StatusOK)
  239. testAPIEditBranchProtection(t, "master", &api.BranchProtection{
  240. EnablePush: true,
  241. }, http.StatusOK)
  242. // enable status checks, require the "test1" check to pass
  243. testAPIEditBranchProtection(t, "master", &api.BranchProtection{
  244. EnableStatusCheck: true,
  245. StatusCheckContexts: []string{"test1"},
  246. }, http.StatusOK)
  247. bp := testAPIGetBranchProtection(t, "master", http.StatusOK)
  248. assert.True(t, bp.EnableStatusCheck)
  249. assert.Equal(t, []string{"test1"}, bp.StatusCheckContexts)
  250. // disable status checks, clear the list of required checks
  251. testAPIEditBranchProtection(t, "master", &api.BranchProtection{
  252. EnableStatusCheck: false,
  253. StatusCheckContexts: []string{},
  254. }, http.StatusOK)
  255. bp = testAPIGetBranchProtection(t, "master", http.StatusOK)
  256. assert.False(t, bp.EnableStatusCheck)
  257. assert.Equal(t, []string{}, bp.StatusCheckContexts)
  258. testAPIDeleteBranchProtection(t, "master", http.StatusNoContent)
  259. // Test branch deletion
  260. testAPIDeleteBranch(t, "master", http.StatusForbidden)
  261. testAPIDeleteBranch(t, "branch2", http.StatusNoContent)
  262. }
  263. func TestAPICreateBranchWithSyncBranches(t *testing.T) {
  264. defer tests.PrepareTestEnv(t)()
  265. branches, err := db.Find[git_model.Branch](t.Context(), git_model.FindBranchOptions{
  266. RepoID: 1,
  267. })
  268. assert.NoError(t, err)
  269. assert.Len(t, branches, 6)
  270. // make a broke repository with no branch on database
  271. _, err = db.DeleteByBean(t.Context(), git_model.Branch{RepoID: 1})
  272. assert.NoError(t, err)
  273. onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
  274. ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
  275. giteaURL.Path = ctx.GitPath()
  276. testAPICreateBranch(t, ctx.Session, "user2", "repo1", "", "new_branch", http.StatusCreated)
  277. })
  278. branches, err = db.Find[git_model.Branch](t.Context(), git_model.FindBranchOptions{
  279. RepoID: 1,
  280. })
  281. assert.NoError(t, err)
  282. assert.Len(t, branches, 7)
  283. branches, err = db.Find[git_model.Branch](t.Context(), git_model.FindBranchOptions{
  284. RepoID: 1,
  285. Keyword: "new_branch",
  286. })
  287. assert.NoError(t, err)
  288. assert.Len(t, branches, 1)
  289. }