podman
395 строк · 10.8 Кб
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"context"
10"encoding/base64"
11"encoding/json"
12"errors"
13"io"
14"net/http"
15"os"
16"os/exec"
17"path"
18"strings"
19)
20
21// ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed.
22var ErrCannotParseDockercfg = errors.New("failed to read authentication from dockercfg")
23
24// AuthConfiguration represents authentication options to use in the PushImage
25// method. It represents the authentication in the Docker index server.
26type AuthConfiguration struct {
27Username string `json:"username,omitempty"`
28Password string `json:"password,omitempty"`
29Email string `json:"email,omitempty"`
30ServerAddress string `json:"serveraddress,omitempty"`
31
32// IdentityToken can be supplied with the identitytoken response of the AuthCheck call
33// see https://pkg.go.dev/github.com/docker/docker/api/types?tab=doc#AuthConfig
34// It can be used in place of password not in conjunction with it
35IdentityToken string `json:"identitytoken,omitempty"`
36
37// RegistryToken can be supplied with the registrytoken
38RegistryToken string `json:"registrytoken,omitempty"`
39}
40
41func (c AuthConfiguration) isEmpty() bool {
42return c == AuthConfiguration{}
43}
44
45func (c AuthConfiguration) headerKey() string {
46return "X-Registry-Auth"
47}
48
49// AuthConfigurations represents authentication options to use for the
50// PushImage method accommodating the new X-Registry-Config header
51type AuthConfigurations struct {
52Configs map[string]AuthConfiguration `json:"configs"`
53}
54
55func (c AuthConfigurations) isEmpty() bool {
56return len(c.Configs) == 0
57}
58
59func (AuthConfigurations) headerKey() string {
60return "X-Registry-Config"
61}
62
63// merge updates the configuration. If a key is defined in both maps, the one
64// in c.Configs takes precedence.
65func (c *AuthConfigurations) merge(other AuthConfigurations) {
66for k, v := range other.Configs {
67if c.Configs == nil {
68c.Configs = make(map[string]AuthConfiguration)
69}
70if _, ok := c.Configs[k]; !ok {
71c.Configs[k] = v
72}
73}
74}
75
76// AuthConfigurations119 is used to serialize a set of AuthConfigurations
77// for Docker API >= 1.19.
78type AuthConfigurations119 map[string]AuthConfiguration
79
80func (c AuthConfigurations119) isEmpty() bool {
81return len(c) == 0
82}
83
84func (c AuthConfigurations119) headerKey() string {
85return "X-Registry-Config"
86}
87
88// dockerConfig represents a registry authentation configuration from the
89// .dockercfg file.
90type dockerConfig struct {
91Auth string `json:"auth"`
92Email string `json:"email"`
93IdentityToken string `json:"identitytoken"`
94RegistryToken string `json:"registrytoken"`
95}
96
97// NewAuthConfigurationsFromFile returns AuthConfigurations from a path containing JSON
98// in the same format as the .dockercfg file.
99func NewAuthConfigurationsFromFile(path string) (*AuthConfigurations, error) {
100r, err := os.Open(path)
101if err != nil {
102return nil, err
103}
104return NewAuthConfigurations(r)
105}
106
107func cfgPaths(dockerConfigEnv string, homeEnv string) []string {
108if dockerConfigEnv != "" {
109return []string{
110path.Join(dockerConfigEnv, "plaintext-passwords.json"),
111path.Join(dockerConfigEnv, "config.json"),
112}
113}
114if homeEnv != "" {
115return []string{
116path.Join(homeEnv, ".docker", "plaintext-passwords.json"),
117path.Join(homeEnv, ".docker", "config.json"),
118path.Join(homeEnv, ".dockercfg"),
119}
120}
121return nil
122}
123
124// NewAuthConfigurationsFromDockerCfg returns AuthConfigurations from system
125// config files. The following files are checked in the order listed:
126//
127// If the environment variable DOCKER_CONFIG is set to a non-empty string:
128//
129// - $DOCKER_CONFIG/plaintext-passwords.json
130// - $DOCKER_CONFIG/config.json
131//
132// Otherwise, it looks for files in the $HOME directory and the legacy
133// location:
134//
135// - $HOME/.docker/plaintext-passwords.json
136// - $HOME/.docker/config.json
137// - $HOME/.dockercfg
138func NewAuthConfigurationsFromDockerCfg() (*AuthConfigurations, error) {
139pathsToTry := cfgPaths(os.Getenv("DOCKER_CONFIG"), os.Getenv("HOME"))
140if len(pathsToTry) < 1 {
141return nil, errors.New("no docker configuration found")
142}
143return newAuthConfigurationsFromDockerCfg(pathsToTry)
144}
145
146func newAuthConfigurationsFromDockerCfg(pathsToTry []string) (*AuthConfigurations, error) {
147var result *AuthConfigurations
148var auths *AuthConfigurations
149var err error
150for _, path := range pathsToTry {
151auths, err = NewAuthConfigurationsFromFile(path)
152if err != nil {
153continue
154}
155
156if result == nil {
157result = auths
158} else {
159result.merge(*auths)
160}
161}
162
163if result != nil {
164return result, nil
165}
166return result, err
167}
168
169// NewAuthConfigurations returns AuthConfigurations from a JSON encoded string in the
170// same format as the .dockercfg file.
171func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) {
172var auth *AuthConfigurations
173confs, err := parseDockerConfig(r)
174if err != nil {
175return nil, err
176}
177auth, err = authConfigs(confs)
178if err != nil {
179return nil, err
180}
181return auth, nil
182}
183
184func parseDockerConfig(r io.Reader) (map[string]dockerConfig, error) {
185buf := new(bytes.Buffer)
186buf.ReadFrom(r)
187byteData := buf.Bytes()
188
189confsWrapper := struct {
190Auths map[string]dockerConfig `json:"auths"`
191}{}
192if err := json.Unmarshal(byteData, &confsWrapper); err == nil {
193if len(confsWrapper.Auths) > 0 {
194return confsWrapper.Auths, nil
195}
196}
197
198var confs map[string]dockerConfig
199if err := json.Unmarshal(byteData, &confs); err != nil {
200return nil, err
201}
202return confs, nil
203}
204
205// authConfigs converts a dockerConfigs map to a AuthConfigurations object.
206func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) {
207c := &AuthConfigurations{
208Configs: make(map[string]AuthConfiguration),
209}
210
211for reg, conf := range confs {
212if conf.Auth == "" {
213continue
214}
215
216// support both padded and unpadded encoding
217data, err := base64.StdEncoding.DecodeString(conf.Auth)
218if err != nil {
219data, err = base64.StdEncoding.WithPadding(base64.NoPadding).DecodeString(conf.Auth)
220}
221if err != nil {
222return nil, errors.New("error decoding plaintext credentials")
223}
224
225userpass := strings.SplitN(string(data), ":", 2)
226if len(userpass) != 2 {
227return nil, ErrCannotParseDockercfg
228}
229
230authConfig := AuthConfiguration{
231Email: conf.Email,
232Username: userpass[0],
233Password: userpass[1],
234ServerAddress: reg,
235}
236
237// if identitytoken provided then zero the password and set it
238if conf.IdentityToken != "" {
239authConfig.Password = ""
240authConfig.IdentityToken = conf.IdentityToken
241}
242
243// if registrytoken provided then zero the password and set it
244if conf.RegistryToken != "" {
245authConfig.Password = ""
246authConfig.RegistryToken = conf.RegistryToken
247}
248c.Configs[reg] = authConfig
249}
250
251return c, nil
252}
253
254// AuthStatus returns the authentication status for Docker API versions >= 1.23.
255type AuthStatus struct {
256Status string `json:"Status,omitempty" yaml:"Status,omitempty" toml:"Status,omitempty"`
257IdentityToken string `json:"IdentityToken,omitempty" yaml:"IdentityToken,omitempty" toml:"IdentityToken,omitempty"`
258}
259
260// AuthCheck validates the given credentials. It returns nil if successful.
261//
262// For Docker API versions >= 1.23, the AuthStatus struct will be populated, otherwise it will be empty.`
263//
264// See https://goo.gl/6nsZkH for more details.
265func (c *Client) AuthCheck(conf *AuthConfiguration) (AuthStatus, error) {
266return c.AuthCheckWithContext(conf, context.TODO())
267}
268
269// AuthCheckWithContext validates the given credentials. It returns nil if successful. The context object
270// can be used to cancel the request.
271//
272// For Docker API versions >= 1.23, the AuthStatus struct will be populated, otherwise it will be empty.
273//
274// See https://goo.gl/6nsZkH for more details.
275func (c *Client) AuthCheckWithContext(conf *AuthConfiguration, ctx context.Context) (AuthStatus, error) {
276var authStatus AuthStatus
277if conf == nil {
278return authStatus, errors.New("conf is nil")
279}
280resp, err := c.do(http.MethodPost, "/auth", doOptions{data: conf, context: ctx})
281if err != nil {
282return authStatus, err
283}
284defer resp.Body.Close()
285data, err := io.ReadAll(resp.Body)
286if err != nil {
287return authStatus, err
288}
289if len(data) == 0 {
290return authStatus, nil
291}
292if err := json.Unmarshal(data, &authStatus); err != nil {
293return authStatus, err
294}
295return authStatus, nil
296}
297
298// helperCredentials represents credentials commit from an helper
299type helperCredentials struct {
300Username string `json:"Username,omitempty"`
301Secret string `json:"Secret,omitempty"`
302}
303
304// NewAuthConfigurationsFromCredsHelpers returns AuthConfigurations from
305// installed credentials helpers
306func NewAuthConfigurationsFromCredsHelpers(registry string) (*AuthConfiguration, error) {
307// Load docker configuration file in order to find a possible helper provider
308pathsToTry := cfgPaths(os.Getenv("DOCKER_CONFIG"), os.Getenv("HOME"))
309if len(pathsToTry) < 1 {
310return nil, errors.New("no docker configuration found")
311}
312
313provider, err := getHelperProviderFromDockerCfg(pathsToTry, registry)
314if err != nil {
315return nil, err
316}
317
318c, err := getCredentialsFromHelper(provider, registry)
319if err != nil {
320return nil, err
321}
322
323creds := new(AuthConfiguration)
324creds.Username = c.Username
325creds.Password = c.Secret
326return creds, nil
327}
328
329func getHelperProviderFromDockerCfg(pathsToTry []string, registry string) (string, error) {
330for _, path := range pathsToTry {
331content, err := os.ReadFile(path)
332if err != nil {
333// if we can't read the file keep going
334continue
335}
336
337provider, err := parseCredsDockerConfig(content, registry)
338if err != nil {
339continue
340}
341if provider != "" {
342return provider, nil
343}
344}
345return "", errors.New("no docker credentials provider found")
346}
347
348func parseCredsDockerConfig(config []byte, registry string) (string, error) {
349creds := struct {
350CredsStore string `json:"credsStore,omitempty"`
351CredHelpers map[string]string `json:"credHelpers,omitempty"`
352}{}
353err := json.Unmarshal(config, &creds)
354if err != nil {
355return "", err
356}
357
358provider, ok := creds.CredHelpers[registry]
359if ok {
360return provider, nil
361}
362return creds.CredsStore, nil
363}
364
365// Run and parse the found credential helper
366func getCredentialsFromHelper(provider string, registry string) (*helperCredentials, error) {
367helpercreds, err := runDockerCredentialsHelper(provider, registry)
368if err != nil {
369return nil, err
370}
371
372c := new(helperCredentials)
373err = json.Unmarshal(helpercreds, c)
374if err != nil {
375return nil, err
376}
377
378return c, nil
379}
380
381func runDockerCredentialsHelper(provider string, registry string) ([]byte, error) {
382cmd := exec.Command("docker-credential-"+provider, "get")
383
384var stdout bytes.Buffer
385
386cmd.Stdin = bytes.NewBuffer([]byte(registry))
387cmd.Stdout = &stdout
388
389err := cmd.Run()
390if err != nil {
391return nil, err
392}
393
394return stdout.Bytes(), nil
395}
396