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.

409 lines
14 KiB

  1. // Copyright 2017 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 integrations
  5. import (
  6. "crypto/rand"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "testing"
  16. "time"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/setting"
  20. api "code.gitea.io/gitea/modules/structs"
  21. "github.com/stretchr/testify/assert"
  22. )
  23. const (
  24. littleSize = 1024 //1ko
  25. bigSize = 128 * 1024 * 1024 //128Mo
  26. )
  27. func TestGit(t *testing.T) {
  28. onGiteaRun(t, testGit)
  29. }
  30. func testGit(t *testing.T, u *url.URL) {
  31. username := "user2"
  32. baseAPITestContext := NewAPITestContext(t, username, "repo1")
  33. u.Path = baseAPITestContext.GitPath()
  34. forkedUserCtx := NewAPITestContext(t, "user4", "repo1")
  35. t.Run("HTTP", func(t *testing.T) {
  36. defer PrintCurrentTest(t)()
  37. ensureAnonymousClone(t, u)
  38. httpContext := baseAPITestContext
  39. httpContext.Reponame = "repo-tmp-17"
  40. forkedUserCtx.Reponame = httpContext.Reponame
  41. dstPath, err := ioutil.TempDir("", httpContext.Reponame)
  42. assert.NoError(t, err)
  43. defer os.RemoveAll(dstPath)
  44. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  45. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, httpContext.Username, models.AccessModeRead))
  46. t.Run("ForkFromDifferentUser", doAPIForkRepository(httpContext, forkedUserCtx.Username))
  47. u.Path = httpContext.GitPath()
  48. u.User = url.UserPassword(username, userPassword)
  49. t.Run("Clone", doGitClone(dstPath, u))
  50. little, big := standardCommitAndPushTest(t, dstPath)
  51. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  52. rawTest(t, &httpContext, little, big, littleLFS, bigLFS)
  53. mediaTest(t, &httpContext, little, big, littleLFS, bigLFS)
  54. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&httpContext, dstPath))
  55. t.Run("MergeFork", func(t *testing.T) {
  56. t.Run("CreatePRAndMerge", doMergeFork(httpContext, forkedUserCtx, "master", httpContext.Username+":master"))
  57. t.Run("DeleteRepository", doAPIDeleteRepository(httpContext))
  58. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  59. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  60. })
  61. })
  62. t.Run("SSH", func(t *testing.T) {
  63. defer PrintCurrentTest(t)()
  64. sshContext := baseAPITestContext
  65. sshContext.Reponame = "repo-tmp-18"
  66. keyname := "my-testing-key"
  67. forkedUserCtx.Reponame = sshContext.Reponame
  68. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  69. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, models.AccessModeRead))
  70. t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username))
  71. //Setup key the user ssh key
  72. withKeyFile(t, keyname, func(keyFile string) {
  73. t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile))
  74. //Setup remote link
  75. //TODO: get url from api
  76. sshURL := createSSHUrl(sshContext.GitPath(), u)
  77. //Setup clone folder
  78. dstPath, err := ioutil.TempDir("", sshContext.Reponame)
  79. assert.NoError(t, err)
  80. defer os.RemoveAll(dstPath)
  81. t.Run("Clone", doGitClone(dstPath, sshURL))
  82. little, big := standardCommitAndPushTest(t, dstPath)
  83. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  84. rawTest(t, &sshContext, little, big, littleLFS, bigLFS)
  85. mediaTest(t, &sshContext, little, big, littleLFS, bigLFS)
  86. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&sshContext, dstPath))
  87. t.Run("MergeFork", func(t *testing.T) {
  88. t.Run("CreatePRAndMerge", doMergeFork(sshContext, forkedUserCtx, "master", sshContext.Username+":master"))
  89. t.Run("DeleteRepository", doAPIDeleteRepository(sshContext))
  90. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  91. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  92. })
  93. })
  94. })
  95. }
  96. func ensureAnonymousClone(t *testing.T, u *url.URL) {
  97. dstLocalPath, err := ioutil.TempDir("", "repo1")
  98. assert.NoError(t, err)
  99. defer os.RemoveAll(dstLocalPath)
  100. t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
  101. }
  102. func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
  103. t.Run("Standard", func(t *testing.T) {
  104. defer PrintCurrentTest(t)()
  105. little, big = commitAndPushTest(t, dstPath, "data-file-")
  106. })
  107. return
  108. }
  109. func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
  110. t.Run("LFS", func(t *testing.T) {
  111. defer PrintCurrentTest(t)()
  112. setting.CheckLFSVersion()
  113. if !setting.LFS.StartServer {
  114. t.Skip()
  115. return
  116. }
  117. prefix := "lfs-data-file-"
  118. _, err := git.NewCommand("lfs").AddArguments("install").RunInDir(dstPath)
  119. assert.NoError(t, err)
  120. _, err = git.NewCommand("lfs").AddArguments("track", prefix+"*").RunInDir(dstPath)
  121. assert.NoError(t, err)
  122. err = git.AddChanges(dstPath, false, ".gitattributes")
  123. assert.NoError(t, err)
  124. err = git.CommitChangesWithArgs(dstPath, allowLFSFilters(), git.CommitChangesOptions{
  125. Committer: &git.Signature{
  126. Email: "user2@example.com",
  127. Name: "User Two",
  128. When: time.Now(),
  129. },
  130. Author: &git.Signature{
  131. Email: "user2@example.com",
  132. Name: "User Two",
  133. When: time.Now(),
  134. },
  135. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  136. })
  137. assert.NoError(t, err)
  138. littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix)
  139. t.Run("Locks", func(t *testing.T) {
  140. defer PrintCurrentTest(t)()
  141. lockTest(t, dstPath)
  142. })
  143. })
  144. return
  145. }
  146. func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
  147. t.Run("PushCommit", func(t *testing.T) {
  148. defer PrintCurrentTest(t)()
  149. t.Run("Little", func(t *testing.T) {
  150. defer PrintCurrentTest(t)()
  151. little = doCommitAndPush(t, littleSize, dstPath, prefix)
  152. })
  153. t.Run("Big", func(t *testing.T) {
  154. if testing.Short() {
  155. t.Skip("Skipping test in short mode.")
  156. return
  157. }
  158. defer PrintCurrentTest(t)()
  159. big = doCommitAndPush(t, bigSize, dstPath, prefix)
  160. })
  161. })
  162. return
  163. }
  164. func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  165. t.Run("Raw", func(t *testing.T) {
  166. defer PrintCurrentTest(t)()
  167. username := ctx.Username
  168. reponame := ctx.Reponame
  169. session := loginUser(t, username)
  170. // Request raw paths
  171. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", little))
  172. resp := session.MakeRequest(t, req, http.StatusOK)
  173. assert.Equal(t, littleSize, resp.Body.Len())
  174. setting.CheckLFSVersion()
  175. if setting.LFS.StartServer {
  176. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", littleLFS))
  177. resp = session.MakeRequest(t, req, http.StatusOK)
  178. assert.NotEqual(t, littleSize, resp.Body.Len())
  179. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  180. }
  181. if !testing.Short() {
  182. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", big))
  183. resp = session.MakeRequest(t, req, http.StatusOK)
  184. assert.Equal(t, bigSize, resp.Body.Len())
  185. if setting.LFS.StartServer {
  186. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", bigLFS))
  187. resp = session.MakeRequest(t, req, http.StatusOK)
  188. assert.NotEqual(t, bigSize, resp.Body.Len())
  189. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  190. }
  191. }
  192. })
  193. }
  194. func mediaTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  195. t.Run("Media", func(t *testing.T) {
  196. defer PrintCurrentTest(t)()
  197. username := ctx.Username
  198. reponame := ctx.Reponame
  199. session := loginUser(t, username)
  200. // Request media paths
  201. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", little))
  202. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  203. assert.Equal(t, littleSize, resp.Length)
  204. setting.CheckLFSVersion()
  205. if setting.LFS.StartServer {
  206. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", littleLFS))
  207. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  208. assert.Equal(t, littleSize, resp.Length)
  209. }
  210. if !testing.Short() {
  211. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", big))
  212. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  213. assert.Equal(t, bigSize, resp.Length)
  214. if setting.LFS.StartServer {
  215. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", bigLFS))
  216. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  217. assert.Equal(t, bigSize, resp.Length)
  218. }
  219. }
  220. })
  221. }
  222. func lockTest(t *testing.T, repoPath string) {
  223. lockFileTest(t, "README.md", repoPath)
  224. }
  225. func lockFileTest(t *testing.T, filename, repoPath string) {
  226. _, err := git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  227. assert.NoError(t, err)
  228. _, err = git.NewCommand("lfs").AddArguments("lock", filename).RunInDir(repoPath)
  229. assert.NoError(t, err)
  230. _, err = git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  231. assert.NoError(t, err)
  232. _, err = git.NewCommand("lfs").AddArguments("unlock", filename).RunInDir(repoPath)
  233. assert.NoError(t, err)
  234. }
  235. func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
  236. name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
  237. assert.NoError(t, err)
  238. _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push
  239. assert.NoError(t, err)
  240. return name
  241. }
  242. func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
  243. //Generate random file
  244. data := make([]byte, size)
  245. _, err := rand.Read(data)
  246. if err != nil {
  247. return "", err
  248. }
  249. tmpFile, err := ioutil.TempFile(repoPath, prefix)
  250. if err != nil {
  251. return "", err
  252. }
  253. defer tmpFile.Close()
  254. _, err = tmpFile.Write(data)
  255. if err != nil {
  256. return "", err
  257. }
  258. //Commit
  259. // Now here we should explicitly allow lfs filters to run
  260. globalArgs := allowLFSFilters()
  261. err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name()))
  262. if err != nil {
  263. return "", err
  264. }
  265. err = git.CommitChangesWithArgs(repoPath, globalArgs, git.CommitChangesOptions{
  266. Committer: &git.Signature{
  267. Email: email,
  268. Name: fullName,
  269. When: time.Now(),
  270. },
  271. Author: &git.Signature{
  272. Email: email,
  273. Name: fullName,
  274. When: time.Now(),
  275. },
  276. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  277. })
  278. return filepath.Base(tmpFile.Name()), err
  279. }
  280. func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
  281. return func(t *testing.T) {
  282. defer PrintCurrentTest(t)()
  283. t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected"))
  284. t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
  285. ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame)
  286. t.Run("ProtectProtectedBranchNoWhitelist", doProtectBranch(ctx, "protected", ""))
  287. t.Run("GenerateCommit", func(t *testing.T) {
  288. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  289. assert.NoError(t, err)
  290. })
  291. t.Run("FailToPushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "origin", "protected"))
  292. t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected"))
  293. var pr api.PullRequest
  294. var err error
  295. t.Run("CreatePullRequest", func(t *testing.T) {
  296. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "protected", "unprotected")(t)
  297. assert.NoError(t, err)
  298. })
  299. t.Run("MergePR", doAPIMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  300. t.Run("PullProtected", doGitPull(dstPath, "origin", "protected"))
  301. t.Run("ProtectProtectedBranchWhitelist", doProtectBranch(ctx, "protected", baseCtx.Username))
  302. t.Run("CheckoutMaster", doGitCheckoutBranch(dstPath, "master"))
  303. t.Run("CreateBranchForced", doGitCreateBranch(dstPath, "toforce"))
  304. t.Run("GenerateCommit", func(t *testing.T) {
  305. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  306. assert.NoError(t, err)
  307. })
  308. t.Run("FailToForcePushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "-f", "origin", "toforce:protected"))
  309. t.Run("MergeProtectedToToforce", doGitMerge(dstPath, "protected"))
  310. t.Run("PushToProtectedBranch", doGitPushTestRepository(dstPath, "origin", "toforce:protected"))
  311. t.Run("CheckoutMasterAgain", doGitCheckoutBranch(dstPath, "master"))
  312. }
  313. }
  314. func doProtectBranch(ctx APITestContext, branch string, userToWhitelist string) func(t *testing.T) {
  315. // We are going to just use the owner to set the protection.
  316. return func(t *testing.T) {
  317. csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)))
  318. if userToWhitelist == "" {
  319. // Change branch to protected
  320. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{
  321. "_csrf": csrf,
  322. "protected": "on",
  323. })
  324. ctx.Session.MakeRequest(t, req, http.StatusFound)
  325. } else {
  326. user, err := models.GetUserByName(userToWhitelist)
  327. assert.NoError(t, err)
  328. // Change branch to protected
  329. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{
  330. "_csrf": csrf,
  331. "protected": "on",
  332. "enable_whitelist": "on",
  333. "whitelist_users": strconv.FormatInt(user.ID, 10),
  334. })
  335. ctx.Session.MakeRequest(t, req, http.StatusFound)
  336. }
  337. // Check if master branch has been locked successfully
  338. flashCookie := ctx.Session.GetCookie("macaron_flash")
  339. assert.NotNil(t, flashCookie)
  340. assert.EqualValues(t, "success%3DBranch%2Bprotection%2Bfor%2Bbranch%2B%2527"+url.QueryEscape(branch)+"%2527%2Bhas%2Bbeen%2Bupdated.", flashCookie.Value)
  341. }
  342. }
  343. func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) func(t *testing.T) {
  344. return func(t *testing.T) {
  345. var pr api.PullRequest
  346. var err error
  347. t.Run("CreatePullRequest", func(t *testing.T) {
  348. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
  349. assert.NoError(t, err)
  350. })
  351. t.Run("MergePR", doAPIMergePullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  352. }
  353. }