Browse Source

Merge auth package within registry

Docker-DCO-1.1-Signed-off-by: Guillaume J. Charmes <guillaume@charmes.net> (github: creack)
Guillaume J. Charmes 11 năm trước cách đây
mục cha
commit
8d88ea0c15
10 tập tin đã thay đổi với 57 bổ sung65 xóa
  1. 13 14
      api/client.go
  2. 11 11
      api/server.go
  3. 0 3
      auth/MAINTAINERS
  4. 3 4
      buildfile.go
  5. 6 6
      integration/auth_test.go
  6. 1 1
      registry/auth.go
  7. 1 1
      registry/auth_test.go
  8. 9 10
      registry/registry.go
  9. 2 3
      registry/registry_test.go
  10. 11 12
      server.go

+ 13 - 14
api/client.go

@@ -8,7 +8,6 @@ import (
 	"errors"
 	"fmt"
 	"github.com/dotcloud/docker/archive"
-	"github.com/dotcloud/docker/auth"
 	"github.com/dotcloud/docker/dockerversion"
 	"github.com/dotcloud/docker/engine"
 	"github.com/dotcloud/docker/nat"
@@ -229,7 +228,7 @@ func (cli *DockerCli) CmdBuild(args ...string) error {
 
 // 'docker login': login / register a user to registry service.
 func (cli *DockerCli) CmdLogin(args ...string) error {
-	cmd := cli.Subcmd("login", "[OPTIONS] [SERVER]", "Register or Login to a docker registry server, if no server is specified \""+auth.IndexServerAddress()+"\" is the default.")
+	cmd := cli.Subcmd("login", "[OPTIONS] [SERVER]", "Register or Login to a docker registry server, if no server is specified \""+registry.IndexServerAddress()+"\" is the default.")
 
 	var username, password, email string
 
@@ -240,7 +239,7 @@ func (cli *DockerCli) CmdLogin(args ...string) error {
 	if err != nil {
 		return nil
 	}
-	serverAddress := auth.IndexServerAddress()
+	serverAddress := registry.IndexServerAddress()
 	if len(cmd.Args()) > 0 {
 		serverAddress = cmd.Arg(0)
 	}
@@ -266,7 +265,7 @@ func (cli *DockerCli) CmdLogin(args ...string) error {
 	cli.LoadConfigFile()
 	authconfig, ok := cli.configFile.Configs[serverAddress]
 	if !ok {
-		authconfig = auth.AuthConfig{}
+		authconfig = registry.AuthConfig{}
 	}
 
 	if username == "" {
@@ -311,7 +310,7 @@ func (cli *DockerCli) CmdLogin(args ...string) error {
 	stream, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress], false)
 	if statusCode == 401 {
 		delete(cli.configFile.Configs, serverAddress)
-		auth.SaveConfig(cli.configFile)
+		registry.SaveConfig(cli.configFile)
 		return err
 	}
 	if err != nil {
@@ -320,10 +319,10 @@ func (cli *DockerCli) CmdLogin(args ...string) error {
 	var out2 engine.Env
 	err = out2.Decode(stream)
 	if err != nil {
-		cli.configFile, _ = auth.LoadConfig(os.Getenv("HOME"))
+		cli.configFile, _ = registry.LoadConfig(os.Getenv("HOME"))
 		return err
 	}
-	auth.SaveConfig(cli.configFile)
+	registry.SaveConfig(cli.configFile)
 	if out2.Get("Status") != "" {
 		fmt.Fprintf(cli.out, "%s\n", out2.Get("Status"))
 	}
@@ -1008,7 +1007,7 @@ func (cli *DockerCli) CmdPush(args ...string) error {
 	// Custom repositories can have different rules, and we must also
 	// allow pushing by image ID.
 	if len(strings.SplitN(name, "/", 2)) == 1 {
-		username := cli.configFile.Configs[auth.IndexServerAddress()].Username
+		username := cli.configFile.Configs[registry.IndexServerAddress()].Username
 		if username == "" {
 			username = "<user>"
 		}
@@ -1016,7 +1015,7 @@ func (cli *DockerCli) CmdPush(args ...string) error {
 	}
 
 	v := url.Values{}
-	push := func(authConfig auth.AuthConfig) error {
+	push := func(authConfig registry.AuthConfig) error {
 		buf, err := json.Marshal(authConfig)
 		if err != nil {
 			return err
@@ -1075,7 +1074,7 @@ func (cli *DockerCli) CmdPull(args ...string) error {
 	v.Set("fromImage", remote)
 	v.Set("tag", *tag)
 
-	pull := func(authConfig auth.AuthConfig) error {
+	pull := func(authConfig registry.AuthConfig) error {
 		buf, err := json.Marshal(authConfig)
 		if err != nil {
 			return err
@@ -2058,8 +2057,8 @@ func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo b
 	if passAuthInfo {
 		cli.LoadConfigFile()
 		// Resolve the Auth config relevant for this server
-		authConfig := cli.configFile.ResolveAuthConfig(auth.IndexServerAddress())
-		getHeaders := func(authConfig auth.AuthConfig) (map[string][]string, error) {
+		authConfig := cli.configFile.ResolveAuthConfig(registry.IndexServerAddress())
+		getHeaders := func(authConfig registry.AuthConfig) (map[string][]string, error) {
 			buf, err := json.Marshal(authConfig)
 			if err != nil {
 				return nil, err
@@ -2340,7 +2339,7 @@ func (cli *DockerCli) Subcmd(name, signature, description string) *flag.FlagSet
 }
 
 func (cli *DockerCli) LoadConfigFile() (err error) {
-	cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
+	cli.configFile, err = registry.LoadConfig(os.Getenv("HOME"))
 	if err != nil {
 		fmt.Fprintf(cli.err, "WARNING: %s\n", err)
 	}
@@ -2422,7 +2421,7 @@ func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *Doc
 type DockerCli struct {
 	proto      string
 	addr       string
-	configFile *auth.ConfigFile
+	configFile *registry.ConfigFile
 	in         io.ReadCloser
 	out        io.Writer
 	err        io.Writer

+ 11 - 11
api/server.go

@@ -8,12 +8,12 @@ import (
 	"encoding/json"
 	"expvar"
 	"fmt"
-	"github.com/dotcloud/docker/auth"
 	"github.com/dotcloud/docker/engine"
 	"github.com/dotcloud/docker/pkg/listenbuffer"
 	"github.com/dotcloud/docker/pkg/systemd"
 	"github.com/dotcloud/docker/pkg/user"
 	"github.com/dotcloud/docker/pkg/version"
+	"github.com/dotcloud/docker/registry"
 	"github.com/dotcloud/docker/utils"
 	"github.com/gorilla/mux"
 	"io"
@@ -381,13 +381,13 @@ func postImagesCreate(eng *engine.Engine, version version.Version, w http.Respon
 		job   *engine.Job
 	)
 	authEncoded := r.Header.Get("X-Registry-Auth")
-	authConfig := &auth.AuthConfig{}
+	authConfig := &registry.AuthConfig{}
 	if authEncoded != "" {
 		authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
 		if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
 			// for a pull it is not an error if no auth was given
 			// to increase compatibility with the existing api it is defaulting to be empty
-			authConfig = &auth.AuthConfig{}
+			authConfig = &registry.AuthConfig{}
 		}
 	}
 	if image != "" { //pull
@@ -429,7 +429,7 @@ func getImagesSearch(eng *engine.Engine, version version.Version, w http.Respons
 	}
 	var (
 		authEncoded = r.Header.Get("X-Registry-Auth")
-		authConfig  = &auth.AuthConfig{}
+		authConfig  = &registry.AuthConfig{}
 		metaHeaders = map[string][]string{}
 	)
 
@@ -438,7 +438,7 @@ func getImagesSearch(eng *engine.Engine, version version.Version, w http.Respons
 		if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
 			// for a search it is not an error if no auth was given
 			// to increase compatibility with the existing api it is defaulting to be empty
-			authConfig = &auth.AuthConfig{}
+			authConfig = &registry.AuthConfig{}
 		}
 	}
 	for k, v := range r.Header {
@@ -494,7 +494,7 @@ func postImagesPush(eng *engine.Engine, version version.Version, w http.Response
 	if err := parseForm(r); err != nil {
 		return err
 	}
-	authConfig := &auth.AuthConfig{}
+	authConfig := &registry.AuthConfig{}
 
 	authEncoded := r.Header.Get("X-Registry-Auth")
 	if authEncoded != "" {
@@ -502,7 +502,7 @@ func postImagesPush(eng *engine.Engine, version version.Version, w http.Response
 		authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
 		if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
 			// to increase compatibility to existing api it is defaulting to be empty
-			authConfig = &auth.AuthConfig{}
+			authConfig = &registry.AuthConfig{}
 		}
 	} else {
 		// the old format is supported for compatibility if there was no authConfig header
@@ -823,9 +823,9 @@ func postBuild(eng *engine.Engine, version version.Version, w http.ResponseWrite
 	}
 	var (
 		authEncoded       = r.Header.Get("X-Registry-Auth")
-		authConfig        = &auth.AuthConfig{}
+		authConfig        = &registry.AuthConfig{}
 		configFileEncoded = r.Header.Get("X-Registry-Config")
-		configFile        = &auth.ConfigFile{}
+		configFile        = &registry.ConfigFile{}
 		job               = eng.Job("build")
 	)
 
@@ -838,7 +838,7 @@ func postBuild(eng *engine.Engine, version version.Version, w http.ResponseWrite
 		if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
 			// for a pull it is not an error if no auth was given
 			// to increase compatibility with the existing api it is defaulting to be empty
-			authConfig = &auth.AuthConfig{}
+			authConfig = &registry.AuthConfig{}
 		}
 	}
 
@@ -847,7 +847,7 @@ func postBuild(eng *engine.Engine, version version.Version, w http.ResponseWrite
 		if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil {
 			// for a pull it is not an error if no auth was given
 			// to increase compatibility with the existing api it is defaulting to be empty
-			configFile = &auth.ConfigFile{}
+			configFile = &registry.ConfigFile{}
 		}
 	}
 

+ 0 - 3
auth/MAINTAINERS

@@ -1,3 +0,0 @@
-Sam Alba <sam@dotcloud.com> (@samalba)
-Joffrey Fuhrer <joffrey@dotcloud.com> (@shin-)
-Ken Cochrane <ken@dotcloud.com> (@kencochrane)

+ 3 - 4
buildfile.go

@@ -7,7 +7,6 @@ import (
 	"errors"
 	"fmt"
 	"github.com/dotcloud/docker/archive"
-	"github.com/dotcloud/docker/auth"
 	"github.com/dotcloud/docker/registry"
 	"github.com/dotcloud/docker/runconfig"
 	"github.com/dotcloud/docker/runtime"
@@ -49,8 +48,8 @@ type buildFile struct {
 	utilizeCache bool
 	rm           bool
 
-	authConfig *auth.AuthConfig
-	configFile *auth.ConfigFile
+	authConfig *registry.AuthConfig
+	configFile *registry.ConfigFile
 
 	tmpContainers map[string]struct{}
 	tmpImages     map[string]struct{}
@@ -793,7 +792,7 @@ func (b *buildFile) BuildStep(name, expression string) error {
 	return nil
 }
 
-func NewBuildFile(srv *Server, outStream, errStream io.Writer, verbose, utilizeCache, rm bool, outOld io.Writer, sf *utils.StreamFormatter, auth *auth.AuthConfig, authConfigFile *auth.ConfigFile) BuildFile {
+func NewBuildFile(srv *Server, outStream, errStream io.Writer, verbose, utilizeCache, rm bool, outOld io.Writer, sf *utils.StreamFormatter, auth *registry.AuthConfig, authConfigFile *registry.ConfigFile) BuildFile {
 	return &buildFile{
 		runtime:       srv.runtime,
 		srv:           srv,

+ 6 - 6
integration/auth_test.go

@@ -4,7 +4,7 @@ import (
 	"crypto/rand"
 	"encoding/hex"
 	"fmt"
-	"github.com/dotcloud/docker/auth"
+	"github.com/dotcloud/docker/registry"
 	"os"
 	"strings"
 	"testing"
@@ -18,13 +18,13 @@ import (
 func TestLogin(t *testing.T) {
 	os.Setenv("DOCKER_INDEX_URL", "https://indexstaging-docker.dotcloud.com")
 	defer os.Setenv("DOCKER_INDEX_URL", "")
-	authConfig := &auth.AuthConfig{
+	authConfig := &registry.AuthConfig{
 		Username:      "unittester",
 		Password:      "surlautrerivejetattendrai",
 		Email:         "noise+unittester@docker.com",
 		ServerAddress: "https://indexstaging-docker.dotcloud.com/v1/",
 	}
-	status, err := auth.Login(authConfig, nil)
+	status, err := registry.Login(authConfig, nil)
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -41,13 +41,13 @@ func TestCreateAccount(t *testing.T) {
 	}
 	token := hex.EncodeToString(tokenBuffer)[:12]
 	username := "ut" + token
-	authConfig := &auth.AuthConfig{
+	authConfig := &registry.AuthConfig{
 		Username:      username,
 		Password:      "test42",
 		Email:         fmt.Sprintf("docker-ut+%s@example.com", token),
 		ServerAddress: "https://indexstaging-docker.dotcloud.com/v1/",
 	}
-	status, err := auth.Login(authConfig, nil)
+	status, err := registry.Login(authConfig, nil)
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -59,7 +59,7 @@ func TestCreateAccount(t *testing.T) {
 		t.Fatalf("Expected status: \"%s\", found \"%s\" instead.", expectedStatus, status)
 	}
 
-	status, err = auth.Login(authConfig, nil)
+	status, err = registry.Login(authConfig, nil)
 	if err == nil {
 		t.Fatalf("Expected error but found nil instead")
 	}

+ 1 - 1
auth/auth.go → registry/auth.go

@@ -1,4 +1,4 @@
-package auth
+package registry
 
 import (
 	"encoding/base64"

+ 1 - 1
auth/auth_test.go → registry/auth_test.go

@@ -1,4 +1,4 @@
-package auth
+package registry
 
 import (
 	"io/ioutil"

+ 9 - 10
registry/registry.go

@@ -6,7 +6,6 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
-	"github.com/dotcloud/docker/auth"
 	"github.com/dotcloud/docker/utils"
 	"io"
 	"io/ioutil"
@@ -27,7 +26,7 @@ var (
 )
 
 func pingRegistryEndpoint(endpoint string) (bool, error) {
-	if endpoint == auth.IndexServerAddress() {
+	if endpoint == IndexServerAddress() {
 		// Skip the check, we now this one is valid
 		// (and we never want to fallback to http in case of error)
 		return false, nil
@@ -103,7 +102,7 @@ func ResolveRepositoryName(reposName string) (string, string, error) {
 		nameParts[0] != "localhost" {
 		// This is a Docker Index repos (ex: samalba/hipache or ubuntu)
 		err := validateRepositoryName(reposName)
-		return auth.IndexServerAddress(), reposName, err
+		return IndexServerAddress(), reposName, err
 	}
 	if len(nameParts) < 2 {
 		// There is a dot in repos name (and no registry address)
@@ -601,7 +600,7 @@ func (r *Registry) PushImageJSONIndex(remote string, imgList []*ImgData, validat
 
 func (r *Registry) SearchRepositories(term string) (*SearchResults, error) {
 	utils.Debugf("Index server: %s", r.indexEndpoint)
-	u := auth.IndexServerAddress() + "search?q=" + url.QueryEscape(term)
+	u := IndexServerAddress() + "search?q=" + url.QueryEscape(term)
 	req, err := r.reqFactory.NewRequest("GET", u, nil)
 	if err != nil {
 		return nil, err
@@ -627,12 +626,12 @@ func (r *Registry) SearchRepositories(term string) (*SearchResults, error) {
 	return result, err
 }
 
-func (r *Registry) GetAuthConfig(withPasswd bool) *auth.AuthConfig {
+func (r *Registry) GetAuthConfig(withPasswd bool) *AuthConfig {
 	password := ""
 	if withPasswd {
 		password = r.authConfig.Password
 	}
-	return &auth.AuthConfig{
+	return &AuthConfig{
 		Username: r.authConfig.Username,
 		Password: password,
 		Email:    r.authConfig.Email,
@@ -668,12 +667,12 @@ type ImgData struct {
 
 type Registry struct {
 	client        *http.Client
-	authConfig    *auth.AuthConfig
+	authConfig    *AuthConfig
 	reqFactory    *utils.HTTPRequestFactory
 	indexEndpoint string
 }
 
-func NewRegistry(authConfig *auth.AuthConfig, factory *utils.HTTPRequestFactory, indexEndpoint string) (r *Registry, err error) {
+func NewRegistry(authConfig *AuthConfig, factory *utils.HTTPRequestFactory, indexEndpoint string) (r *Registry, err error) {
 	httpTransport := &http.Transport{
 		DisableKeepAlives: true,
 		Proxy:             http.ProxyFromEnvironment,
@@ -693,13 +692,13 @@ func NewRegistry(authConfig *auth.AuthConfig, factory *utils.HTTPRequestFactory,
 
 	// If we're working with a standalone private registry over HTTPS, send Basic Auth headers
 	// alongside our requests.
-	if indexEndpoint != auth.IndexServerAddress() && strings.HasPrefix(indexEndpoint, "https://") {
+	if indexEndpoint != IndexServerAddress() && strings.HasPrefix(indexEndpoint, "https://") {
 		standalone, err := pingRegistryEndpoint(indexEndpoint)
 		if err != nil {
 			return nil, err
 		}
 		if standalone {
-			utils.Debugf("Endpoint %s is eligible for private registry auth. Enabling decorator.", indexEndpoint)
+			utils.Debugf("Endpoint %s is eligible for private registry registry. Enabling decorator.", indexEndpoint)
 			dec := utils.NewHTTPAuthDecorator(authConfig.Username, authConfig.Password)
 			factory.AddDecorator(dec)
 		}

+ 2 - 3
registry/registry_test.go

@@ -1,7 +1,6 @@
 package registry
 
 import (
-	"github.com/dotcloud/docker/auth"
 	"github.com/dotcloud/docker/utils"
 	"strings"
 	"testing"
@@ -14,7 +13,7 @@ var (
 )
 
 func spawnTestRegistry(t *testing.T) *Registry {
-	authConfig := &auth.AuthConfig{}
+	authConfig := &AuthConfig{}
 	r, err := NewRegistry(authConfig, utils.NewHTTPRequestFactory(), makeURL("/v1/"))
 	if err != nil {
 		t.Fatal(err)
@@ -137,7 +136,7 @@ func TestResolveRepositoryName(t *testing.T) {
 	if err != nil {
 		t.Fatal(err)
 	}
-	assertEqual(t, ep, auth.IndexServerAddress(), "Expected endpoint to be index server address")
+	assertEqual(t, ep, IndexServerAddress(), "Expected endpoint to be index server address")
 	assertEqual(t, repo, "fooo/bar", "Expected resolved repo to be foo/bar")
 
 	u := makeURL("")[7:]

+ 11 - 12
server.go

@@ -4,7 +4,6 @@ import (
 	"encoding/json"
 	"fmt"
 	"github.com/dotcloud/docker/archive"
-	"github.com/dotcloud/docker/auth"
 	"github.com/dotcloud/docker/daemonconfig"
 	"github.com/dotcloud/docker/dockerversion"
 	"github.com/dotcloud/docker/engine"
@@ -199,19 +198,19 @@ func (srv *Server) ContainerKill(job *engine.Job) engine.Status {
 func (srv *Server) Auth(job *engine.Job) engine.Status {
 	var (
 		err        error
-		authConfig = &auth.AuthConfig{}
+		authConfig = &registry.AuthConfig{}
 	)
 
 	job.GetenvJson("authConfig", authConfig)
 	// TODO: this is only done here because auth and registry need to be merged into one pkg
-	if addr := authConfig.ServerAddress; addr != "" && addr != auth.IndexServerAddress() {
+	if addr := authConfig.ServerAddress; addr != "" && addr != registry.IndexServerAddress() {
 		addr, err = registry.ExpandAndVerifyRegistryUrl(addr)
 		if err != nil {
 			return job.Error(err)
 		}
 		authConfig.ServerAddress = addr
 	}
-	status, err := auth.Login(authConfig, srv.HTTPRequestFactory(nil))
+	status, err := registry.Login(authConfig, srv.HTTPRequestFactory(nil))
 	if err != nil {
 		return job.Error(err)
 	}
@@ -431,8 +430,8 @@ func (srv *Server) Build(job *engine.Job) engine.Status {
 		suppressOutput = job.GetenvBool("q")
 		noCache        = job.GetenvBool("nocache")
 		rm             = job.GetenvBool("rm")
-		authConfig     = &auth.AuthConfig{}
-		configFile     = &auth.ConfigFile{}
+		authConfig     = &registry.AuthConfig{}
+		configFile     = &registry.ConfigFile{}
 		tag            string
 		context        io.ReadCloser
 	)
@@ -611,12 +610,12 @@ func (srv *Server) ImagesSearch(job *engine.Job) engine.Status {
 	var (
 		term        = job.Args[0]
 		metaHeaders = map[string][]string{}
-		authConfig  = &auth.AuthConfig{}
+		authConfig  = &registry.AuthConfig{}
 	)
 	job.GetenvJson("authConfig", authConfig)
 	job.GetenvJson("metaHeaders", metaHeaders)
 
-	r, err := registry.NewRegistry(authConfig, srv.HTTPRequestFactory(metaHeaders), auth.IndexServerAddress())
+	r, err := registry.NewRegistry(authConfig, srv.HTTPRequestFactory(metaHeaders), registry.IndexServerAddress())
 	if err != nil {
 		return job.Error(err)
 	}
@@ -827,7 +826,7 @@ func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
 	v.Set("ExecutionDriver", srv.runtime.ExecutionDriver().Name())
 	v.SetInt("NEventsListener", len(srv.listeners))
 	v.Set("KernelVersion", kernelVersion)
-	v.Set("IndexServerAddress", auth.IndexServerAddress())
+	v.Set("IndexServerAddress", registry.IndexServerAddress())
 	v.Set("InitSha1", dockerversion.INITSHA1)
 	v.Set("InitPath", initPath)
 	if _, err := v.WriteTo(job.Stdout); err != nil {
@@ -1312,7 +1311,7 @@ func (srv *Server) ImagePull(job *engine.Job) engine.Status {
 		localName   = job.Args[0]
 		tag         string
 		sf          = utils.NewStreamFormatter(job.GetenvBool("json"))
-		authConfig  = &auth.AuthConfig{}
+		authConfig  = &registry.AuthConfig{}
 		metaHeaders map[string][]string
 	)
 	if len(job.Args) > 1 {
@@ -1350,7 +1349,7 @@ func (srv *Server) ImagePull(job *engine.Job) engine.Status {
 		return job.Error(err)
 	}
 
-	if endpoint == auth.IndexServerAddress() {
+	if endpoint == registry.IndexServerAddress() {
 		// If pull "index.docker.io/foo/bar", it's stored locally under "foo/bar"
 		localName = remoteName
 	}
@@ -1531,7 +1530,7 @@ func (srv *Server) ImagePush(job *engine.Job) engine.Status {
 	var (
 		localName   = job.Args[0]
 		sf          = utils.NewStreamFormatter(job.GetenvBool("json"))
-		authConfig  = &auth.AuthConfig{}
+		authConfig  = &registry.AuthConfig{}
 		metaHeaders map[string][]string
 	)