summaryrefslogtreecommitdiff
path: root/pkg/auth/auth.go
blob: a4d7896a86c2d5d870e4b23ad2a712be6c7fe574 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package auth

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	imageAuth "github.com/containers/image/v5/pkg/docker/config"
	"github.com/containers/image/v5/types"
	dockerAPITypes "github.com/docker/docker/api/types"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

type HeaderAuthName string

func (h HeaderAuthName) String() string { return string(h) }

// XRegistryAuthHeader is the key to the encoded registry authentication configuration in an http-request header.
// This header supports one registry per header occurrence. To support N registries provide N headers, one per registry.
// As of Docker API 1.40 and Libpod API 1.0.0, this header is supported by all endpoints.
const XRegistryAuthHeader HeaderAuthName = "X-Registry-Auth"

// XRegistryConfigHeader is the key to the encoded registry authentication configuration in an http-request header.
// This header supports N registries in one header via a Base64 encoded, JSON map.
// As of Docker API 1.40 and Libpod API 2.0.0, this header is supported by build endpoints.
const XRegistryConfigHeader HeaderAuthName = "X-Registry-Config"

// GetCredentials queries the http.Request for X-Registry-.* headers and extracts
// the necessary authentication information for libpod operations
func GetCredentials(r *http.Request) (*types.DockerAuthConfig, string, error) {
	nonemptyHeaderValue := func(key HeaderAuthName) ([]string, bool) {
		hdr := r.Header.Values(key.String())
		return hdr, len(hdr) > 0
	}
	var override *types.DockerAuthConfig
	var authFile string
	var headerName HeaderAuthName
	var err error
	if hdr, ok := nonemptyHeaderValue(XRegistryConfigHeader); ok {
		headerName = XRegistryConfigHeader
		override, authFile, err = getConfigCredentials(r, hdr)
	} else if hdr, ok := nonemptyHeaderValue(XRegistryAuthHeader); ok {
		headerName = XRegistryAuthHeader
		override, authFile, err = getAuthCredentials(hdr)
	} else {
		return nil, "", nil
	}
	if err != nil {
		return nil, "", errors.Wrapf(err, "failed to parse %q header for %s", headerName, r.URL.String())
	}
	return override, authFile, nil
}

// getConfigCredentials extracts one or more docker.AuthConfig from a request and its
// XRegistryConfigHeader value.  An empty key will be used as default while a named registry will be
// returned as types.DockerAuthConfig
func getConfigCredentials(r *http.Request, headers []string) (*types.DockerAuthConfig, string, error) {
	var auth *types.DockerAuthConfig
	configs := make(map[string]types.DockerAuthConfig)

	for _, h := range headers {
		param, err := base64.URLEncoding.DecodeString(h)
		if err != nil {
			return nil, "", errors.Wrapf(err, "failed to decode %q", XRegistryConfigHeader)
		}

		ac := make(map[string]dockerAPITypes.AuthConfig)
		err = json.Unmarshal(param, &ac)
		if err != nil {
			return nil, "", errors.Wrapf(err, "failed to unmarshal %q", XRegistryConfigHeader)
		}

		for k, v := range ac {
			configs[k] = dockerAuthToImageAuth(v)
		}
	}

	// Empty key implies no registry given in API
	if c, found := configs[""]; found {
		auth = &c
	}

	// Override any default given above if specialized credentials provided
	if registries, found := r.URL.Query()["registry"]; found {
		for _, r := range registries {
			for k, v := range configs {
				if strings.Contains(k, r) {
					v := v
					auth = &v
					break
				}
			}
			if auth != nil {
				break
			}
		}

		if auth == nil {
			logrus.Debugf("%q header found in request, but \"registry=%v\" query parameter not provided",
				XRegistryConfigHeader, registries)
		} else {
			logrus.Debugf("%q header found in request for username %q", XRegistryConfigHeader, auth.Username)
		}
	}

	authfile, err := authConfigsToAuthFile(configs)
	return auth, authfile, err
}

// getAuthCredentials extracts one or more DockerAuthConfigs from an XRegistryAuthHeader
// value.  The header could specify a single-auth config in which case the
// first return value is set.  In case of a multi-auth header, the contents are
// stored in a temporary auth file (2nd return value).  Note that the auth file
// should be removed after usage.
func getAuthCredentials(headers []string) (*types.DockerAuthConfig, string, error) {
	authHeader := headers[0]

	// First look for a multi-auth header (i.e., a map).
	authConfigs, err := parseMultiAuthHeader(authHeader)
	if err == nil {
		authfile, err := authConfigsToAuthFile(authConfigs)
		return nil, authfile, err
	}

	// Fallback to looking for a single-auth header (i.e., one config).
	authConfig, err := parseSingleAuthHeader(authHeader)
	if err != nil {
		return nil, "", err
	}
	return &authConfig, "", nil
}

// Header builds the requested Authentication Header
func Header(sys *types.SystemContext, headerName HeaderAuthName, authfile, username, password string) (map[string]string, error) {
	var (
		content string
		err     error
	)
	switch headerName {
	case XRegistryAuthHeader:
		content, err = headerAuth(sys, authfile, username, password)
	case XRegistryConfigHeader:
		content, err = headerConfig(sys, authfile, username, password)
	default:
		err = fmt.Errorf("unsupported authentication header: %q", headerName)
	}
	if err != nil {
		return nil, err
	}

	if len(content) > 0 {
		return map[string]string{string(headerName): content}, nil
	}
	return nil, nil
}

// headerConfig returns a map with the XRegistryConfigHeader set which can
// conveniently be used in the http stack.
func headerConfig(sys *types.SystemContext, authfile, username, password string) (string, error) {
	if sys == nil {
		sys = &types.SystemContext{}
	}
	if authfile != "" {
		sys.AuthFilePath = authfile
	}
	authConfigs, err := imageAuth.GetAllCredentials(sys)
	if err != nil {
		return "", err
	}

	if username != "" {
		authConfigs[""] = types.DockerAuthConfig{
			Username: username,
			Password: password,
		}
	}

	if len(authConfigs) == 0 {
		return "", nil
	}
	return encodeMultiAuthConfigs(authConfigs)
}

// headerAuth returns a base64 encoded map with the XRegistryAuthHeader set which can
// conveniently be used in the http stack.
func headerAuth(sys *types.SystemContext, authfile, username, password string) (string, error) {
	if username != "" {
		return encodeSingleAuthConfig(types.DockerAuthConfig{Username: username, Password: password})
	}

	if sys == nil {
		sys = &types.SystemContext{}
	}
	if authfile != "" {
		sys.AuthFilePath = authfile
	}
	authConfigs, err := imageAuth.GetAllCredentials(sys)
	if err != nil {
		return "", err
	}
	return encodeMultiAuthConfigs(authConfigs)
}

// RemoveAuthfile is a convenience function that is meant to be called in a
// deferred statement. If non-empty, it removes the specified authfile and log
// errors.  It's meant to reduce boilerplate code at call sites of
// `GetCredentials`.
func RemoveAuthfile(authfile string) {
	if authfile == "" {
		return
	}
	if err := os.Remove(authfile); err != nil {
		logrus.Errorf("Removing temporary auth file %q: %v", authfile, err)
	}
}

// encodeSingleAuthConfig serializes the auth configuration as a base64 encoded JSON payload.
func encodeSingleAuthConfig(authConfig types.DockerAuthConfig) (string, error) {
	conf := imageAuthToDockerAuth(authConfig)
	buf, err := json.Marshal(conf)
	if err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(buf), nil
}

// encodeMultiAuthConfigs serializes the auth configurations as a base64 encoded JSON payload.
func encodeMultiAuthConfigs(authConfigs map[string]types.DockerAuthConfig) (string, error) {
	confs := make(map[string]dockerAPITypes.AuthConfig)
	for registry, authConf := range authConfigs {
		confs[registry] = imageAuthToDockerAuth(authConf)
	}
	buf, err := json.Marshal(confs)
	if err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(buf), nil
}

// authConfigsToAuthFile stores the specified auth configs in a temporary files
// and returns its path. The file can later be used an auth file for contacting
// one or more container registries.  If tmpDir is empty, the system's default
// TMPDIR will be used.
func authConfigsToAuthFile(authConfigs map[string]types.DockerAuthConfig) (string, error) {
	// Initialize an empty temporary JSON file.
	tmpFile, err := ioutil.TempFile("", "auth.json.")
	if err != nil {
		return "", err
	}
	if _, err := tmpFile.Write([]byte{'{', '}'}); err != nil {
		return "", errors.Wrap(err, "error initializing temporary auth file")
	}
	if err := tmpFile.Close(); err != nil {
		return "", errors.Wrap(err, "error closing temporary auth file")
	}
	authFilePath := tmpFile.Name()

	// TODO: It would be nice if c/image could dump the map at once.
	//
	// Now use the c/image packages to store the credentials. It's battle
	// tested, and we make sure to use the same code as the image backend.
	sys := types.SystemContext{AuthFilePath: authFilePath}
	for authFileKey, config := range authConfigs {
		key := normalizeAuthFileKey(authFileKey)

		// Note that we do not validate the credentials here. We assume
		// that all credentials are valid. They'll be used on demand
		// later.
		if err := imageAuth.SetAuthentication(&sys, key, config.Username, config.Password); err != nil {
			return "", errors.Wrapf(err, "error storing credentials in temporary auth file (key: %q / %q, user: %q)", authFileKey, key, config.Username)
		}
	}

	return authFilePath, nil
}

// normalizeAuthFileKey takes an auth file key and converts it into a new-style credential key
// in the canonical format, as interpreted by c/image/pkg/docker/config.
func normalizeAuthFileKey(authFileKey string) string {
	stripped := strings.TrimPrefix(authFileKey, "http://")
	stripped = strings.TrimPrefix(stripped, "https://")

	if stripped != authFileKey { // URLs are interpreted to mean complete registries
		stripped = strings.SplitN(stripped, "/", 2)[0]
	}

	// Only non-namespaced registry names (or URLs) need to be normalized; repo namespaces
	// always use the simple format.
	switch stripped {
	case "registry-1.docker.io", "index.docker.io":
		return "docker.io"
	default:
		return stripped
	}
}

// dockerAuthToImageAuth converts a docker auth config to one we're using
// internally from c/image.  Note that the Docker types look slightly
// different, so we need to convert to be extra sure we're not running into
// undesired side-effects when unmarhalling directly to our types.
func dockerAuthToImageAuth(authConfig dockerAPITypes.AuthConfig) types.DockerAuthConfig {
	return types.DockerAuthConfig{
		Username:      authConfig.Username,
		Password:      authConfig.Password,
		IdentityToken: authConfig.IdentityToken,
	}
}

// reverse conversion of `dockerAuthToImageAuth`.
func imageAuthToDockerAuth(authConfig types.DockerAuthConfig) dockerAPITypes.AuthConfig {
	return dockerAPITypes.AuthConfig{
		Username:      authConfig.Username,
		Password:      authConfig.Password,
		IdentityToken: authConfig.IdentityToken,
	}
}

// parseSingleAuthHeader extracts a DockerAuthConfig from an XRegistryAuthHeader value.
// The header content is a single DockerAuthConfig.
func parseSingleAuthHeader(authHeader string) (types.DockerAuthConfig, error) {
	// Accept "null" and handle it as empty value for compatibility reason with Docker.
	// Some java docker clients pass this value, e.g. this one used in Eclipse.
	if len(authHeader) == 0 || authHeader == "null" {
		return types.DockerAuthConfig{}, nil
	}

	authConfig := dockerAPITypes.AuthConfig{}
	authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authHeader))
	if err := json.NewDecoder(authJSON).Decode(&authConfig); err != nil {
		return types.DockerAuthConfig{}, err
	}
	return dockerAuthToImageAuth(authConfig), nil
}

// parseMultiAuthHeader extracts a DockerAuthConfig from an XRegistryAuthHeader value.
// The header content is a map[string]DockerAuthConfigs.
func parseMultiAuthHeader(authHeader string) (map[string]types.DockerAuthConfig, error) {
	// Accept "null" and handle it as empty value for compatibility reason with Docker.
	// Some java docker clients pass this value, e.g. this one used in Eclipse.
	if len(authHeader) == 0 || authHeader == "null" {
		return nil, nil
	}

	dockerAuthConfigs := make(map[string]dockerAPITypes.AuthConfig)
	authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authHeader))
	if err := json.NewDecoder(authJSON).Decode(&dockerAuthConfigs); err != nil {
		return nil, err
	}

	// Now convert to the internal types.
	authConfigs := make(map[string]types.DockerAuthConfig)
	for server := range dockerAuthConfigs {
		authConfigs[server] = dockerAuthToImageAuth(dockerAuthConfigs[server])
	}
	return authConfigs, nil
}