route_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // Copyright 2020 The Gogs 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 lfs
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/http/httptest"
  10. "testing"
  11. "github.com/stretchr/testify/assert"
  12. "gopkg.in/macaron.v1"
  13. "gogs.io/gogs/internal/auth"
  14. "gogs.io/gogs/internal/db"
  15. "gogs.io/gogs/internal/lfsutil"
  16. )
  17. func Test_authenticate(t *testing.T) {
  18. m := macaron.New()
  19. m.Use(macaron.Renderer())
  20. m.Get("/", authenticate(), func(w http.ResponseWriter, user *db.User) {
  21. fmt.Fprintf(w, "ID: %d, Name: %s", user.ID, user.Name)
  22. })
  23. tests := []struct {
  24. name string
  25. header http.Header
  26. mockUsersStore *db.MockUsersStore
  27. mockTwoFactorsStore *db.MockTwoFactorsStore
  28. mockAccessTokensStore *db.MockAccessTokensStore
  29. expStatusCode int
  30. expHeader http.Header
  31. expBody string
  32. }{
  33. {
  34. name: "no authorization",
  35. expStatusCode: http.StatusUnauthorized,
  36. expHeader: http.Header{
  37. "Lfs-Authenticate": []string{`Basic realm="Git LFS"`},
  38. "Content-Type": []string{"application/vnd.git-lfs+json"},
  39. },
  40. expBody: `{"message":"Credentials needed"}` + "\n",
  41. },
  42. {
  43. name: "user has 2FA enabled",
  44. header: http.Header{
  45. "Authorization": []string{"Basic dXNlcm5hbWU6cGFzc3dvcmQ="},
  46. },
  47. mockUsersStore: &db.MockUsersStore{
  48. MockAuthenticate: func(username, password string, loginSourceID int64) (*db.User, error) {
  49. return &db.User{}, nil
  50. },
  51. },
  52. mockTwoFactorsStore: &db.MockTwoFactorsStore{
  53. MockIsUserEnabled: func(userID int64) bool {
  54. return true
  55. },
  56. },
  57. expStatusCode: http.StatusBadRequest,
  58. expHeader: http.Header{},
  59. expBody: "Users with 2FA enabled are not allowed to authenticate via username and password.",
  60. },
  61. {
  62. name: "both user and access token do not exist",
  63. header: http.Header{
  64. "Authorization": []string{"Basic dXNlcm5hbWU="},
  65. },
  66. mockUsersStore: &db.MockUsersStore{
  67. MockAuthenticate: func(username, password string, loginSourceID int64) (*db.User, error) {
  68. return nil, auth.ErrBadCredentials{}
  69. },
  70. },
  71. mockAccessTokensStore: &db.MockAccessTokensStore{
  72. MockGetBySHA: func(sha string) (*db.AccessToken, error) {
  73. return nil, db.ErrAccessTokenNotExist{}
  74. },
  75. },
  76. expStatusCode: http.StatusUnauthorized,
  77. expHeader: http.Header{
  78. "Lfs-Authenticate": []string{`Basic realm="Git LFS"`},
  79. "Content-Type": []string{"application/vnd.git-lfs+json"},
  80. },
  81. expBody: `{"message":"Credentials needed"}` + "\n",
  82. },
  83. {
  84. name: "authenticated by username and password",
  85. header: http.Header{
  86. "Authorization": []string{"Basic dXNlcm5hbWU6cGFzc3dvcmQ="},
  87. },
  88. mockUsersStore: &db.MockUsersStore{
  89. MockAuthenticate: func(username, password string, loginSourceID int64) (*db.User, error) {
  90. return &db.User{ID: 1, Name: "unknwon"}, nil
  91. },
  92. },
  93. mockTwoFactorsStore: &db.MockTwoFactorsStore{
  94. MockIsUserEnabled: func(userID int64) bool {
  95. return false
  96. },
  97. },
  98. expStatusCode: http.StatusOK,
  99. expHeader: http.Header{},
  100. expBody: "ID: 1, Name: unknwon",
  101. },
  102. {
  103. name: "authenticate by access token",
  104. header: http.Header{
  105. "Authorization": []string{"Basic dXNlcm5hbWU="},
  106. },
  107. mockUsersStore: &db.MockUsersStore{
  108. MockAuthenticate: func(username, password string, loginSourceID int64) (*db.User, error) {
  109. return nil, auth.ErrBadCredentials{}
  110. },
  111. MockGetByID: func(id int64) (*db.User, error) {
  112. return &db.User{ID: 1, Name: "unknwon"}, nil
  113. },
  114. },
  115. mockAccessTokensStore: &db.MockAccessTokensStore{
  116. MockGetBySHA: func(sha string) (*db.AccessToken, error) {
  117. return &db.AccessToken{}, nil
  118. },
  119. MockSave: func(t *db.AccessToken) error {
  120. return nil
  121. },
  122. },
  123. expStatusCode: http.StatusOK,
  124. expHeader: http.Header{},
  125. expBody: "ID: 1, Name: unknwon",
  126. },
  127. }
  128. for _, test := range tests {
  129. t.Run(test.name, func(t *testing.T) {
  130. db.SetMockUsersStore(t, test.mockUsersStore)
  131. db.SetMockTwoFactorsStore(t, test.mockTwoFactorsStore)
  132. db.SetMockAccessTokensStore(t, test.mockAccessTokensStore)
  133. r, err := http.NewRequest("GET", "/", nil)
  134. if err != nil {
  135. t.Fatal(err)
  136. }
  137. r.Header = test.header
  138. rr := httptest.NewRecorder()
  139. m.ServeHTTP(rr, r)
  140. resp := rr.Result()
  141. assert.Equal(t, test.expStatusCode, resp.StatusCode)
  142. assert.Equal(t, test.expHeader, resp.Header)
  143. body, err := ioutil.ReadAll(resp.Body)
  144. if err != nil {
  145. t.Fatal(err)
  146. }
  147. assert.Equal(t, test.expBody, string(body))
  148. })
  149. }
  150. }
  151. func Test_authorize(t *testing.T) {
  152. tests := []struct {
  153. name string
  154. authroize macaron.Handler
  155. mockUsersStore *db.MockUsersStore
  156. mockReposStore *db.MockReposStore
  157. mockPermsStore *db.MockPermsStore
  158. expStatusCode int
  159. expBody string
  160. }{
  161. {
  162. name: "user does not exist",
  163. authroize: authorize(db.AccessModeNone),
  164. mockUsersStore: &db.MockUsersStore{
  165. MockGetByUsername: func(username string) (*db.User, error) {
  166. return nil, db.ErrUserNotExist{}
  167. },
  168. },
  169. expStatusCode: http.StatusNotFound,
  170. },
  171. {
  172. name: "repository does not exist",
  173. authroize: authorize(db.AccessModeNone),
  174. mockUsersStore: &db.MockUsersStore{
  175. MockGetByUsername: func(username string) (*db.User, error) {
  176. return &db.User{Name: username}, nil
  177. },
  178. },
  179. mockReposStore: &db.MockReposStore{
  180. MockGetByName: func(ownerID int64, name string) (*db.Repository, error) {
  181. return nil, db.ErrRepoNotExist{}
  182. },
  183. },
  184. expStatusCode: http.StatusNotFound,
  185. },
  186. {
  187. name: "actor is not authorized",
  188. authroize: authorize(db.AccessModeWrite),
  189. mockUsersStore: &db.MockUsersStore{
  190. MockGetByUsername: func(username string) (*db.User, error) {
  191. return &db.User{Name: username}, nil
  192. },
  193. },
  194. mockReposStore: &db.MockReposStore{
  195. MockGetByName: func(ownerID int64, name string) (*db.Repository, error) {
  196. return &db.Repository{Name: name}, nil
  197. },
  198. },
  199. mockPermsStore: &db.MockPermsStore{
  200. MockAuthorize: func(userID, repoID int64, desired db.AccessMode, opts db.AccessModeOptions) bool {
  201. return desired <= db.AccessModeRead
  202. },
  203. },
  204. expStatusCode: http.StatusNotFound,
  205. },
  206. {
  207. name: "actor is authorized",
  208. authroize: authorize(db.AccessModeRead),
  209. mockUsersStore: &db.MockUsersStore{
  210. MockGetByUsername: func(username string) (*db.User, error) {
  211. return &db.User{Name: username}, nil
  212. },
  213. },
  214. mockReposStore: &db.MockReposStore{
  215. MockGetByName: func(ownerID int64, name string) (*db.Repository, error) {
  216. return &db.Repository{Name: name}, nil
  217. },
  218. },
  219. mockPermsStore: &db.MockPermsStore{
  220. MockAuthorize: func(userID, repoID int64, desired db.AccessMode, opts db.AccessModeOptions) bool {
  221. return desired <= db.AccessModeRead
  222. },
  223. },
  224. expStatusCode: http.StatusOK,
  225. expBody: "owner.Name: owner, repo.Name: repo",
  226. },
  227. }
  228. for _, test := range tests {
  229. t.Run(test.name, func(t *testing.T) {
  230. db.SetMockUsersStore(t, test.mockUsersStore)
  231. db.SetMockReposStore(t, test.mockReposStore)
  232. db.SetMockPermsStore(t, test.mockPermsStore)
  233. m := macaron.New()
  234. m.Use(macaron.Renderer())
  235. m.Use(func(c *macaron.Context) {
  236. c.Map(&db.User{})
  237. })
  238. m.Get("/:username/:reponame", test.authroize, func(w http.ResponseWriter, owner *db.User, repo *db.Repository) {
  239. fmt.Fprintf(w, "owner.Name: %s, repo.Name: %s", owner.Name, repo.Name)
  240. })
  241. r, err := http.NewRequest("GET", "/owner/repo", nil)
  242. if err != nil {
  243. t.Fatal(err)
  244. }
  245. rr := httptest.NewRecorder()
  246. m.ServeHTTP(rr, r)
  247. resp := rr.Result()
  248. assert.Equal(t, test.expStatusCode, resp.StatusCode)
  249. body, err := ioutil.ReadAll(resp.Body)
  250. if err != nil {
  251. t.Fatal(err)
  252. }
  253. assert.Equal(t, test.expBody, string(body))
  254. })
  255. }
  256. }
  257. func Test_verifyHeader(t *testing.T) {
  258. tests := []struct {
  259. name string
  260. verifyHeader macaron.Handler
  261. header http.Header
  262. expStatusCode int
  263. }{
  264. {
  265. name: "header not found",
  266. verifyHeader: verifyHeader("Accept", contentType, http.StatusNotAcceptable),
  267. expStatusCode: http.StatusNotAcceptable,
  268. },
  269. {
  270. name: "header found",
  271. verifyHeader: verifyHeader("Accept", "application/vnd.git-lfs+json", http.StatusNotAcceptable),
  272. header: http.Header{
  273. "Accept": []string{"application/vnd.git-lfs+json; charset=utf-8"},
  274. },
  275. expStatusCode: http.StatusOK,
  276. },
  277. }
  278. for _, test := range tests {
  279. t.Run(test.name, func(t *testing.T) {
  280. m := macaron.New()
  281. m.Use(macaron.Renderer())
  282. m.Get("/", test.verifyHeader)
  283. r, err := http.NewRequest("GET", "/", nil)
  284. if err != nil {
  285. t.Fatal(err)
  286. }
  287. r.Header = test.header
  288. rr := httptest.NewRecorder()
  289. m.ServeHTTP(rr, r)
  290. resp := rr.Result()
  291. assert.Equal(t, test.expStatusCode, resp.StatusCode)
  292. })
  293. }
  294. }
  295. func Test_verifyOID(t *testing.T) {
  296. m := macaron.New()
  297. m.Get("/:oid", verifyOID(), func(w http.ResponseWriter, oid lfsutil.OID) {
  298. fmt.Fprintf(w, "oid: %s", oid)
  299. })
  300. tests := []struct {
  301. name string
  302. url string
  303. expStatusCode int
  304. expBody string
  305. }{
  306. {
  307. name: "bad oid",
  308. url: "/bad_oid",
  309. expStatusCode: http.StatusBadRequest,
  310. expBody: `{"message":"Invalid oid"}` + "\n",
  311. },
  312. {
  313. name: "good oid",
  314. url: "/ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
  315. expStatusCode: http.StatusOK,
  316. expBody: "oid: ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
  317. },
  318. }
  319. for _, test := range tests {
  320. t.Run(test.name, func(t *testing.T) {
  321. r, err := http.NewRequest("GET", test.url, nil)
  322. if err != nil {
  323. t.Fatal(err)
  324. }
  325. rr := httptest.NewRecorder()
  326. m.ServeHTTP(rr, r)
  327. resp := rr.Result()
  328. assert.Equal(t, test.expStatusCode, resp.StatusCode)
  329. body, err := ioutil.ReadAll(resp.Body)
  330. if err != nil {
  331. t.Fatal(err)
  332. }
  333. assert.Equal(t, test.expBody, string(body))
  334. })
  335. }
  336. }
  337. func Test_internalServerError(t *testing.T) {
  338. rr := httptest.NewRecorder()
  339. internalServerError(rr)
  340. resp := rr.Result()
  341. assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
  342. body, err := ioutil.ReadAll(resp.Body)
  343. if err != nil {
  344. t.Fatal(err)
  345. }
  346. assert.Equal(t, `{"message":"Internal server error"}`+"\n", string(body))
  347. }