PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/registry/api/v2/routes_test.go

https://gitlab.com/vectorci/cf-distribution
Go | 355 lines | 282 code | 33 blank | 40 comment | 27 complexity | 03244c96e4761f3b02b17a0585c92e10 MD5 | raw file
  1. package v2
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math/rand"
  6. "net/http"
  7. "net/http/httptest"
  8. "reflect"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/gorilla/mux"
  13. )
  14. type routeTestCase struct {
  15. RequestURI string
  16. ExpectedURI string
  17. Vars map[string]string
  18. RouteName string
  19. StatusCode int
  20. }
  21. // TestRouter registers a test handler with all the routes and ensures that
  22. // each route returns the expected path variables. Not method verification is
  23. // present. This not meant to be exhaustive but as check to ensure that the
  24. // expected variables are extracted.
  25. //
  26. // This may go away as the application structure comes together.
  27. func TestRouter(t *testing.T) {
  28. testCases := []routeTestCase{
  29. {
  30. RouteName: RouteNameBase,
  31. RequestURI: "/v2/",
  32. Vars: map[string]string{},
  33. },
  34. {
  35. RouteName: RouteNameManifest,
  36. RequestURI: "/v2/foo/manifests/bar",
  37. Vars: map[string]string{
  38. "name": "foo",
  39. "reference": "bar",
  40. },
  41. },
  42. {
  43. RouteName: RouteNameManifest,
  44. RequestURI: "/v2/foo/bar/manifests/tag",
  45. Vars: map[string]string{
  46. "name": "foo/bar",
  47. "reference": "tag",
  48. },
  49. },
  50. {
  51. RouteName: RouteNameManifest,
  52. RequestURI: "/v2/foo/bar/manifests/sha256:abcdef01234567890",
  53. Vars: map[string]string{
  54. "name": "foo/bar",
  55. "reference": "sha256:abcdef01234567890",
  56. },
  57. },
  58. {
  59. RouteName: RouteNameTags,
  60. RequestURI: "/v2/foo/bar/tags/list",
  61. Vars: map[string]string{
  62. "name": "foo/bar",
  63. },
  64. },
  65. {
  66. RouteName: RouteNameTags,
  67. RequestURI: "/v2/docker.com/foo/tags/list",
  68. Vars: map[string]string{
  69. "name": "docker.com/foo",
  70. },
  71. },
  72. {
  73. RouteName: RouteNameTags,
  74. RequestURI: "/v2/docker.com/foo/bar/tags/list",
  75. Vars: map[string]string{
  76. "name": "docker.com/foo/bar",
  77. },
  78. },
  79. {
  80. RouteName: RouteNameTags,
  81. RequestURI: "/v2/docker.com/foo/bar/baz/tags/list",
  82. Vars: map[string]string{
  83. "name": "docker.com/foo/bar/baz",
  84. },
  85. },
  86. {
  87. RouteName: RouteNameBlob,
  88. RequestURI: "/v2/foo/bar/blobs/tarsum.dev+foo:abcdef0919234",
  89. Vars: map[string]string{
  90. "name": "foo/bar",
  91. "digest": "tarsum.dev+foo:abcdef0919234",
  92. },
  93. },
  94. {
  95. RouteName: RouteNameBlob,
  96. RequestURI: "/v2/foo/bar/blobs/sha256:abcdef0919234",
  97. Vars: map[string]string{
  98. "name": "foo/bar",
  99. "digest": "sha256:abcdef0919234",
  100. },
  101. },
  102. {
  103. RouteName: RouteNameBlobUpload,
  104. RequestURI: "/v2/foo/bar/blobs/uploads/",
  105. Vars: map[string]string{
  106. "name": "foo/bar",
  107. },
  108. },
  109. {
  110. RouteName: RouteNameBlobUploadChunk,
  111. RequestURI: "/v2/foo/bar/blobs/uploads/uuid",
  112. Vars: map[string]string{
  113. "name": "foo/bar",
  114. "uuid": "uuid",
  115. },
  116. },
  117. {
  118. // support uuid proper
  119. RouteName: RouteNameBlobUploadChunk,
  120. RequestURI: "/v2/foo/bar/blobs/uploads/D95306FA-FAD3-4E36-8D41-CF1C93EF8286",
  121. Vars: map[string]string{
  122. "name": "foo/bar",
  123. "uuid": "D95306FA-FAD3-4E36-8D41-CF1C93EF8286",
  124. },
  125. },
  126. {
  127. RouteName: RouteNameBlobUploadChunk,
  128. RequestURI: "/v2/foo/bar/blobs/uploads/RDk1MzA2RkEtRkFEMy00RTM2LThENDEtQ0YxQzkzRUY4Mjg2IA==",
  129. Vars: map[string]string{
  130. "name": "foo/bar",
  131. "uuid": "RDk1MzA2RkEtRkFEMy00RTM2LThENDEtQ0YxQzkzRUY4Mjg2IA==",
  132. },
  133. },
  134. {
  135. // supports urlsafe base64
  136. RouteName: RouteNameBlobUploadChunk,
  137. RequestURI: "/v2/foo/bar/blobs/uploads/RDk1MzA2RkEtRkFEMy00RTM2LThENDEtQ0YxQzkzRUY4Mjg2IA_-==",
  138. Vars: map[string]string{
  139. "name": "foo/bar",
  140. "uuid": "RDk1MzA2RkEtRkFEMy00RTM2LThENDEtQ0YxQzkzRUY4Mjg2IA_-==",
  141. },
  142. },
  143. {
  144. // does not match
  145. RouteName: RouteNameBlobUploadChunk,
  146. RequestURI: "/v2/foo/bar/blobs/uploads/totalandcompletejunk++$$-==",
  147. StatusCode: http.StatusNotFound,
  148. },
  149. {
  150. // Check ambiguity: ensure we can distinguish between tags for
  151. // "foo/bar/image/image" and image for "foo/bar/image" with tag
  152. // "tags"
  153. RouteName: RouteNameManifest,
  154. RequestURI: "/v2/foo/bar/manifests/manifests/tags",
  155. Vars: map[string]string{
  156. "name": "foo/bar/manifests",
  157. "reference": "tags",
  158. },
  159. },
  160. {
  161. // This case presents an ambiguity between foo/bar with tag="tags"
  162. // and list tags for "foo/bar/manifest"
  163. RouteName: RouteNameTags,
  164. RequestURI: "/v2/foo/bar/manifests/tags/list",
  165. Vars: map[string]string{
  166. "name": "foo/bar/manifests",
  167. },
  168. },
  169. }
  170. checkTestRouter(t, testCases, "", true)
  171. checkTestRouter(t, testCases, "/prefix/", true)
  172. }
  173. func TestRouterWithPathTraversals(t *testing.T) {
  174. testCases := []routeTestCase{
  175. {
  176. RouteName: RouteNameBlobUploadChunk,
  177. RequestURI: "/v2/foo/../../blob/uploads/D95306FA-FAD3-4E36-8D41-CF1C93EF8286",
  178. ExpectedURI: "/blob/uploads/D95306FA-FAD3-4E36-8D41-CF1C93EF8286",
  179. StatusCode: http.StatusNotFound,
  180. },
  181. {
  182. // Testing for path traversal attack handling
  183. RouteName: RouteNameTags,
  184. RequestURI: "/v2/foo/../bar/baz/tags/list",
  185. ExpectedURI: "/v2/bar/baz/tags/list",
  186. Vars: map[string]string{
  187. "name": "bar/baz",
  188. },
  189. },
  190. }
  191. checkTestRouter(t, testCases, "", false)
  192. }
  193. func TestRouterWithBadCharacters(t *testing.T) {
  194. if testing.Short() {
  195. testCases := []routeTestCase{
  196. {
  197. RouteName: RouteNameBlobUploadChunk,
  198. RequestURI: "/v2/foo/blob/uploads/不95306FA-FAD3-4E36-8D41-CF1C93EF8286",
  199. StatusCode: http.StatusNotFound,
  200. },
  201. {
  202. // Testing for path traversal attack handling
  203. RouteName: RouteNameTags,
  204. RequestURI: "/v2/foo/不bar/tags/list",
  205. StatusCode: http.StatusNotFound,
  206. },
  207. }
  208. checkTestRouter(t, testCases, "", true)
  209. } else {
  210. // in the long version we're going to fuzz the router
  211. // with random UTF8 characters not in the 128 bit ASCII range.
  212. // These are not valid characters for the router and we expect
  213. // 404s on every test.
  214. rand.Seed(time.Now().UTC().UnixNano())
  215. testCases := make([]routeTestCase, 1000)
  216. for idx := range testCases {
  217. testCases[idx] = routeTestCase{
  218. RouteName: RouteNameTags,
  219. RequestURI: fmt.Sprintf("/v2/%v/%v/tags/list", randomString(10), randomString(10)),
  220. StatusCode: http.StatusNotFound,
  221. }
  222. }
  223. checkTestRouter(t, testCases, "", true)
  224. }
  225. }
  226. func checkTestRouter(t *testing.T, testCases []routeTestCase, prefix string, deeplyEqual bool) {
  227. router := RouterWithPrefix(prefix)
  228. testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  229. testCase := routeTestCase{
  230. RequestURI: r.RequestURI,
  231. Vars: mux.Vars(r),
  232. RouteName: mux.CurrentRoute(r).GetName(),
  233. }
  234. enc := json.NewEncoder(w)
  235. if err := enc.Encode(testCase); err != nil {
  236. http.Error(w, err.Error(), http.StatusInternalServerError)
  237. return
  238. }
  239. })
  240. // Startup test server
  241. server := httptest.NewServer(router)
  242. for _, testcase := range testCases {
  243. testcase.RequestURI = strings.TrimSuffix(prefix, "/") + testcase.RequestURI
  244. // Register the endpoint
  245. route := router.GetRoute(testcase.RouteName)
  246. if route == nil {
  247. t.Fatalf("route for name %q not found", testcase.RouteName)
  248. }
  249. route.Handler(testHandler)
  250. u := server.URL + testcase.RequestURI
  251. resp, err := http.Get(u)
  252. if err != nil {
  253. t.Fatalf("error issuing get request: %v", err)
  254. }
  255. if testcase.StatusCode == 0 {
  256. // Override default, zero-value
  257. testcase.StatusCode = http.StatusOK
  258. }
  259. if testcase.ExpectedURI == "" {
  260. // Override default, zero-value
  261. testcase.ExpectedURI = testcase.RequestURI
  262. }
  263. if resp.StatusCode != testcase.StatusCode {
  264. t.Fatalf("unexpected status for %s: %v %v", u, resp.Status, resp.StatusCode)
  265. }
  266. if testcase.StatusCode != http.StatusOK {
  267. resp.Body.Close()
  268. // We don't care about json response.
  269. continue
  270. }
  271. dec := json.NewDecoder(resp.Body)
  272. var actualRouteInfo routeTestCase
  273. if err := dec.Decode(&actualRouteInfo); err != nil {
  274. t.Fatalf("error reading json response: %v", err)
  275. }
  276. // Needs to be set out of band
  277. actualRouteInfo.StatusCode = resp.StatusCode
  278. if actualRouteInfo.RequestURI != testcase.ExpectedURI {
  279. t.Fatalf("URI %v incorrectly parsed, expected %v", actualRouteInfo.RequestURI, testcase.ExpectedURI)
  280. }
  281. if actualRouteInfo.RouteName != testcase.RouteName {
  282. t.Fatalf("incorrect route %q matched, expected %q", actualRouteInfo.RouteName, testcase.RouteName)
  283. }
  284. // when testing deep equality, the actualRouteInfo has an empty ExpectedURI, we don't want
  285. // that to make the comparison fail. We're otherwise done with the testcase so empty the
  286. // testcase.ExpectedURI
  287. testcase.ExpectedURI = ""
  288. if deeplyEqual && !reflect.DeepEqual(actualRouteInfo, testcase) {
  289. t.Fatalf("actual does not equal expected: %#v != %#v", actualRouteInfo, testcase)
  290. }
  291. resp.Body.Close()
  292. }
  293. }
  294. // -------------- START LICENSED CODE --------------
  295. // The following code is derivative of https://github.com/google/gofuzz
  296. // gofuzz is licensed under the Apache License, Version 2.0, January 2004,
  297. // a copy of which can be found in the LICENSE file at the root of this
  298. // repository.
  299. // These functions allow us to generate strings containing only multibyte
  300. // characters that are invalid in our URLs. They are used above for fuzzing
  301. // to ensure we always get 404s on these invalid strings
  302. type charRange struct {
  303. first, last rune
  304. }
  305. // choose returns a random unicode character from the given range, using the
  306. // given randomness source.
  307. func (r *charRange) choose() rune {
  308. count := int64(r.last - r.first)
  309. return r.first + rune(rand.Int63n(count))
  310. }
  311. var unicodeRanges = []charRange{
  312. {'\u00a0', '\u02af'}, // Multi-byte encoded characters
  313. {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings)
  314. }
  315. func randomString(length int) string {
  316. runes := make([]rune, length)
  317. for i := range runes {
  318. runes[i] = unicodeRanges[rand.Intn(len(unicodeRanges))].choose()
  319. }
  320. return string(runes)
  321. }
  322. // -------------- END LICENSED CODE --------------