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