github.com/uriddle/docker@v0.0.0-20210926094723-4072e6aeb013/distribution/registry_unit_test.go (about)

     1  package distribution
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"os"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/Sirupsen/logrus"
    11  	"github.com/docker/docker/reference"
    12  	"github.com/docker/docker/registry"
    13  	"github.com/docker/docker/utils"
    14  	"github.com/docker/engine-api/types"
    15  	registrytypes "github.com/docker/engine-api/types/registry"
    16  	"golang.org/x/net/context"
    17  )
    18  
    19  func TestTokenPassThru(t *testing.T) {
    20  	authConfig := &types.AuthConfig{
    21  		RegistryToken: "mysecrettoken",
    22  	}
    23  	gotToken := false
    24  	handler := func(w http.ResponseWriter, r *http.Request) {
    25  		if strings.Contains(r.Header.Get("Authorization"), authConfig.RegistryToken) {
    26  			logrus.Debug("Detected registry token in auth header")
    27  			gotToken = true
    28  		}
    29  		if r.RequestURI == "/v2/" {
    30  			w.Header().Set("WWW-Authenticate", `Bearer realm="foorealm"`)
    31  			w.WriteHeader(401)
    32  		}
    33  	}
    34  	ts := httptest.NewServer(http.HandlerFunc(handler))
    35  	defer ts.Close()
    36  
    37  	tmp, err := utils.TestDirectory("")
    38  	if err != nil {
    39  		t.Fatal(err)
    40  	}
    41  	defer os.RemoveAll(tmp)
    42  
    43  	endpoint := registry.APIEndpoint{
    44  		Mirror:       false,
    45  		URL:          ts.URL,
    46  		Version:      2,
    47  		Official:     false,
    48  		TrimHostname: false,
    49  		TLSConfig:    nil,
    50  		//VersionHeader: "verheader",
    51  	}
    52  	n, _ := reference.ParseNamed("testremotename")
    53  	repoInfo := &registry.RepositoryInfo{
    54  		Named: n,
    55  		Index: &registrytypes.IndexInfo{
    56  			Name:     "testrepo",
    57  			Mirrors:  nil,
    58  			Secure:   false,
    59  			Official: false,
    60  		},
    61  		Official: false,
    62  	}
    63  	imagePullConfig := &ImagePullConfig{
    64  		MetaHeaders: http.Header{},
    65  		AuthConfig:  authConfig,
    66  	}
    67  	puller, err := newPuller(endpoint, repoInfo, imagePullConfig)
    68  	if err != nil {
    69  		t.Fatal(err)
    70  	}
    71  	p := puller.(*v2Puller)
    72  	ctx := context.Background()
    73  	p.repo, _, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "pull")
    74  	if err != nil {
    75  		t.Fatal(err)
    76  	}
    77  
    78  	logrus.Debug("About to pull")
    79  	// We expect it to fail, since we haven't mock'd the full registry exchange in our handler above
    80  	tag, _ := reference.WithTag(n, "tag_goes_here")
    81  	_ = p.pullV2Repository(ctx, tag)
    82  
    83  	if !gotToken {
    84  		t.Fatal("Failed to receive registry token")
    85  	}
    86  
    87  }