Fix the dependency issue (#231)

This commit is contained in:
Robbie Zhang
2018-06-21 12:09:42 -07:00
committed by GitHub
parent 027b76651d
commit 6ec1098bb8
16629 changed files with 74837 additions and 4975021 deletions

View File

@@ -1,127 +0,0 @@
package registry
import (
"testing"
"github.com/hyperhq/hyper-api/types"
registrytypes "github.com/hyperhq/hyper-api/types/registry"
)
func buildAuthConfigs() map[string]types.AuthConfig {
authConfigs := map[string]types.AuthConfig{}
for _, registry := range []string{"testIndex", IndexServer} {
authConfigs[registry] = types.AuthConfig{
Username: "docker-user",
Password: "docker-pass",
Email: "docker@docker.io",
}
}
return authConfigs
}
func TestSameAuthDataPostSave(t *testing.T) {
authConfigs := buildAuthConfigs()
authConfig := authConfigs["testIndex"]
if authConfig.Username != "docker-user" {
t.Fail()
}
if authConfig.Password != "docker-pass" {
t.Fail()
}
if authConfig.Email != "docker@docker.io" {
t.Fail()
}
if authConfig.Auth != "" {
t.Fail()
}
}
func TestResolveAuthConfigIndexServer(t *testing.T) {
authConfigs := buildAuthConfigs()
indexConfig := authConfigs[IndexServer]
officialIndex := &registrytypes.IndexInfo{
Official: true,
}
privateIndex := &registrytypes.IndexInfo{
Official: false,
}
resolved := ResolveAuthConfig(authConfigs, officialIndex)
assertEqual(t, resolved, indexConfig, "Expected ResolveAuthConfig to return IndexServer")
resolved = ResolveAuthConfig(authConfigs, privateIndex)
assertNotEqual(t, resolved, indexConfig, "Expected ResolveAuthConfig to not return IndexServer")
}
func TestResolveAuthConfigFullURL(t *testing.T) {
authConfigs := buildAuthConfigs()
registryAuth := types.AuthConfig{
Username: "foo-user",
Password: "foo-pass",
Email: "foo@example.com",
}
localAuth := types.AuthConfig{
Username: "bar-user",
Password: "bar-pass",
Email: "bar@example.com",
}
officialAuth := types.AuthConfig{
Username: "baz-user",
Password: "baz-pass",
Email: "baz@example.com",
}
authConfigs[IndexServer] = officialAuth
expectedAuths := map[string]types.AuthConfig{
"registry.example.com": registryAuth,
"localhost:8000": localAuth,
"registry.com": localAuth,
}
validRegistries := map[string][]string{
"registry.example.com": {
"https://registry.example.com/v1/",
"http://registry.example.com/v1/",
"registry.example.com",
"registry.example.com/v1/",
},
"localhost:8000": {
"https://localhost:8000/v1/",
"http://localhost:8000/v1/",
"localhost:8000",
"localhost:8000/v1/",
},
"registry.com": {
"https://registry.com/v1/",
"http://registry.com/v1/",
"registry.com",
"registry.com/v1/",
},
}
for configKey, registries := range validRegistries {
configured, ok := expectedAuths[configKey]
if !ok || configured.Email == "" {
t.Fail()
}
index := &registrytypes.IndexInfo{
Name: configKey,
}
for _, registry := range registries {
authConfigs[registry] = configured
resolved := ResolveAuthConfig(authConfigs, index)
if resolved.Email != configured.Email {
t.Errorf("%s -> %q != %q\n", registry, resolved.Email, configured.Email)
}
delete(authConfigs, registry)
resolved = ResolveAuthConfig(authConfigs, index)
if resolved.Email == configured.Email {
t.Errorf("%s -> %q == %q\n", registry, resolved.Email, configured.Email)
}
}
}
}

View File

@@ -1,49 +0,0 @@
package registry
import (
"testing"
)
func TestValidateMirror(t *testing.T) {
valid := []string{
"http://mirror-1.com",
"https://mirror-1.com",
"http://localhost",
"https://localhost",
"http://localhost:5000",
"https://localhost:5000",
"http://127.0.0.1",
"https://127.0.0.1",
"http://127.0.0.1:5000",
"https://127.0.0.1:5000",
}
invalid := []string{
"!invalid!://%as%",
"ftp://mirror-1.com",
"http://mirror-1.com/",
"http://mirror-1.com/?q=foo",
"http://mirror-1.com/v1/",
"http://mirror-1.com/v1/?q=foo",
"http://mirror-1.com/v1/?q=foo#frag",
"http://mirror-1.com?q=foo",
"https://mirror-1.com#frag",
"https://mirror-1.com/",
"https://mirror-1.com/#frag",
"https://mirror-1.com/v1/",
"https://mirror-1.com/v1/#",
"https://mirror-1.com?q",
}
for _, address := range valid {
if ret, err := ValidateMirror(address); err != nil || ret == "" {
t.Errorf("ValidateMirror(`"+address+"`) got %s %s", ret, err)
}
}
for _, address := range invalid {
if ret, err := ValidateMirror(address); err == nil || ret != "" {
t.Errorf("ValidateMirror(`"+address+"`) got %s %s", ret, err)
}
}
}

View File

@@ -1,93 +0,0 @@
package registry
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
func TestEndpointParse(t *testing.T) {
testData := []struct {
str string
expected string
}{
{IndexServer, IndexServer},
{"http://0.0.0.0:5000/v1/", "http://0.0.0.0:5000/v1/"},
{"http://0.0.0.0:5000/v2/", "http://0.0.0.0:5000/v2/"},
{"http://0.0.0.0:5000", "http://0.0.0.0:5000/v0/"},
{"0.0.0.0:5000", "https://0.0.0.0:5000/v0/"},
}
for _, td := range testData {
e, err := newEndpoint(td.str, nil, "", nil)
if err != nil {
t.Errorf("%q: %s", td.str, err)
}
if e == nil {
t.Logf("something's fishy, endpoint for %q is nil", td.str)
continue
}
if e.String() != td.expected {
t.Errorf("expected %q, got %q", td.expected, e.String())
}
}
}
// Ensure that a registry endpoint that responds with a 401 only is determined
// to be a v1 registry unless it includes a valid v2 API header.
func TestValidateEndpointAmbiguousAPIVersion(t *testing.T) {
requireBasicAuthHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("WWW-Authenticate", `Basic realm="localhost"`)
w.WriteHeader(http.StatusUnauthorized)
})
requireBasicAuthHandlerV2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This mock server supports v2.0, v2.1, v42.0, and v100.0
w.Header().Add("Docker-Distribution-API-Version", "registry/100.0 registry/42.0")
w.Header().Add("Docker-Distribution-API-Version", "registry/2.0 registry/2.1")
requireBasicAuthHandler.ServeHTTP(w, r)
})
// Make a test server which should validate as a v1 server.
testServer := httptest.NewServer(requireBasicAuthHandler)
defer testServer.Close()
testServerURL, err := url.Parse(testServer.URL)
if err != nil {
t.Fatal(err)
}
testEndpoint := Endpoint{
URL: testServerURL,
Version: APIVersionUnknown,
client: HTTPClient(NewTransport(nil)),
}
if err = validateEndpoint(&testEndpoint); err != nil {
t.Fatal(err)
}
if testEndpoint.Version != APIVersion1 {
t.Fatalf("expected endpoint to validate to %d, got %d", APIVersion1, testEndpoint.Version)
}
// Make a test server which should validate as a v2 server.
testServer = httptest.NewServer(requireBasicAuthHandlerV2)
defer testServer.Close()
testServerURL, err = url.Parse(testServer.URL)
if err != nil {
t.Fatal(err)
}
testEndpoint.URL = testServerURL
testEndpoint.Version = APIVersionUnknown
if err = validateEndpoint(&testEndpoint); err != nil {
t.Fatal(err)
}
if testEndpoint.Version != APIVersion2 {
t.Fatalf("expected endpoint to validate to %d, got %d", APIVersion2, testEndpoint.Version)
}
}

View File

@@ -1,487 +0,0 @@
package registry
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
"github.com/gorilla/mux"
registrytypes "github.com/hyperhq/hyper-api/types/registry"
"github.com/hyperhq/hypercli/opts"
"github.com/hyperhq/hypercli/reference"
"github.com/Sirupsen/logrus"
)
var (
testHTTPServer *httptest.Server
testHTTPSServer *httptest.Server
testLayers = map[string]map[string]string{
"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20": {
"json": `{"id":"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20",
"comment":"test base image","created":"2013-03-23T12:53:11.10432-07:00",
"container_config":{"Hostname":"","User":"","Memory":0,"MemorySwap":0,
"CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,
"Tty":false,"OpenStdin":false,"StdinOnce":false,
"Env":null,"Cmd":null,"Dns":null,"Image":"","Volumes":null,
"VolumesFrom":"","Entrypoint":null},"Size":424242}`,
"checksum_simple": "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37",
"checksum_tarsum": "tarsum+sha256:4409a0685741ca86d38df878ed6f8cbba4c99de5dc73cd71aef04be3bb70be7c",
"ancestry": `["77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20"]`,
"layer": string([]byte{
0x1f, 0x8b, 0x08, 0x08, 0x0e, 0xb0, 0xee, 0x51, 0x02, 0x03, 0x6c, 0x61, 0x79, 0x65,
0x72, 0x2e, 0x74, 0x61, 0x72, 0x00, 0xed, 0xd2, 0x31, 0x0e, 0xc2, 0x30, 0x0c, 0x05,
0x50, 0xcf, 0x9c, 0xc2, 0x27, 0x48, 0xed, 0x38, 0x4e, 0xce, 0x13, 0x44, 0x2b, 0x66,
0x62, 0x24, 0x8e, 0x4f, 0xa0, 0x15, 0x63, 0xb6, 0x20, 0x21, 0xfc, 0x96, 0xbf, 0x78,
0xb0, 0xf5, 0x1d, 0x16, 0x98, 0x8e, 0x88, 0x8a, 0x2a, 0xbe, 0x33, 0xef, 0x49, 0x31,
0xed, 0x79, 0x40, 0x8e, 0x5c, 0x44, 0x85, 0x88, 0x33, 0x12, 0x73, 0x2c, 0x02, 0xa8,
0xf0, 0x05, 0xf7, 0x66, 0xf5, 0xd6, 0x57, 0x69, 0xd7, 0x7a, 0x19, 0xcd, 0xf5, 0xb1,
0x6d, 0x1b, 0x1f, 0xf9, 0xba, 0xe3, 0x93, 0x3f, 0x22, 0x2c, 0xb6, 0x36, 0x0b, 0xf6,
0xb0, 0xa9, 0xfd, 0xe7, 0x94, 0x46, 0xfd, 0xeb, 0xd1, 0x7f, 0x2c, 0xc4, 0xd2, 0xfb,
0x97, 0xfe, 0x02, 0x80, 0xe4, 0xfd, 0x4f, 0x77, 0xae, 0x6d, 0x3d, 0x81, 0x73, 0xce,
0xb9, 0x7f, 0xf3, 0x04, 0x41, 0xc1, 0xab, 0xc6, 0x00, 0x0a, 0x00, 0x00,
}),
},
"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d": {
"json": `{"id":"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
"parent":"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20",
"comment":"test base image","created":"2013-03-23T12:55:11.10432-07:00",
"container_config":{"Hostname":"","User":"","Memory":0,"MemorySwap":0,
"CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,
"Tty":false,"OpenStdin":false,"StdinOnce":false,
"Env":null,"Cmd":null,"Dns":null,"Image":"","Volumes":null,
"VolumesFrom":"","Entrypoint":null},"Size":424242}`,
"checksum_simple": "sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2",
"checksum_tarsum": "tarsum+sha256:68fdb56fb364f074eec2c9b3f85ca175329c4dcabc4a6a452b7272aa613a07a2",
"ancestry": `["42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20"]`,
"layer": string([]byte{
0x1f, 0x8b, 0x08, 0x08, 0xbd, 0xb3, 0xee, 0x51, 0x02, 0x03, 0x6c, 0x61, 0x79, 0x65,
0x72, 0x2e, 0x74, 0x61, 0x72, 0x00, 0xed, 0xd1, 0x31, 0x0e, 0xc2, 0x30, 0x0c, 0x05,
0x50, 0xcf, 0x9c, 0xc2, 0x27, 0x48, 0x9d, 0x38, 0x8e, 0xcf, 0x53, 0x51, 0xaa, 0x56,
0xea, 0x44, 0x82, 0xc4, 0xf1, 0x09, 0xb4, 0xea, 0x98, 0x2d, 0x48, 0x08, 0xbf, 0xe5,
0x2f, 0x1e, 0xfc, 0xf5, 0xdd, 0x00, 0xdd, 0x11, 0x91, 0x8a, 0xe0, 0x27, 0xd3, 0x9e,
0x14, 0xe2, 0x9e, 0x07, 0xf4, 0xc1, 0x2b, 0x0b, 0xfb, 0xa4, 0x82, 0xe4, 0x3d, 0x93,
0x02, 0x0a, 0x7c, 0xc1, 0x23, 0x97, 0xf1, 0x5e, 0x5f, 0xc9, 0xcb, 0x38, 0xb5, 0xee,
0xea, 0xd9, 0x3c, 0xb7, 0x4b, 0xbe, 0x7b, 0x9c, 0xf9, 0x23, 0xdc, 0x50, 0x6e, 0xb9,
0xb8, 0xf2, 0x2c, 0x5d, 0xf7, 0x4f, 0x31, 0xb6, 0xf6, 0x4f, 0xc7, 0xfe, 0x41, 0x55,
0x63, 0xdd, 0x9f, 0x89, 0x09, 0x90, 0x6c, 0xff, 0xee, 0xae, 0xcb, 0xba, 0x4d, 0x17,
0x30, 0xc6, 0x18, 0xf3, 0x67, 0x5e, 0xc1, 0xed, 0x21, 0x5d, 0x00, 0x0a, 0x00, 0x00,
}),
},
}
testRepositories = map[string]map[string]string{
"foo42/bar": {
"latest": "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
"test": "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
},
}
mockHosts = map[string][]net.IP{
"": {net.ParseIP("0.0.0.0")},
"localhost": {net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
"example.com": {net.ParseIP("42.42.42.42")},
"other.com": {net.ParseIP("43.43.43.43")},
}
)
func init() {
r := mux.NewRouter()
// /v1/
r.HandleFunc("/v1/_ping", handlerGetPing).Methods("GET")
r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|ancestry}", handlerGetImage).Methods("GET")
r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|checksum}", handlerPutImage).Methods("PUT")
r.HandleFunc("/v1/repositories/{repository:.+}/tags", handlerGetDeleteTags).Methods("GET", "DELETE")
r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerGetTag).Methods("GET")
r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerPutTag).Methods("PUT")
r.HandleFunc("/v1/users{null:.*}", handlerUsers).Methods("GET", "POST", "PUT")
r.HandleFunc("/v1/repositories/{repository:.+}{action:/images|/}", handlerImages).Methods("GET", "PUT", "DELETE")
r.HandleFunc("/v1/repositories/{repository:.+}/auth", handlerAuth).Methods("PUT")
r.HandleFunc("/v1/search", handlerSearch).Methods("GET")
// /v2/
r.HandleFunc("/v2/version", handlerGetPing).Methods("GET")
testHTTPServer = httptest.NewServer(handlerAccessLog(r))
testHTTPSServer = httptest.NewTLSServer(handlerAccessLog(r))
// override net.LookupIP
lookupIP = func(host string) ([]net.IP, error) {
if host == "127.0.0.1" {
// I believe in future Go versions this will fail, so let's fix it later
return net.LookupIP(host)
}
for h, addrs := range mockHosts {
if host == h {
return addrs, nil
}
for _, addr := range addrs {
if addr.String() == host {
return []net.IP{addr}, nil
}
}
}
return nil, errors.New("lookup: no such host")
}
}
func handlerAccessLog(handler http.Handler) http.Handler {
logHandler := func(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("%s \"%s %s\"", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
}
return http.HandlerFunc(logHandler)
}
func makeURL(req string) string {
return testHTTPServer.URL + req
}
func makeHTTPSURL(req string) string {
return testHTTPSServer.URL + req
}
func makeIndex(req string) *registrytypes.IndexInfo {
index := &registrytypes.IndexInfo{
Name: makeURL(req),
}
return index
}
func makeHTTPSIndex(req string) *registrytypes.IndexInfo {
index := &registrytypes.IndexInfo{
Name: makeHTTPSURL(req),
}
return index
}
func makePublicIndex() *registrytypes.IndexInfo {
index := &registrytypes.IndexInfo{
Name: IndexServer,
Secure: true,
Official: true,
}
return index
}
func makeServiceConfig(mirrors []string, insecureRegistries []string) *registrytypes.ServiceConfig {
options := &Options{
Mirrors: opts.NewListOpts(nil),
InsecureRegistries: opts.NewListOpts(nil),
}
if mirrors != nil {
for _, mirror := range mirrors {
options.Mirrors.Set(mirror)
}
}
if insecureRegistries != nil {
for _, insecureRegistries := range insecureRegistries {
options.InsecureRegistries.Set(insecureRegistries)
}
}
return NewServiceConfig(options)
}
func writeHeaders(w http.ResponseWriter) {
h := w.Header()
h.Add("Server", "docker-tests/mock")
h.Add("Expires", "-1")
h.Add("Content-Type", "application/json")
h.Add("Pragma", "no-cache")
h.Add("Cache-Control", "no-cache")
h.Add("X-Docker-Registry-Version", "0.0.0")
h.Add("X-Docker-Registry-Config", "mock")
}
func writeResponse(w http.ResponseWriter, message interface{}, code int) {
writeHeaders(w)
w.WriteHeader(code)
body, err := json.Marshal(message)
if err != nil {
io.WriteString(w, err.Error())
return
}
w.Write(body)
}
func readJSON(r *http.Request, dest interface{}) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
return json.Unmarshal(body, dest)
}
func apiError(w http.ResponseWriter, message string, code int) {
body := map[string]string{
"error": message,
}
writeResponse(w, body, code)
}
func assertEqual(t *testing.T, a interface{}, b interface{}, message string) {
if a == b {
return
}
if len(message) == 0 {
message = fmt.Sprintf("%v != %v", a, b)
}
t.Fatal(message)
}
func assertNotEqual(t *testing.T, a interface{}, b interface{}, message string) {
if a != b {
return
}
if len(message) == 0 {
message = fmt.Sprintf("%v == %v", a, b)
}
t.Fatal(message)
}
// Similar to assertEqual, but does not stop test
func checkEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) {
if a == b {
return
}
message := fmt.Sprintf("%v != %v", a, b)
if len(messagePrefix) != 0 {
message = messagePrefix + ": " + message
}
t.Error(message)
}
// Similar to assertNotEqual, but does not stop test
func checkNotEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) {
if a != b {
return
}
message := fmt.Sprintf("%v == %v", a, b)
if len(messagePrefix) != 0 {
message = messagePrefix + ": " + message
}
t.Error(message)
}
func requiresAuth(w http.ResponseWriter, r *http.Request) bool {
writeCookie := func() {
value := fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano())
cookie := &http.Cookie{Name: "session", Value: value, MaxAge: 3600}
http.SetCookie(w, cookie)
//FIXME(sam): this should be sent only on Index routes
value = fmt.Sprintf("FAKE-TOKEN-%d", time.Now().UnixNano())
w.Header().Add("X-Docker-Token", value)
}
if len(r.Cookies()) > 0 {
writeCookie()
return true
}
if len(r.Header.Get("Authorization")) > 0 {
writeCookie()
return true
}
w.Header().Add("WWW-Authenticate", "token")
apiError(w, "Wrong auth", 401)
return false
}
func handlerGetPing(w http.ResponseWriter, r *http.Request) {
writeResponse(w, true, 200)
}
func handlerGetImage(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
vars := mux.Vars(r)
layer, exists := testLayers[vars["image_id"]]
if !exists {
http.NotFound(w, r)
return
}
writeHeaders(w)
layerSize := len(layer["layer"])
w.Header().Add("X-Docker-Size", strconv.Itoa(layerSize))
io.WriteString(w, layer[vars["action"]])
}
func handlerPutImage(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
vars := mux.Vars(r)
imageID := vars["image_id"]
action := vars["action"]
layer, exists := testLayers[imageID]
if !exists {
if action != "json" {
http.NotFound(w, r)
return
}
layer = make(map[string]string)
testLayers[imageID] = layer
}
if checksum := r.Header.Get("X-Docker-Checksum"); checksum != "" {
if checksum != layer["checksum_simple"] && checksum != layer["checksum_tarsum"] {
apiError(w, "Wrong checksum", 400)
return
}
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
apiError(w, fmt.Sprintf("Error: %s", err), 500)
return
}
layer[action] = string(body)
writeResponse(w, true, 200)
}
func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
repositoryName, err := reference.WithName(mux.Vars(r)["repository"])
if err != nil {
apiError(w, "Could not parse repository", 400)
return
}
tags, exists := testRepositories[repositoryName.String()]
if !exists {
apiError(w, "Repository not found", 404)
return
}
if r.Method == "DELETE" {
delete(testRepositories, repositoryName.String())
writeResponse(w, true, 200)
return
}
writeResponse(w, tags, 200)
}
func handlerGetTag(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
vars := mux.Vars(r)
repositoryName, err := reference.WithName(vars["repository"])
if err != nil {
apiError(w, "Could not parse repository", 400)
return
}
tagName := vars["tag"]
tags, exists := testRepositories[repositoryName.String()]
if !exists {
apiError(w, "Repository not found", 404)
return
}
tag, exists := tags[tagName]
if !exists {
apiError(w, "Tag not found", 404)
return
}
writeResponse(w, tag, 200)
}
func handlerPutTag(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
vars := mux.Vars(r)
repositoryName, err := reference.WithName(vars["repository"])
if err != nil {
apiError(w, "Could not parse repository", 400)
return
}
tagName := vars["tag"]
tags, exists := testRepositories[repositoryName.String()]
if !exists {
tags = make(map[string]string)
testRepositories[repositoryName.String()] = tags
}
tagValue := ""
readJSON(r, tagValue)
tags[tagName] = tagValue
writeResponse(w, true, 200)
}
func handlerUsers(w http.ResponseWriter, r *http.Request) {
code := 200
if r.Method == "POST" {
code = 201
} else if r.Method == "PUT" {
code = 204
}
writeResponse(w, "", code)
}
func handlerImages(w http.ResponseWriter, r *http.Request) {
u, _ := url.Parse(testHTTPServer.URL)
w.Header().Add("X-Docker-Endpoints", fmt.Sprintf("%s , %s ", u.Host, "test.example.com"))
w.Header().Add("X-Docker-Token", fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano()))
if r.Method == "PUT" {
if strings.HasSuffix(r.URL.Path, "images") {
writeResponse(w, "", 204)
return
}
writeResponse(w, "", 200)
return
}
if r.Method == "DELETE" {
writeResponse(w, "", 204)
return
}
images := []map[string]string{}
for imageID, layer := range testLayers {
image := make(map[string]string)
image["id"] = imageID
image["checksum"] = layer["checksum_tarsum"]
image["Tag"] = "latest"
images = append(images, image)
}
writeResponse(w, images, 200)
}
func handlerAuth(w http.ResponseWriter, r *http.Request) {
writeResponse(w, "OK", 200)
}
func handlerSearch(w http.ResponseWriter, r *http.Request) {
result := &registrytypes.SearchResults{
Query: "fakequery",
NumResults: 1,
Results: []registrytypes.SearchResult{{Name: "fakeimage", StarCount: 42}},
}
writeResponse(w, result, 200)
}
func TestPing(t *testing.T) {
res, err := http.Get(makeURL("/v1/_ping"))
if err != nil {
t.Fatal(err)
}
assertEqual(t, res.StatusCode, 200, "")
assertEqual(t, res.Header.Get("X-Docker-Registry-Config"), "mock",
"This is not a Mocked Registry")
}
/* Uncomment this to test Mocked Registry locally with curl
* WARNING: Don't push on the repos uncommented, it'll block the tests
*
func TestWait(t *testing.T) {
logrus.Println("Test HTTP server ready and waiting:", testHTTPServer.URL)
c := make(chan int)
<-c
}
//*/

View File

@@ -1,891 +0,0 @@
package registry
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"testing"
"github.com/docker/distribution/registry/client/transport"
"github.com/hyperhq/hyper-api/types"
registrytypes "github.com/hyperhq/hyper-api/types/registry"
"github.com/hyperhq/hypercli/reference"
)
var (
token = []string{"fake-token"}
)
const (
imageID = "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d"
REPO = "foo42/bar"
)
func spawnTestRegistrySession(t *testing.T) *Session {
authConfig := &types.AuthConfig{}
endpoint, err := NewEndpoint(makeIndex("/v1/"), "", nil, APIVersionUnknown)
if err != nil {
t.Fatal(err)
}
userAgent := "docker test client"
var tr http.RoundTripper = debugTransport{NewTransport(nil), t.Log}
tr = transport.NewTransport(AuthTransport(tr, authConfig, false), DockerHeaders(userAgent, nil)...)
client := HTTPClient(tr)
r, err := NewSession(client, authConfig, endpoint)
if err != nil {
t.Fatal(err)
}
// In a normal scenario for the v1 registry, the client should send a `X-Docker-Token: true`
// header while authenticating, in order to retrieve a token that can be later used to
// perform authenticated actions.
//
// The mock v1 registry does not support that, (TODO(tiborvass): support it), instead,
// it will consider authenticated any request with the header `X-Docker-Token: fake-token`.
//
// Because we know that the client's transport is an `*authTransport` we simply cast it,
// in order to set the internal cached token to the fake token, and thus send that fake token
// upon every subsequent requests.
r.client.Transport.(*authTransport).token = token
return r
}
func TestPingRegistryEndpoint(t *testing.T) {
testPing := func(index *registrytypes.IndexInfo, expectedStandalone bool, assertMessage string) {
ep, err := NewEndpoint(index, "", nil, APIVersionUnknown)
if err != nil {
t.Fatal(err)
}
regInfo, err := ep.Ping()
if err != nil {
t.Fatal(err)
}
assertEqual(t, regInfo.Standalone, expectedStandalone, assertMessage)
}
testPing(makeIndex("/v1/"), true, "Expected standalone to be true (default)")
testPing(makeHTTPSIndex("/v1/"), true, "Expected standalone to be true (default)")
testPing(makePublicIndex(), false, "Expected standalone to be false for public index")
}
func TestEndpoint(t *testing.T) {
// Simple wrapper to fail test if err != nil
expandEndpoint := func(index *registrytypes.IndexInfo) *Endpoint {
endpoint, err := NewEndpoint(index, "", nil, APIVersionUnknown)
if err != nil {
t.Fatal(err)
}
return endpoint
}
assertInsecureIndex := func(index *registrytypes.IndexInfo) {
index.Secure = true
_, err := NewEndpoint(index, "", nil, APIVersionUnknown)
assertNotEqual(t, err, nil, index.Name+": Expected error for insecure index")
assertEqual(t, strings.Contains(err.Error(), "insecure-registry"), true, index.Name+": Expected insecure-registry error for insecure index")
index.Secure = false
}
assertSecureIndex := func(index *registrytypes.IndexInfo) {
index.Secure = true
_, err := NewEndpoint(index, "", nil, APIVersionUnknown)
assertNotEqual(t, err, nil, index.Name+": Expected cert error for secure index")
assertEqual(t, strings.Contains(err.Error(), "certificate signed by unknown authority"), true, index.Name+": Expected cert error for secure index")
index.Secure = false
}
index := &registrytypes.IndexInfo{}
index.Name = makeURL("/v1/")
endpoint := expandEndpoint(index)
assertEqual(t, endpoint.String(), index.Name, "Expected endpoint to be "+index.Name)
if endpoint.Version != APIVersion1 {
t.Fatal("Expected endpoint to be v1")
}
assertInsecureIndex(index)
index.Name = makeURL("")
endpoint = expandEndpoint(index)
assertEqual(t, endpoint.String(), index.Name+"/v1/", index.Name+": Expected endpoint to be "+index.Name+"/v1/")
if endpoint.Version != APIVersion1 {
t.Fatal("Expected endpoint to be v1")
}
assertInsecureIndex(index)
httpURL := makeURL("")
index.Name = strings.SplitN(httpURL, "://", 2)[1]
endpoint = expandEndpoint(index)
assertEqual(t, endpoint.String(), httpURL+"/v1/", index.Name+": Expected endpoint to be "+httpURL+"/v1/")
if endpoint.Version != APIVersion1 {
t.Fatal("Expected endpoint to be v1")
}
assertInsecureIndex(index)
index.Name = makeHTTPSURL("/v1/")
endpoint = expandEndpoint(index)
assertEqual(t, endpoint.String(), index.Name, "Expected endpoint to be "+index.Name)
if endpoint.Version != APIVersion1 {
t.Fatal("Expected endpoint to be v1")
}
assertSecureIndex(index)
index.Name = makeHTTPSURL("")
endpoint = expandEndpoint(index)
assertEqual(t, endpoint.String(), index.Name+"/v1/", index.Name+": Expected endpoint to be "+index.Name+"/v1/")
if endpoint.Version != APIVersion1 {
t.Fatal("Expected endpoint to be v1")
}
assertSecureIndex(index)
httpsURL := makeHTTPSURL("")
index.Name = strings.SplitN(httpsURL, "://", 2)[1]
endpoint = expandEndpoint(index)
assertEqual(t, endpoint.String(), httpsURL+"/v1/", index.Name+": Expected endpoint to be "+httpsURL+"/v1/")
if endpoint.Version != APIVersion1 {
t.Fatal("Expected endpoint to be v1")
}
assertSecureIndex(index)
badEndpoints := []string{
"http://127.0.0.1/v1/",
"https://127.0.0.1/v1/",
"http://127.0.0.1",
"https://127.0.0.1",
"127.0.0.1",
}
for _, address := range badEndpoints {
index.Name = address
_, err := NewEndpoint(index, "", nil, APIVersionUnknown)
checkNotEqual(t, err, nil, "Expected error while expanding bad endpoint")
}
}
func TestGetRemoteHistory(t *testing.T) {
r := spawnTestRegistrySession(t)
hist, err := r.GetRemoteHistory(imageID, makeURL("/v1/"))
if err != nil {
t.Fatal(err)
}
assertEqual(t, len(hist), 2, "Expected 2 images in history")
assertEqual(t, hist[0], imageID, "Expected "+imageID+"as first ancestry")
assertEqual(t, hist[1], "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20",
"Unexpected second ancestry")
}
func TestLookupRemoteImage(t *testing.T) {
r := spawnTestRegistrySession(t)
err := r.LookupRemoteImage(imageID, makeURL("/v1/"))
assertEqual(t, err, nil, "Expected error of remote lookup to nil")
if err := r.LookupRemoteImage("abcdef", makeURL("/v1/")); err == nil {
t.Fatal("Expected error of remote lookup to not nil")
}
}
func TestGetRemoteImageJSON(t *testing.T) {
r := spawnTestRegistrySession(t)
json, size, err := r.GetRemoteImageJSON(imageID, makeURL("/v1/"))
if err != nil {
t.Fatal(err)
}
assertEqual(t, size, int64(154), "Expected size 154")
if len(json) <= 0 {
t.Fatal("Expected non-empty json")
}
_, _, err = r.GetRemoteImageJSON("abcdef", makeURL("/v1/"))
if err == nil {
t.Fatal("Expected image not found error")
}
}
func TestGetRemoteImageLayer(t *testing.T) {
r := spawnTestRegistrySession(t)
data, err := r.GetRemoteImageLayer(imageID, makeURL("/v1/"), 0)
if err != nil {
t.Fatal(err)
}
if data == nil {
t.Fatal("Expected non-nil data result")
}
_, err = r.GetRemoteImageLayer("abcdef", makeURL("/v1/"), 0)
if err == nil {
t.Fatal("Expected image not found error")
}
}
func TestGetRemoteTag(t *testing.T) {
r := spawnTestRegistrySession(t)
repoRef, err := reference.ParseNamed(REPO)
if err != nil {
t.Fatal(err)
}
tag, err := r.GetRemoteTag([]string{makeURL("/v1/")}, repoRef, "test")
if err != nil {
t.Fatal(err)
}
assertEqual(t, tag, imageID, "Expected tag test to map to "+imageID)
bazRef, err := reference.ParseNamed("foo42/baz")
if err != nil {
t.Fatal(err)
}
_, err = r.GetRemoteTag([]string{makeURL("/v1/")}, bazRef, "foo")
if err != ErrRepoNotFound {
t.Fatal("Expected ErrRepoNotFound error when fetching tag for bogus repo")
}
}
func TestGetRemoteTags(t *testing.T) {
r := spawnTestRegistrySession(t)
repoRef, err := reference.ParseNamed(REPO)
if err != nil {
t.Fatal(err)
}
tags, err := r.GetRemoteTags([]string{makeURL("/v1/")}, repoRef)
if err != nil {
t.Fatal(err)
}
assertEqual(t, len(tags), 2, "Expected two tags")
assertEqual(t, tags["latest"], imageID, "Expected tag latest to map to "+imageID)
assertEqual(t, tags["test"], imageID, "Expected tag test to map to "+imageID)
bazRef, err := reference.ParseNamed("foo42/baz")
if err != nil {
t.Fatal(err)
}
_, err = r.GetRemoteTags([]string{makeURL("/v1/")}, bazRef)
if err != ErrRepoNotFound {
t.Fatal("Expected ErrRepoNotFound error when fetching tags for bogus repo")
}
}
func TestGetRepositoryData(t *testing.T) {
r := spawnTestRegistrySession(t)
parsedURL, err := url.Parse(makeURL("/v1/"))
if err != nil {
t.Fatal(err)
}
host := "http://" + parsedURL.Host + "/v1/"
repoRef, err := reference.ParseNamed(REPO)
if err != nil {
t.Fatal(err)
}
data, err := r.GetRepositoryData(repoRef)
if err != nil {
t.Fatal(err)
}
assertEqual(t, len(data.ImgList), 2, "Expected 2 images in ImgList")
assertEqual(t, len(data.Endpoints), 2,
fmt.Sprintf("Expected 2 endpoints in Endpoints, found %d instead", len(data.Endpoints)))
assertEqual(t, data.Endpoints[0], host,
fmt.Sprintf("Expected first endpoint to be %s but found %s instead", host, data.Endpoints[0]))
assertEqual(t, data.Endpoints[1], "http://test.example.com/v1/",
fmt.Sprintf("Expected first endpoint to be http://test.example.com/v1/ but found %s instead", data.Endpoints[1]))
}
func TestPushImageJSONRegistry(t *testing.T) {
r := spawnTestRegistrySession(t)
imgData := &ImgData{
ID: "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20",
Checksum: "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37",
}
err := r.PushImageJSONRegistry(imgData, []byte{0x42, 0xdf, 0x0}, makeURL("/v1/"))
if err != nil {
t.Fatal(err)
}
}
func TestPushImageLayerRegistry(t *testing.T) {
r := spawnTestRegistrySession(t)
layer := strings.NewReader("")
_, _, err := r.PushImageLayerRegistry(imageID, layer, makeURL("/v1/"), []byte{})
if err != nil {
t.Fatal(err)
}
}
func TestParseRepositoryInfo(t *testing.T) {
type staticRepositoryInfo struct {
Index *registrytypes.IndexInfo
RemoteName string
CanonicalName string
LocalName string
Official bool
}
expectedRepoInfos := map[string]staticRepositoryInfo{
"fooo/bar": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "fooo/bar",
LocalName: "fooo/bar",
CanonicalName: "docker.io/fooo/bar",
Official: false,
},
"library/ubuntu": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "library/ubuntu",
LocalName: "ubuntu",
CanonicalName: "docker.io/library/ubuntu",
Official: true,
},
"nonlibrary/ubuntu": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "nonlibrary/ubuntu",
LocalName: "nonlibrary/ubuntu",
CanonicalName: "docker.io/nonlibrary/ubuntu",
Official: false,
},
"ubuntu": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "library/ubuntu",
LocalName: "ubuntu",
CanonicalName: "docker.io/library/ubuntu",
Official: true,
},
"other/library": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "other/library",
LocalName: "other/library",
CanonicalName: "docker.io/other/library",
Official: false,
},
"127.0.0.1:8000/private/moonbase": {
Index: &registrytypes.IndexInfo{
Name: "127.0.0.1:8000",
Official: false,
},
RemoteName: "private/moonbase",
LocalName: "127.0.0.1:8000/private/moonbase",
CanonicalName: "127.0.0.1:8000/private/moonbase",
Official: false,
},
"127.0.0.1:8000/privatebase": {
Index: &registrytypes.IndexInfo{
Name: "127.0.0.1:8000",
Official: false,
},
RemoteName: "privatebase",
LocalName: "127.0.0.1:8000/privatebase",
CanonicalName: "127.0.0.1:8000/privatebase",
Official: false,
},
"localhost:8000/private/moonbase": {
Index: &registrytypes.IndexInfo{
Name: "localhost:8000",
Official: false,
},
RemoteName: "private/moonbase",
LocalName: "localhost:8000/private/moonbase",
CanonicalName: "localhost:8000/private/moonbase",
Official: false,
},
"localhost:8000/privatebase": {
Index: &registrytypes.IndexInfo{
Name: "localhost:8000",
Official: false,
},
RemoteName: "privatebase",
LocalName: "localhost:8000/privatebase",
CanonicalName: "localhost:8000/privatebase",
Official: false,
},
"example.com/private/moonbase": {
Index: &registrytypes.IndexInfo{
Name: "example.com",
Official: false,
},
RemoteName: "private/moonbase",
LocalName: "example.com/private/moonbase",
CanonicalName: "example.com/private/moonbase",
Official: false,
},
"example.com/privatebase": {
Index: &registrytypes.IndexInfo{
Name: "example.com",
Official: false,
},
RemoteName: "privatebase",
LocalName: "example.com/privatebase",
CanonicalName: "example.com/privatebase",
Official: false,
},
"example.com:8000/private/moonbase": {
Index: &registrytypes.IndexInfo{
Name: "example.com:8000",
Official: false,
},
RemoteName: "private/moonbase",
LocalName: "example.com:8000/private/moonbase",
CanonicalName: "example.com:8000/private/moonbase",
Official: false,
},
"example.com:8000/privatebase": {
Index: &registrytypes.IndexInfo{
Name: "example.com:8000",
Official: false,
},
RemoteName: "privatebase",
LocalName: "example.com:8000/privatebase",
CanonicalName: "example.com:8000/privatebase",
Official: false,
},
"localhost/private/moonbase": {
Index: &registrytypes.IndexInfo{
Name: "localhost",
Official: false,
},
RemoteName: "private/moonbase",
LocalName: "localhost/private/moonbase",
CanonicalName: "localhost/private/moonbase",
Official: false,
},
"localhost/privatebase": {
Index: &registrytypes.IndexInfo{
Name: "localhost",
Official: false,
},
RemoteName: "privatebase",
LocalName: "localhost/privatebase",
CanonicalName: "localhost/privatebase",
Official: false,
},
IndexName + "/public/moonbase": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "public/moonbase",
LocalName: "public/moonbase",
CanonicalName: "docker.io/public/moonbase",
Official: false,
},
"index." + IndexName + "/public/moonbase": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "public/moonbase",
LocalName: "public/moonbase",
CanonicalName: "docker.io/public/moonbase",
Official: false,
},
"ubuntu-12.04-base": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "library/ubuntu-12.04-base",
LocalName: "ubuntu-12.04-base",
CanonicalName: "docker.io/library/ubuntu-12.04-base",
Official: true,
},
IndexName + "/ubuntu-12.04-base": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "library/ubuntu-12.04-base",
LocalName: "ubuntu-12.04-base",
CanonicalName: "docker.io/library/ubuntu-12.04-base",
Official: true,
},
"index." + IndexName + "/ubuntu-12.04-base": {
Index: &registrytypes.IndexInfo{
Name: IndexName,
Official: true,
},
RemoteName: "library/ubuntu-12.04-base",
LocalName: "ubuntu-12.04-base",
CanonicalName: "docker.io/library/ubuntu-12.04-base",
Official: true,
},
}
for reposName, expectedRepoInfo := range expectedRepoInfos {
named, err := reference.WithName(reposName)
if err != nil {
t.Error(err)
}
repoInfo, err := ParseRepositoryInfo(named)
if err != nil {
t.Error(err)
} else {
checkEqual(t, repoInfo.Index.Name, expectedRepoInfo.Index.Name, reposName)
checkEqual(t, repoInfo.RemoteName(), expectedRepoInfo.RemoteName, reposName)
checkEqual(t, repoInfo.Name(), expectedRepoInfo.LocalName, reposName)
checkEqual(t, repoInfo.FullName(), expectedRepoInfo.CanonicalName, reposName)
checkEqual(t, repoInfo.Index.Official, expectedRepoInfo.Index.Official, reposName)
checkEqual(t, repoInfo.Official, expectedRepoInfo.Official, reposName)
}
}
}
func TestNewIndexInfo(t *testing.T) {
testIndexInfo := func(config *registrytypes.ServiceConfig, expectedIndexInfos map[string]*registrytypes.IndexInfo) {
for indexName, expectedIndexInfo := range expectedIndexInfos {
index, err := newIndexInfo(config, indexName)
if err != nil {
t.Fatal(err)
} else {
checkEqual(t, index.Name, expectedIndexInfo.Name, indexName+" name")
checkEqual(t, index.Official, expectedIndexInfo.Official, indexName+" is official")
checkEqual(t, index.Secure, expectedIndexInfo.Secure, indexName+" is secure")
checkEqual(t, len(index.Mirrors), len(expectedIndexInfo.Mirrors), indexName+" mirrors")
}
}
}
config := NewServiceConfig(nil)
noMirrors := []string{}
expectedIndexInfos := map[string]*registrytypes.IndexInfo{
IndexName: {
Name: IndexName,
Official: true,
Secure: true,
Mirrors: noMirrors,
},
"index." + IndexName: {
Name: IndexName,
Official: true,
Secure: true,
Mirrors: noMirrors,
},
"example.com": {
Name: "example.com",
Official: false,
Secure: true,
Mirrors: noMirrors,
},
"127.0.0.1:5000": {
Name: "127.0.0.1:5000",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
}
testIndexInfo(config, expectedIndexInfos)
publicMirrors := []string{"http://mirror1.local", "http://mirror2.local"}
config = makeServiceConfig(publicMirrors, []string{"example.com"})
expectedIndexInfos = map[string]*registrytypes.IndexInfo{
IndexName: {
Name: IndexName,
Official: true,
Secure: true,
Mirrors: publicMirrors,
},
"index." + IndexName: {
Name: IndexName,
Official: true,
Secure: true,
Mirrors: publicMirrors,
},
"example.com": {
Name: "example.com",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
"example.com:5000": {
Name: "example.com:5000",
Official: false,
Secure: true,
Mirrors: noMirrors,
},
"127.0.0.1": {
Name: "127.0.0.1",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
"127.0.0.1:5000": {
Name: "127.0.0.1:5000",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
"other.com": {
Name: "other.com",
Official: false,
Secure: true,
Mirrors: noMirrors,
},
}
testIndexInfo(config, expectedIndexInfos)
config = makeServiceConfig(nil, []string{"42.42.0.0/16"})
expectedIndexInfos = map[string]*registrytypes.IndexInfo{
"example.com": {
Name: "example.com",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
"example.com:5000": {
Name: "example.com:5000",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
"127.0.0.1": {
Name: "127.0.0.1",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
"127.0.0.1:5000": {
Name: "127.0.0.1:5000",
Official: false,
Secure: false,
Mirrors: noMirrors,
},
"other.com": {
Name: "other.com",
Official: false,
Secure: true,
Mirrors: noMirrors,
},
}
testIndexInfo(config, expectedIndexInfos)
}
func TestMirrorEndpointLookup(t *testing.T) {
containsMirror := func(endpoints []APIEndpoint) bool {
for _, pe := range endpoints {
if pe.URL == "my.mirror" {
return true
}
}
return false
}
s := Service{Config: makeServiceConfig([]string{"my.mirror"}, nil)}
imageName, err := reference.WithName(IndexName + "/test/image")
if err != nil {
t.Error(err)
}
pushAPIEndpoints, err := s.LookupPushEndpoints(imageName)
if err != nil {
t.Fatal(err)
}
if containsMirror(pushAPIEndpoints) {
t.Fatal("Push endpoint should not contain mirror")
}
pullAPIEndpoints, err := s.LookupPullEndpoints(imageName)
if err != nil {
t.Fatal(err)
}
if !containsMirror(pullAPIEndpoints) {
t.Fatal("Pull endpoint should contain mirror")
}
}
func TestPushRegistryTag(t *testing.T) {
r := spawnTestRegistrySession(t)
repoRef, err := reference.ParseNamed(REPO)
if err != nil {
t.Fatal(err)
}
err = r.PushRegistryTag(repoRef, imageID, "stable", makeURL("/v1/"))
if err != nil {
t.Fatal(err)
}
}
func TestPushImageJSONIndex(t *testing.T) {
r := spawnTestRegistrySession(t)
imgData := []*ImgData{
{
ID: "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20",
Checksum: "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37",
},
{
ID: "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d",
Checksum: "sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2",
},
}
repoRef, err := reference.ParseNamed(REPO)
if err != nil {
t.Fatal(err)
}
repoData, err := r.PushImageJSONIndex(repoRef, imgData, false, nil)
if err != nil {
t.Fatal(err)
}
if repoData == nil {
t.Fatal("Expected RepositoryData object")
}
repoData, err = r.PushImageJSONIndex(repoRef, imgData, true, []string{r.indexEndpoint.String()})
if err != nil {
t.Fatal(err)
}
if repoData == nil {
t.Fatal("Expected RepositoryData object")
}
}
func TestSearchRepositories(t *testing.T) {
r := spawnTestRegistrySession(t)
results, err := r.SearchRepositories("fakequery")
if err != nil {
t.Fatal(err)
}
if results == nil {
t.Fatal("Expected non-nil SearchResults object")
}
assertEqual(t, results.NumResults, 1, "Expected 1 search results")
assertEqual(t, results.Query, "fakequery", "Expected 'fakequery' as query")
assertEqual(t, results.Results[0].StarCount, 42, "Expected 'fakeimage' to have 42 stars")
}
func TestTrustedLocation(t *testing.T) {
for _, url := range []string{"http://example.com", "https://example.com:7777", "http://docker.io", "http://test.docker.com", "https://fakedocker.com"} {
req, _ := http.NewRequest("GET", url, nil)
if trustedLocation(req) == true {
t.Fatalf("'%s' shouldn't be detected as a trusted location", url)
}
}
for _, url := range []string{"https://docker.io", "https://test.docker.com:80"} {
req, _ := http.NewRequest("GET", url, nil)
if trustedLocation(req) == false {
t.Fatalf("'%s' should be detected as a trusted location", url)
}
}
}
func TestAddRequiredHeadersToRedirectedRequests(t *testing.T) {
for _, urls := range [][]string{
{"http://docker.io", "https://docker.com"},
{"https://foo.docker.io:7777", "http://bar.docker.com"},
{"https://foo.docker.io", "https://example.com"},
} {
reqFrom, _ := http.NewRequest("GET", urls[0], nil)
reqFrom.Header.Add("Content-Type", "application/json")
reqFrom.Header.Add("Authorization", "super_secret")
reqTo, _ := http.NewRequest("GET", urls[1], nil)
addRequiredHeadersToRedirectedRequests(reqTo, []*http.Request{reqFrom})
if len(reqTo.Header) != 1 {
t.Fatalf("Expected 1 headers, got %d", len(reqTo.Header))
}
if reqTo.Header.Get("Content-Type") != "application/json" {
t.Fatal("'Content-Type' should be 'application/json'")
}
if reqTo.Header.Get("Authorization") != "" {
t.Fatal("'Authorization' should be empty")
}
}
for _, urls := range [][]string{
{"https://docker.io", "https://docker.com"},
{"https://foo.docker.io:7777", "https://bar.docker.com"},
} {
reqFrom, _ := http.NewRequest("GET", urls[0], nil)
reqFrom.Header.Add("Content-Type", "application/json")
reqFrom.Header.Add("Authorization", "super_secret")
reqTo, _ := http.NewRequest("GET", urls[1], nil)
addRequiredHeadersToRedirectedRequests(reqTo, []*http.Request{reqFrom})
if len(reqTo.Header) != 2 {
t.Fatalf("Expected 2 headers, got %d", len(reqTo.Header))
}
if reqTo.Header.Get("Content-Type") != "application/json" {
t.Fatal("'Content-Type' should be 'application/json'")
}
if reqTo.Header.Get("Authorization") != "super_secret" {
t.Fatal("'Authorization' should be 'super_secret'")
}
}
}
func TestIsSecureIndex(t *testing.T) {
tests := []struct {
addr string
insecureRegistries []string
expected bool
}{
{IndexName, nil, true},
{"example.com", []string{}, true},
{"example.com", []string{"example.com"}, false},
{"localhost", []string{"localhost:5000"}, false},
{"localhost:5000", []string{"localhost:5000"}, false},
{"localhost", []string{"example.com"}, false},
{"127.0.0.1:5000", []string{"127.0.0.1:5000"}, false},
{"localhost", nil, false},
{"localhost:5000", nil, false},
{"127.0.0.1", nil, false},
{"localhost", []string{"example.com"}, false},
{"127.0.0.1", []string{"example.com"}, false},
{"example.com", nil, true},
{"example.com", []string{"example.com"}, false},
{"127.0.0.1", []string{"example.com"}, false},
{"127.0.0.1:5000", []string{"example.com"}, false},
{"example.com:5000", []string{"42.42.0.0/16"}, false},
{"example.com", []string{"42.42.0.0/16"}, false},
{"example.com:5000", []string{"42.42.42.42/8"}, false},
{"127.0.0.1:5000", []string{"127.0.0.0/8"}, false},
{"42.42.42.42:5000", []string{"42.1.1.1/8"}, false},
{"invalid.domain.com", []string{"42.42.0.0/16"}, true},
{"invalid.domain.com", []string{"invalid.domain.com"}, false},
{"invalid.domain.com:5000", []string{"invalid.domain.com"}, true},
{"invalid.domain.com:5000", []string{"invalid.domain.com:5000"}, false},
}
for _, tt := range tests {
config := makeServiceConfig(nil, tt.insecureRegistries)
if sec := isSecureIndex(config, tt.addr); sec != tt.expected {
t.Errorf("isSecureIndex failed for %q %v, expected %v got %v", tt.addr, tt.insecureRegistries, tt.expected, sec)
}
}
}
type debugTransport struct {
http.RoundTripper
log func(...interface{})
}
func (tr debugTransport) RoundTrip(req *http.Request) (*http.Response, error) {
dump, err := httputil.DumpRequestOut(req, false)
if err != nil {
tr.log("could not dump request")
}
tr.log(string(dump))
resp, err := tr.RoundTripper.RoundTrip(req)
if err != nil {
return nil, err
}
dump, err = httputil.DumpResponse(resp, false)
if err != nil {
tr.log("could not dump response")
}
tr.log(string(dump))
return resp, err
}