registry_mock_test.go 14 KB

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