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.

git_test.go 12KB

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