registry_mock_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. package registry
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/docker/docker/reference"
  17. registrytypes "github.com/docker/engine-api/types/registry"
  18. "github.com/gorilla/mux"
  19. "github.com/Sirupsen/logrus"
  20. )
  21. var (
  22. testHTTPServer *httptest.Server
  23. testHTTPSServer *httptest.Server
  24. testLayers = map[string]map[string]string{
  25. "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20": {
  26. "json": `{"id":"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20",
  27. "comment":"test base image","created":"2013-03-23T12:53:11.10432-07:00",
  28. "container_config":{"Hostname":"","User":"","Memory":0,"MemorySwap":0,
  29. "CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,
  30. "Tty":false,"OpenStdin":false,"StdinOnce":false,
  31. "Env":null,"Cmd":null,"Dns":null,"Image":"","Volumes":null,
  32. "VolumesFrom":"","Entrypoint":null},"Size":424242}`,
  33. "checksum_simple": "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37",
  34. "checksum_tarsum": "tarsum+sha256:4409a0685741ca86d38df878ed6f8cbba4c99de5dc73cd71aef04be3bb70be7c",
  35. "ancestry": `["77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20"]`,
  36. "layer": string([]byte{
  37. 0x1f, 0x8b, 0x08, 0x08, 0x0e, 0xb0, 0xee, 0x51, 0x02, 0x03, 0x6c, 0x61, 0x79, 0x65,
  38. 0x72, 0x2e, 0x74, 0x61, 0x72, 0x00, 0xed, 0xd2, 0x31, 0x0e, 0xc2, 0x30, 0x0c, 0x05,
  39. 0x50, 0xcf, 0x9c, 0xc2, 0x27, 0x48, 0xed, 0x38, 0x4e, 0xce, 0x13, 0x44, 0x2b, 0x66,
  40. 0x62, 0x24, 0x8e, 0x4f, 0xa0, 0x15, 0x63, 0xb6, 0x20, 0x21, 0xfc, 0x96, 0xbf, 0x78,
  41. 0xb0, 0xf5, 0x1d, 0x16, 0x98, 0x8e, 0x88, 0x8a, 0x2a, 0xbe, 0x33, 0xef, 0x49, 0x31,
  42. 0xed, 0x79, 0x40, 0x8e, 0x5c, 0x44, 0x85, 0x88, 0x33, 0x12, 0x73, 0x2c, 0x02, 0xa8,
  43. 0xf0, 0x05, 0xf7, 0x66, 0xf5, 0xd6, 0x57, 0x69, 0xd7, 0x7a, 0x19, 0xcd, 0xf5, 0xb1,
  44. 0x6d, 0x1b, 0x1f, 0xf9, 0xba, 0xe3, 0x93, 0x3f, 0x22, 0x2c, 0xb6, 0x36, 0x0b, 0xf6,
  45. 0xb0, 0xa9, 0xfd, 0xe7, 0x94, 0x46, 0xfd, 0xeb, 0xd1, 0x7f, 0x2c, 0xc4, 0xd2, 0xfb,
  46. 0x97, 0xfe, 0x02, 0x80, 0xe4, 0xfd, 0x4f, 0x77, 0xae, 0x6d, 0x3d, 0x81, 0x73, 0xce,
  47. 0xb9, 0x7f, 0xf3, 0x04, 0x41, 0xc1, 0xab, 0xc6, 0x00, 0x0a, 0x00, 0x00,
  48. }),
  49. },
  50. "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d": {
  51. "json": `{"id":"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
  52. "parent":"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20",
  53. "comment":"test base image","created":"2013-03-23T12:55:11.10432-07:00",
  54. "container_config":{"Hostname":"","User":"","Memory":0,"MemorySwap":0,
  55. "CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,
  56. "Tty":false,"OpenStdin":false,"StdinOnce":false,
  57. "Env":null,"Cmd":null,"Dns":null,"Image":"","Volumes":null,
  58. "VolumesFrom":"","Entrypoint":null},"Size":424242}`,
  59. "checksum_simple": "sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2",
  60. "checksum_tarsum": "tarsum+sha256:68fdb56fb364f074eec2c9b3f85ca175329c4dcabc4a6a452b7272aa613a07a2",
  61. "ancestry": `["42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
  62. "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20"]`,
  63. "layer": string([]byte{
  64. 0x1f, 0x8b, 0x08, 0x08, 0xbd, 0xb3, 0xee, 0x51, 0x02, 0x03, 0x6c, 0x61, 0x79, 0x65,
  65. 0x72, 0x2e, 0x74, 0x61, 0x72, 0x00, 0xed, 0xd1, 0x31, 0x0e, 0xc2, 0x30, 0x0c, 0x05,
  66. 0x50, 0xcf, 0x9c, 0xc2, 0x27, 0x48, 0x9d, 0x38, 0x8e, 0xcf, 0x53, 0x51, 0xaa, 0x56,
  67. 0xea, 0x44, 0x82, 0xc4, 0xf1, 0x09, 0xb4, 0xea, 0x98, 0x2d, 0x48, 0x08, 0xbf, 0xe5,
  68. 0x2f, 0x1e, 0xfc, 0xf5, 0xdd, 0x00, 0xdd, 0x11, 0x91, 0x8a, 0xe0, 0x27, 0xd3, 0x9e,
  69. 0x14, 0xe2, 0x9e, 0x07, 0xf4, 0xc1, 0x2b, 0x0b, 0xfb, 0xa4, 0x82, 0xe4, 0x3d, 0x93,
  70. 0x02, 0x0a, 0x7c, 0xc1, 0x23, 0x97, 0xf1, 0x5e, 0x5f, 0xc9, 0xcb, 0x38, 0xb5, 0xee,
  71. 0xea, 0xd9, 0x3c, 0xb7, 0x4b, 0xbe, 0x7b, 0x9c, 0xf9, 0x23, 0xdc, 0x50, 0x6e, 0xb9,
  72. 0xb8, 0xf2, 0x2c, 0x5d, 0xf7, 0x4f, 0x31, 0xb6, 0xf6, 0x4f, 0xc7, 0xfe, 0x41, 0x55,
  73. 0x63, 0xdd, 0x9f, 0x89, 0x09, 0x90, 0x6c, 0xff, 0xee, 0xae, 0xcb, 0xba, 0x4d, 0x17,
  74. 0x30, 0xc6, 0x18, 0xf3, 0x67, 0x5e, 0xc1, 0xed, 0x21, 0x5d, 0x00, 0x0a, 0x00, 0x00,
  75. }),
  76. },
  77. }
  78. testRepositories = map[string]map[string]string{
  79. "foo42/bar": {
  80. "latest": "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
  81. "test": "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
  82. },
  83. }
  84. mockHosts = map[string][]net.IP{
  85. "": {net.ParseIP("0.0.0.0")},
  86. "localhost": {net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
  87. "example.com": {net.ParseIP("42.42.42.42")},
  88. "other.com": {net.ParseIP("43.43.43.43")},
  89. }
  90. )
  91. func init() {
  92. r := mux.NewRouter()
  93. // /v1/
  94. r.HandleFunc("/v1/_ping", handlerGetPing).Methods("GET")
  95. r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|ancestry}", handlerGetImage).Methods("GET")
  96. r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|checksum}", handlerPutImage).Methods("PUT")
  97. r.HandleFunc("/v1/repositories/{repository:.+}/tags", handlerGetDeleteTags).Methods("GET", "DELETE")
  98. r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerGetTag).Methods("GET")
  99. r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerPutTag).Methods("PUT")
  100. r.HandleFunc("/v1/users{null:.*}", handlerUsers).Methods("GET", "POST", "PUT")
  101. r.HandleFunc("/v1/repositories/{repository:.+}{action:/images|/}", handlerImages).Methods("GET", "PUT", "DELETE")
  102. r.HandleFunc("/v1/repositories/{repository:.+}/auth", handlerAuth).Methods("PUT")
  103. r.HandleFunc("/v1/search", handlerSearch).Methods("GET")
  104. // /v2/
  105. r.HandleFunc("/v2/version", handlerGetPing).Methods("GET")
  106. testHTTPServer = httptest.NewServer(handlerAccessLog(r))
  107. testHTTPSServer = httptest.NewTLSServer(handlerAccessLog(r))
  108. // override net.LookupIP
  109. lookupIP = func(host string) ([]net.IP, error) {
  110. if host == "127.0.0.1" {
  111. // I believe in future Go versions this will fail, so let's fix it later
  112. return net.LookupIP(host)
  113. }
  114. for h, addrs := range mockHosts {
  115. if host == h {
  116. return addrs, nil
  117. }
  118. for _, addr := range addrs {
  119. if addr.String() == host {
  120. return []net.IP{addr}, nil
  121. }
  122. }
  123. }
  124. return nil, errors.New("lookup: no such host")
  125. }
  126. }
  127. func handlerAccessLog(handler http.Handler) http.Handler {
  128. logHandler := func(w http.ResponseWriter, r *http.Request) {
  129. logrus.Debugf("%s \"%s %s\"", r.RemoteAddr, r.Method, r.URL)
  130. handler.ServeHTTP(w, r)
  131. }
  132. return http.HandlerFunc(logHandler)
  133. }
  134. func makeURL(req string) string {
  135. return testHTTPServer.URL + req
  136. }
  137. func makeHTTPSURL(req string) string {
  138. return testHTTPSServer.URL + req
  139. }
  140. func makeIndex(req string) *registrytypes.IndexInfo {
  141. index := &registrytypes.IndexInfo{
  142. Name: makeURL(req),
  143. }
  144. return index
  145. }
  146. func makeHTTPSIndex(req string) *registrytypes.IndexInfo {
  147. index := &registrytypes.IndexInfo{
  148. Name: makeHTTPSURL(req),
  149. }
  150. return index
  151. }
  152. func makePublicIndex() *registrytypes.IndexInfo {
  153. index := &registrytypes.IndexInfo{
  154. Name: IndexServer,
  155. Secure: true,
  156. Official: true,
  157. }
  158. return index
  159. }
  160. func makeServiceConfig(mirrors []string, insecureRegistries []string) *serviceConfig {
  161. options := ServiceOptions{
  162. Mirrors: mirrors,
  163. InsecureRegistries: insecureRegistries,
  164. }
  165. return newServiceConfig(options)
  166. }
  167. func writeHeaders(w http.ResponseWriter) {
  168. h := w.Header()
  169. h.Add("Server", "docker-tests/mock")
  170. h.Add("Expires", "-1")
  171. h.Add("Content-Type", "application/json")
  172. h.Add("Pragma", "no-cache")
  173. h.Add("Cache-Control", "no-cache")
  174. h.Add("X-Docker-Registry-Version", "0.0.0")
  175. h.Add("X-Docker-Registry-Config", "mock")
  176. }
  177. func writeResponse(w http.ResponseWriter, message interface{}, code int) {
  178. writeHeaders(w)
  179. w.WriteHeader(code)
  180. body, err := json.Marshal(message)
  181. if err != nil {
  182. io.WriteString(w, err.Error())
  183. return
  184. }
  185. w.Write(body)
  186. }
  187. func readJSON(r *http.Request, dest interface{}) error {
  188. body, err := ioutil.ReadAll(r.Body)
  189. if err != nil {
  190. return err
  191. }
  192. return json.Unmarshal(body, dest)
  193. }
  194. func apiError(w http.ResponseWriter, message string, code int) {
  195. body := map[string]string{
  196. "error": message,
  197. }
  198. writeResponse(w, body, code)
  199. }
  200. func assertEqual(t *testing.T, a interface{}, b interface{}, message string) {
  201. if a == b {
  202. return
  203. }
  204. if len(message) == 0 {
  205. message = fmt.Sprintf("%v != %v", a, b)
  206. }
  207. t.Fatal(message)
  208. }
  209. func assertNotEqual(t *testing.T, a interface{}, b interface{}, message string) {
  210. if a != b {
  211. return
  212. }
  213. if len(message) == 0 {
  214. message = fmt.Sprintf("%v == %v", a, b)
  215. }
  216. t.Fatal(message)
  217. }
  218. // Similar to assertEqual, but does not stop test
  219. func checkEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) {
  220. if a == b {
  221. return
  222. }
  223. message := fmt.Sprintf("%v != %v", a, b)
  224. if len(messagePrefix) != 0 {
  225. message = messagePrefix + ": " + message
  226. }
  227. t.Error(message)
  228. }
  229. // Similar to assertNotEqual, but does not stop test
  230. func checkNotEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) {
  231. if a != b {
  232. return
  233. }
  234. message := fmt.Sprintf("%v == %v", a, b)
  235. if len(messagePrefix) != 0 {
  236. message = messagePrefix + ": " + message
  237. }
  238. t.Error(message)
  239. }
  240. func requiresAuth(w http.ResponseWriter, r *http.Request) bool {
  241. writeCookie := func() {
  242. value := fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano())
  243. cookie := &http.Cookie{Name: "session", Value: value, MaxAge: 3600}
  244. http.SetCookie(w, cookie)
  245. //FIXME(sam): this should be sent only on Index routes
  246. value = fmt.Sprintf("FAKE-TOKEN-%d", time.Now().UnixNano())
  247. w.Header().Add("X-Docker-Token", value)
  248. }
  249. if len(r.Cookies()) > 0 {
  250. writeCookie()
  251. return true
  252. }
  253. if len(r.Header.Get("Authorization")) > 0 {
  254. writeCookie()
  255. return true
  256. }
  257. w.Header().Add("WWW-Authenticate", "token")
  258. apiError(w, "Wrong auth", 401)
  259. return false
  260. }
  261. func handlerGetPing(w http.ResponseWriter, r *http.Request) {
  262. writeResponse(w, true, 200)
  263. }
  264. func handlerGetImage(w http.ResponseWriter, r *http.Request) {
  265. if !requiresAuth(w, r) {
  266. return
  267. }
  268. vars := mux.Vars(r)
  269. layer, exists := testLayers[vars["image_id"]]
  270. if !exists {
  271. http.NotFound(w, r)
  272. return
  273. }
  274. writeHeaders(w)
  275. layerSize := len(layer["layer"])
  276. w.Header().Add("X-Docker-Size", strconv.Itoa(layerSize))
  277. io.WriteString(w, layer[vars["action"]])
  278. }
  279. func handlerPutImage(w http.ResponseWriter, r *http.Request) {
  280. if !requiresAuth(w, r) {
  281. return
  282. }
  283. vars := mux.Vars(r)
  284. imageID := vars["image_id"]
  285. action := vars["action"]
  286. layer, exists := testLayers[imageID]
  287. if !exists {
  288. if action != "json" {
  289. http.NotFound(w, r)
  290. return
  291. }
  292. layer = make(map[string]string)
  293. testLayers[imageID] = layer
  294. }
  295. if checksum := r.Header.Get("X-Docker-Checksum"); checksum != "" {
  296. if checksum != layer["checksum_simple"] && checksum != layer["checksum_tarsum"] {
  297. apiError(w, "Wrong checksum", 400)
  298. return
  299. }
  300. }
  301. body, err := ioutil.ReadAll(r.Body)
  302. if err != nil {
  303. apiError(w, fmt.Sprintf("Error: %s", err), 500)
  304. return
  305. }
  306. layer[action] = string(body)
  307. writeResponse(w, true, 200)
  308. }
  309. func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) {
  310. if !requiresAuth(w, r) {
  311. return
  312. }
  313. repositoryName, err := reference.WithName(mux.Vars(r)["repository"])
  314. if err != nil {
  315. apiError(w, "Could not parse repository", 400)
  316. return
  317. }
  318. tags, exists := testRepositories[repositoryName.String()]
  319. if !exists {
  320. apiError(w, "Repository not found", 404)
  321. return
  322. }
  323. if r.Method == "DELETE" {
  324. delete(testRepositories, repositoryName.String())
  325. writeResponse(w, true, 200)
  326. return
  327. }
  328. writeResponse(w, tags, 200)
  329. }
  330. func handlerGetTag(w http.ResponseWriter, r *http.Request) {
  331. if !requiresAuth(w, r) {
  332. return
  333. }
  334. vars := mux.Vars(r)
  335. repositoryName, err := reference.WithName(vars["repository"])
  336. if err != nil {
  337. apiError(w, "Could not parse repository", 400)
  338. return
  339. }
  340. tagName := vars["tag"]
  341. tags, exists := testRepositories[repositoryName.String()]
  342. if !exists {
  343. apiError(w, "Repository not found", 404)
  344. return
  345. }
  346. tag, exists := tags[tagName]
  347. if !exists {
  348. apiError(w, "Tag not found", 404)
  349. return
  350. }
  351. writeResponse(w, tag, 200)
  352. }
  353. func handlerPutTag(w http.ResponseWriter, r *http.Request) {
  354. if !requiresAuth(w, r) {
  355. return
  356. }
  357. vars := mux.Vars(r)
  358. repositoryName, err := reference.WithName(vars["repository"])
  359. if err != nil {
  360. apiError(w, "Could not parse repository", 400)
  361. return
  362. }
  363. tagName := vars["tag"]
  364. tags, exists := testRepositories[repositoryName.String()]
  365. if !exists {
  366. tags = make(map[string]string)
  367. testRepositories[repositoryName.String()] = tags
  368. }
  369. tagValue := ""
  370. readJSON(r, tagValue)
  371. tags[tagName] = tagValue
  372. writeResponse(w, true, 200)
  373. }
  374. func handlerUsers(w http.ResponseWriter, r *http.Request) {
  375. code := 200
  376. if r.Method == "POST" {
  377. code = 201
  378. } else if r.Method == "PUT" {
  379. code = 204
  380. }
  381. writeResponse(w, "", code)
  382. }
  383. func handlerImages(w http.ResponseWriter, r *http.Request) {
  384. u, _ := url.Parse(testHTTPServer.URL)
  385. w.Header().Add("X-Docker-Endpoints", fmt.Sprintf("%s , %s ", u.Host, "test.example.com"))
  386. w.Header().Add("X-Docker-Token", fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano()))
  387. if r.Method == "PUT" {
  388. if strings.HasSuffix(r.URL.Path, "images") {
  389. writeResponse(w, "", 204)
  390. return
  391. }
  392. writeResponse(w, "", 200)
  393. return
  394. }
  395. if r.Method == "DELETE" {
  396. writeResponse(w, "", 204)
  397. return
  398. }
  399. images := []map[string]string{}
  400. for imageID, layer := range testLayers {
  401. image := make(map[string]string)
  402. image["id"] = imageID
  403. image["checksum"] = layer["checksum_tarsum"]
  404. image["Tag"] = "latest"
  405. images = append(images, image)
  406. }
  407. writeResponse(w, images, 200)
  408. }
  409. func handlerAuth(w http.ResponseWriter, r *http.Request) {
  410. writeResponse(w, "OK", 200)
  411. }
  412. func handlerSearch(w http.ResponseWriter, r *http.Request) {
  413. result := &registrytypes.SearchResults{
  414. Query: "fakequery",
  415. NumResults: 1,
  416. Results: []registrytypes.SearchResult{{Name: "fakeimage", StarCount: 42}},
  417. }
  418. writeResponse(w, result, 200)
  419. }
  420. func TestPing(t *testing.T) {
  421. res, err := http.Get(makeURL("/v1/_ping"))
  422. if err != nil {
  423. t.Fatal(err)
  424. }
  425. assertEqual(t, res.StatusCode, 200, "")
  426. assertEqual(t, res.Header.Get("X-Docker-Registry-Config"), "mock",
  427. "This is not a Mocked Registry")
  428. }
  429. /* Uncomment this to test Mocked Registry locally with curl
  430. * WARNING: Don't push on the repos uncommented, it'll block the tests
  431. *
  432. func TestWait(t *testing.T) {
  433. logrus.Println("Test HTTP server ready and waiting:", testHTTPServer.URL)
  434. c := make(chan int)
  435. <-c
  436. }
  437. //*/