1// Copyright 2015 go-dockerclient authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package docker
6
7import (
8	"bytes"
9	"encoding/base64"
10	"encoding/json"
11	"errors"
12	"fmt"
13	"io"
14	"os"
15	"path"
16	"strings"
17)
18
19// ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed.
20var ErrCannotParseDockercfg = errors.New("Failed to read authentication from dockercfg")
21
22// AuthConfiguration represents authentication options to use in the PushImage
23// method. It represents the authentication in the Docker index server.
24type AuthConfiguration struct {
25	Username      string `json:"username,omitempty"`
26	Password      string `json:"password,omitempty"`
27	Email         string `json:"email,omitempty"`
28	ServerAddress string `json:"serveraddress,omitempty"`
29}
30
31// AuthConfigurations represents authentication options to use for the
32// PushImage method accommodating the new X-Registry-Config header
33type AuthConfigurations struct {
34	Configs map[string]AuthConfiguration `json:"configs"`
35}
36
37// AuthConfigurations119 is used to serialize a set of AuthConfigurations
38// for Docker API >= 1.19.
39type AuthConfigurations119 map[string]AuthConfiguration
40
41// dockerConfig represents a registry authentation configuration from the
42// .dockercfg file.
43type dockerConfig struct {
44	Auth  string `json:"auth"`
45	Email string `json:"email"`
46}
47
48// NewAuthConfigurationsFromDockerCfg returns AuthConfigurations from the
49// ~/.dockercfg file.
50func NewAuthConfigurationsFromDockerCfg() (*AuthConfigurations, error) {
51	var r io.Reader
52	var err error
53	p := path.Join(os.Getenv("HOME"), ".docker", "config.json")
54	r, err = os.Open(p)
55	if err != nil {
56		p := path.Join(os.Getenv("HOME"), ".dockercfg")
57		r, err = os.Open(p)
58		if err != nil {
59			return nil, err
60		}
61	}
62	return NewAuthConfigurations(r)
63}
64
65// NewAuthConfigurations returns AuthConfigurations from a JSON encoded string in the
66// same format as the .dockercfg file.
67func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) {
68	var auth *AuthConfigurations
69	confs, err := parseDockerConfig(r)
70	if err != nil {
71		return nil, err
72	}
73	auth, err = authConfigs(confs)
74	if err != nil {
75		return nil, err
76	}
77	return auth, nil
78}
79
80func parseDockerConfig(r io.Reader) (map[string]dockerConfig, error) {
81	buf := new(bytes.Buffer)
82	buf.ReadFrom(r)
83	byteData := buf.Bytes()
84
85	var confsWrapper map[string]map[string]dockerConfig
86	if err := json.Unmarshal(byteData, &confsWrapper); err == nil {
87		if confs, ok := confsWrapper["auths"]; ok {
88			return confs, nil
89		}
90	}
91
92	var confs map[string]dockerConfig
93	if err := json.Unmarshal(byteData, &confs); err != nil {
94		return nil, err
95	}
96	return confs, nil
97}
98
99// authConfigs converts a dockerConfigs map to a AuthConfigurations object.
100func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) {
101	c := &AuthConfigurations{
102		Configs: make(map[string]AuthConfiguration),
103	}
104	for reg, conf := range confs {
105		data, err := base64.StdEncoding.DecodeString(conf.Auth)
106		if err != nil {
107			return nil, err
108		}
109		userpass := strings.Split(string(data), ":")
110		if len(userpass) != 2 {
111			return nil, ErrCannotParseDockercfg
112		}
113		c.Configs[reg] = AuthConfiguration{
114			Email:         conf.Email,
115			Username:      userpass[0],
116			Password:      userpass[1],
117			ServerAddress: reg,
118		}
119	}
120	return c, nil
121}
122
123// AuthCheck validates the given credentials. It returns nil if successful.
124//
125// See https://goo.gl/m2SleN for more details.
126func (c *Client) AuthCheck(conf *AuthConfiguration) error {
127	if conf == nil {
128		return fmt.Errorf("conf is nil")
129	}
130	resp, err := c.do("POST", "/auth", doOptions{data: conf})
131	if err != nil {
132		return err
133	}
134	resp.Body.Close()
135	return nil
136}
137