github.com/torfuzx/docker@v1.8.1/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 "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 "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 "test": "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d", 85 }, 86 } 87 mockHosts = map[string][]net.IP{ 88 "": {net.ParseIP("0.0.0.0")}, 89 "localhost": {net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, 90 "example.com": {net.ParseIP("42.42.42.42")}, 91 "other.com": {net.ParseIP("43.43.43.43")}, 92 } 93 ) 94 95 func init() { 96 r := mux.NewRouter() 97 98 // /v1/ 99 r.HandleFunc("/v1/_ping", handlerGetPing).Methods("GET") 100 r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|ancestry}", handlerGetImage).Methods("GET") 101 r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|checksum}", handlerPutImage).Methods("PUT") 102 r.HandleFunc("/v1/repositories/{repository:.+}/tags", handlerGetDeleteTags).Methods("GET", "DELETE") 103 r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerGetTag).Methods("GET") 104 r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerPutTag).Methods("PUT") 105 r.HandleFunc("/v1/users{null:.*}", handlerUsers).Methods("GET", "POST", "PUT") 106 r.HandleFunc("/v1/repositories/{repository:.+}{action:/images|/}", handlerImages).Methods("GET", "PUT", "DELETE") 107 r.HandleFunc("/v1/repositories/{repository:.+}/auth", handlerAuth).Methods("PUT") 108 r.HandleFunc("/v1/search", handlerSearch).Methods("GET") 109 110 // /v2/ 111 r.HandleFunc("/v2/version", handlerGetPing).Methods("GET") 112 113 testHTTPServer = httptest.NewServer(handlerAccessLog(r)) 114 testHTTPSServer = httptest.NewTLSServer(handlerAccessLog(r)) 115 116 // override net.LookupIP 117 lookupIP = func(host string) ([]net.IP, error) { 118 if host == "127.0.0.1" { 119 // I believe in future Go versions this will fail, so let's fix it later 120 return net.LookupIP(host) 121 } 122 for h, addrs := range mockHosts { 123 if host == h { 124 return addrs, nil 125 } 126 for _, addr := range addrs { 127 if addr.String() == host { 128 return []net.IP{addr}, nil 129 } 130 } 131 } 132 return nil, errors.New("lookup: no such host") 133 } 134 } 135 136 func handlerAccessLog(handler http.Handler) http.Handler { 137 logHandler := func(w http.ResponseWriter, r *http.Request) { 138 logrus.Debugf("%s \"%s %s\"", r.RemoteAddr, r.Method, r.URL) 139 handler.ServeHTTP(w, r) 140 } 141 return http.HandlerFunc(logHandler) 142 } 143 144 func makeURL(req string) string { 145 return testHTTPServer.URL + req 146 } 147 148 func makeHTTPSURL(req string) string { 149 return testHTTPSServer.URL + req 150 } 151 152 func makeIndex(req string) *IndexInfo { 153 index := &IndexInfo{ 154 Name: makeURL(req), 155 } 156 return index 157 } 158 159 func makeHTTPSIndex(req string) *IndexInfo { 160 index := &IndexInfo{ 161 Name: makeHTTPSURL(req), 162 } 163 return index 164 } 165 166 func makePublicIndex() *IndexInfo { 167 index := &IndexInfo{ 168 Name: IndexServer, 169 Secure: true, 170 Official: true, 171 } 172 return index 173 } 174 175 func makeServiceConfig(mirrors []string, insecureRegistries []string) *ServiceConfig { 176 options := &Options{ 177 Mirrors: opts.NewListOpts(nil), 178 InsecureRegistries: opts.NewListOpts(nil), 179 } 180 if mirrors != nil { 181 for _, mirror := range mirrors { 182 options.Mirrors.Set(mirror) 183 } 184 } 185 if insecureRegistries != nil { 186 for _, insecureRegistries := range insecureRegistries { 187 options.InsecureRegistries.Set(insecureRegistries) 188 } 189 } 190 191 return NewServiceConfig(options) 192 } 193 194 func writeHeaders(w http.ResponseWriter) { 195 h := w.Header() 196 h.Add("Server", "docker-tests/mock") 197 h.Add("Expires", "-1") 198 h.Add("Content-Type", "application/json") 199 h.Add("Pragma", "no-cache") 200 h.Add("Cache-Control", "no-cache") 201 h.Add("X-Docker-Registry-Version", "0.0.0") 202 h.Add("X-Docker-Registry-Config", "mock") 203 } 204 205 func writeResponse(w http.ResponseWriter, message interface{}, code int) { 206 writeHeaders(w) 207 w.WriteHeader(code) 208 body, err := json.Marshal(message) 209 if err != nil { 210 io.WriteString(w, err.Error()) 211 return 212 } 213 w.Write(body) 214 } 215 216 func readJSON(r *http.Request, dest interface{}) error { 217 body, err := ioutil.ReadAll(r.Body) 218 if err != nil { 219 return err 220 } 221 return json.Unmarshal(body, dest) 222 } 223 224 func apiError(w http.ResponseWriter, message string, code int) { 225 body := map[string]string{ 226 "error": message, 227 } 228 writeResponse(w, body, code) 229 } 230 231 func assertEqual(t *testing.T, a interface{}, b interface{}, message string) { 232 if a == b { 233 return 234 } 235 if len(message) == 0 { 236 message = fmt.Sprintf("%v != %v", a, b) 237 } 238 t.Fatal(message) 239 } 240 241 func assertNotEqual(t *testing.T, a interface{}, b interface{}, message string) { 242 if a != b { 243 return 244 } 245 if len(message) == 0 { 246 message = fmt.Sprintf("%v == %v", a, b) 247 } 248 t.Fatal(message) 249 } 250 251 // Similar to assertEqual, but does not stop test 252 func checkEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) { 253 if a == b { 254 return 255 } 256 message := fmt.Sprintf("%v != %v", a, b) 257 if len(messagePrefix) != 0 { 258 message = messagePrefix + ": " + message 259 } 260 t.Error(message) 261 } 262 263 // Similar to assertNotEqual, but does not stop test 264 func checkNotEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) { 265 if a != b { 266 return 267 } 268 message := fmt.Sprintf("%v == %v", a, b) 269 if len(messagePrefix) != 0 { 270 message = messagePrefix + ": " + message 271 } 272 t.Error(message) 273 } 274 275 func requiresAuth(w http.ResponseWriter, r *http.Request) bool { 276 writeCookie := func() { 277 value := fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano()) 278 cookie := &http.Cookie{Name: "session", Value: value, MaxAge: 3600} 279 http.SetCookie(w, cookie) 280 //FIXME(sam): this should be sent only on Index routes 281 value = fmt.Sprintf("FAKE-TOKEN-%d", time.Now().UnixNano()) 282 w.Header().Add("X-Docker-Token", value) 283 } 284 if len(r.Cookies()) > 0 { 285 writeCookie() 286 return true 287 } 288 if len(r.Header.Get("Authorization")) > 0 { 289 writeCookie() 290 return true 291 } 292 w.Header().Add("WWW-Authenticate", "token") 293 apiError(w, "Wrong auth", 401) 294 return false 295 } 296 297 func handlerGetPing(w http.ResponseWriter, r *http.Request) { 298 writeResponse(w, true, 200) 299 } 300 301 func handlerGetImage(w http.ResponseWriter, r *http.Request) { 302 if !requiresAuth(w, r) { 303 return 304 } 305 vars := mux.Vars(r) 306 layer, exists := testLayers[vars["image_id"]] 307 if !exists { 308 http.NotFound(w, r) 309 return 310 } 311 writeHeaders(w) 312 layerSize := len(layer["layer"]) 313 w.Header().Add("X-Docker-Size", strconv.Itoa(layerSize)) 314 io.WriteString(w, layer[vars["action"]]) 315 } 316 317 func handlerPutImage(w http.ResponseWriter, r *http.Request) { 318 if !requiresAuth(w, r) { 319 return 320 } 321 vars := mux.Vars(r) 322 imageID := vars["image_id"] 323 action := vars["action"] 324 layer, exists := testLayers[imageID] 325 if !exists { 326 if action != "json" { 327 http.NotFound(w, r) 328 return 329 } 330 layer = make(map[string]string) 331 testLayers[imageID] = layer 332 } 333 if checksum := r.Header.Get("X-Docker-Checksum"); checksum != "" { 334 if checksum != layer["checksum_simple"] && checksum != layer["checksum_tarsum"] { 335 apiError(w, "Wrong checksum", 400) 336 return 337 } 338 } 339 body, err := ioutil.ReadAll(r.Body) 340 if err != nil { 341 apiError(w, fmt.Sprintf("Error: %s", err), 500) 342 return 343 } 344 layer[action] = string(body) 345 writeResponse(w, true, 200) 346 } 347 348 func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) { 349 if !requiresAuth(w, r) { 350 return 351 } 352 repositoryName := mux.Vars(r)["repository"] 353 repositoryName = NormalizeLocalName(repositoryName) 354 tags, exists := testRepositories[repositoryName] 355 if !exists { 356 apiError(w, "Repository not found", 404) 357 return 358 } 359 if r.Method == "DELETE" { 360 delete(testRepositories, repositoryName) 361 writeResponse(w, true, 200) 362 return 363 } 364 writeResponse(w, tags, 200) 365 } 366 367 func handlerGetTag(w http.ResponseWriter, r *http.Request) { 368 if !requiresAuth(w, r) { 369 return 370 } 371 vars := mux.Vars(r) 372 repositoryName := vars["repository"] 373 repositoryName = NormalizeLocalName(repositoryName) 374 tagName := vars["tag"] 375 tags, exists := testRepositories[repositoryName] 376 if !exists { 377 apiError(w, "Repository not found", 404) 378 return 379 } 380 tag, exists := tags[tagName] 381 if !exists { 382 apiError(w, "Tag not found", 404) 383 return 384 } 385 writeResponse(w, tag, 200) 386 } 387 388 func handlerPutTag(w http.ResponseWriter, r *http.Request) { 389 if !requiresAuth(w, r) { 390 return 391 } 392 vars := mux.Vars(r) 393 repositoryName := vars["repository"] 394 repositoryName = NormalizeLocalName(repositoryName) 395 tagName := vars["tag"] 396 tags, exists := testRepositories[repositoryName] 397 if !exists { 398 tags := make(map[string]string) 399 testRepositories[repositoryName] = tags 400 } 401 tagValue := "" 402 readJSON(r, tagValue) 403 tags[tagName] = tagValue 404 writeResponse(w, true, 200) 405 } 406 407 func handlerUsers(w http.ResponseWriter, r *http.Request) { 408 code := 200 409 if r.Method == "POST" { 410 code = 201 411 } else if r.Method == "PUT" { 412 code = 204 413 } 414 writeResponse(w, "", code) 415 } 416 417 func handlerImages(w http.ResponseWriter, r *http.Request) { 418 u, _ := url.Parse(testHTTPServer.URL) 419 w.Header().Add("X-Docker-Endpoints", fmt.Sprintf("%s , %s ", u.Host, "test.example.com")) 420 w.Header().Add("X-Docker-Token", fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano())) 421 if r.Method == "PUT" { 422 if strings.HasSuffix(r.URL.Path, "images") { 423 writeResponse(w, "", 204) 424 return 425 } 426 writeResponse(w, "", 200) 427 return 428 } 429 if r.Method == "DELETE" { 430 writeResponse(w, "", 204) 431 return 432 } 433 images := []map[string]string{} 434 for imageID, layer := range testLayers { 435 image := make(map[string]string) 436 image["id"] = imageID 437 image["checksum"] = layer["checksum_tarsum"] 438 image["Tag"] = "latest" 439 images = append(images, image) 440 } 441 writeResponse(w, images, 200) 442 } 443 444 func handlerAuth(w http.ResponseWriter, r *http.Request) { 445 writeResponse(w, "OK", 200) 446 } 447 448 func handlerSearch(w http.ResponseWriter, r *http.Request) { 449 result := &SearchResults{ 450 Query: "fakequery", 451 NumResults: 1, 452 Results: []SearchResult{{Name: "fakeimage", StarCount: 42}}, 453 } 454 writeResponse(w, result, 200) 455 } 456 457 func TestPing(t *testing.T) { 458 res, err := http.Get(makeURL("/v1/_ping")) 459 if err != nil { 460 t.Fatal(err) 461 } 462 assertEqual(t, res.StatusCode, 200, "") 463 assertEqual(t, res.Header.Get("X-Docker-Registry-Config"), "mock", 464 "This is not a Mocked Registry") 465 } 466 467 /* Uncomment this to test Mocked Registry locally with curl 468 * WARNING: Don't push on the repos uncommented, it'll block the tests 469 * 470 func TestWait(t *testing.T) { 471 logrus.Println("Test HTTP server ready and waiting:", testHTTPServer.URL) 472 c := make(chan int) 473 <-c 474 } 475 476 //*/