Debian Codegraph @

registry/remote/auth/client.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 // Package auth provides authentication for a client to a remote registry.
17 package auth
18
19 import (
20 "context"
21 "encoding/base64"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "net"
27 "net/http"
28 "net/url"
29 "strings"
30
31 "oras.land/oras-go/v2/registry/remote/internal/errutil"
32 "oras.land/oras-go/v2/registry/remote/retry"
33 )
34
35 // ErrBasicCredentialNotFound is returned when the credential is not found for
36 // basic auth.
37 var ErrBasicCredentialNotFound = errors.New("basic credential not found")
38
39 // DefaultClient is the default auth-decorated client.
40 var DefaultClient = &Client{
41 Client: retry.DefaultClient,
42 Header: http.Header{
43 "User-Agent": {"oras-go"},
44 },
45 Cache: DefaultCache,
46 }
47
48 // maxResponseBytes specifies the default limit on how many response bytes are
49 // allowed in the server's response from authorization service servers.
50 // A typical response message from authorization service servers is around 1 to
51 // 4 KiB. Since the size of a token must be smaller than the HTTP header size
52 // limit, which is usually 16 KiB. As specified by the distribution, the
53 // response may contain 2 identical tokens, that is, 16 x 2 = 32 KiB.
54 // Hence, 128 KiB should be sufficient.
55 // References: https://distribution.github.io/distribution/spec/auth/token/
56 var maxResponseBytes int64 = 128 * 1024 // 128 KiB
57
58 // defaultClientID specifies the default client ID used in OAuth2.
59 // See also ClientID.
60 var defaultClientID = "oras-go"
61
62 // CredentialFunc represents a function that resolves the credential for the
63 // given registry (i.e. host:port).
64 //
65 // [EmptyCredential] is a valid return value and should not be considered as
66 // an error.
67 type CredentialFunc func(ctx context.Context, hostport string) (Credential, error)
68
69 // StaticCredential specifies static credentials for the given host.
70 func StaticCredential(registry string, cred Credential) CredentialFunc {
71 if registry == "docker.io" {
72 // it is expected that traffic targeting "docker.io" will be redirected
73 // to "registry-1.docker.io"
74 // reference: https://github.com/moby/moby/blob/v24.0.0-beta.2/registry/config.go#L25-L48
75 registry = "registry-1.docker.io"
76 }
77 return func(_ context.Context, hostport string) (Credential, error) {
78 if hostport == registry {
79 return cred, nil
80 }
81 return EmptyCredential, nil
82 }
83 }
84
85 // Client is an auth-decorated HTTP client.
86 // Its zero value is a usable client that uses http.DefaultClient with no cache.
87 type Client struct {
88 // Client is the underlying HTTP client used to access the remote
89 // server.
90 // If nil, http.DefaultClient is used.
91 // It is possible to use the default retry client from the package
92 // `oras.land/oras-go/v2/registry/remote/retry`. That client is already available
93 // in the DefaultClient.
94 // It is also possible to use a custom client. For example, github.com/hashicorp/go-retryablehttp
95 // is a popular HTTP client that supports retries.
96 Client *http.Client
97
98 // Header contains the custom headers to be added to each request.
99 Header http.Header
100
101 // Credential specifies the function for resolving the credential for the
102 // given registry (i.e. host:port).
103 // EmptyCredential is a valid return value and should not be considered as
104 // an error.
105 // If nil, the credential is always resolved to EmptyCredential.
106 Credential CredentialFunc
107
108 // Cache caches credentials for direct accessing the remote registry.
109 // If nil, no cache is used.
110 Cache Cache
111
112 // ClientID used in fetching OAuth2 token as a required field.
113 // If empty, a default client ID is used.
114 // Reference: https://distribution.github.io/distribution/spec/auth/oauth/#getting-a-token
115 ClientID string
116
117 // ForceAttemptOAuth2 controls whether to follow OAuth2 with password grant
118 // instead the distribution spec when authenticating using username and
119 // password.
120 // References:
121 // - https://distribution.github.io/distribution/spec/auth/jwt/
122 // - https://distribution.github.io/distribution/spec/auth/oauth/
123 ForceAttemptOAuth2 bool
124 }
125
126 // client returns an HTTP client used to access the remote registry.
127 // http.DefaultClient is return if the client is not configured.
128 func (c *Client) client() *http.Client {
129 if c.Client == nil {
130 return http.DefaultClient
131 }
132 return c.Client
133 }
134
135 // send adds headers to the request and sends the request to the remote server.
136 func (c *Client) send(req *http.Request) (*http.Response, error) {
137 for key, values := range c.Header {
138 req.Header[key] = append(req.Header[key], values...)
139 }
140 // Drop the Authorization header when a redirect crosses an HTTP origin
141 // (scheme, host, or port). The standard library only strips sensitive
142 // headers when the hostname changes, so a redirect to a different port on
143 // the same host would otherwise forward credentials to an unintended
144 // endpoint. Any caller-provided CheckRedirect is preserved.
145 // Reference: https://github.com/oras-project/oras-go/security/advisories/GHSA-vh4v-2xq2-g5cg
146 client := c.client()
147 clientCopy := *client
148 checkRedirect := client.CheckRedirect
149 clientCopy.CheckRedirect = func(req *http.Request, via []*http.Request) error {
150 if len(via) > 0 && !sameHTTPOrigin(via[len(via)-1].URL, req.URL) {
151 req.Header.Del("Authorization")
152 }
153 if checkRedirect != nil {
154 return checkRedirect(req, via)
155 }
156 return nil
157 }
158 return clientCopy.Do(req)
159 }
160
161 // sameHTTPOrigin reports whether a and b share the same HTTP origin, i.e. the
162 // same scheme and host. Default ports are normalized so that, for example,
163 // "example.com" and "example.com:443" compare equal over https.
164 func sameHTTPOrigin(a, b *url.URL) bool {
165 if !strings.EqualFold(a.Scheme, b.Scheme) {
166 return false
167 }
168 return canonicalHost(a) == canonicalHost(b)
169 }
170
171 // canonicalHost returns the lower-cased host of u with the default port for its
172 // scheme applied when no explicit port is present.
173 func canonicalHost(u *url.URL) string {
174 port := u.Port()
175 if port == "" {
176 switch strings.ToLower(u.Scheme) {
177 case "https":
178 port = "443"
179 case "http":
180 port = "80"
181 }
182 }
183 return strings.ToLower(u.Hostname()) + ":" + port
184 }
185
186 // credential resolves the credential for the given registry.
187 func (c *Client) credential(ctx context.Context, reg string) (Credential, error) {
188 if c.Credential == nil {
189 return EmptyCredential, nil
190 }
191 return c.Credential(ctx, reg)
192 }
193
194 // cache resolves the cache.
195 // noCache is return if the cache is not configured.
196 func (c *Client) cache() Cache {
197 if c.Cache == nil {
198 return noCache{}
199 }
200 return c.Cache
201 }
202
203 // validateRealm rejects bearer token realm URLs that would have the client
204 // forward credentials to obviously unsafe destinations:
205 //
206 // - schemes other than http or https,
207 // - http realms when the registry was contacted over https (TLS downgrade),
208 // - hosts that are IP literals in loopback, link-local, private, or
209 // unspecified ranges (e.g. cloud instance metadata services such as
210 // 169.254.169.254).
211 //
212 // Cross-host realms with a public hostname are permitted, because the
213 // distribution spec allows a separate token endpoint (e.g. Docker Hub's
214 // auth.docker.io). When the registry itself is reached at the same hostname
215 // as the realm, the IP-literal check is skipped so loopback and in-cluster
216 // deployments continue to work.
217 func validateRealm(realm string, registryURL *url.URL) error {
218 if realm == "" {
219 return nil
220 }
221 realmURL, err := url.Parse(realm)
222 if err != nil {
223 return fmt.Errorf("failed to parse bearer realm %q: %w", realm, err)
224 }
225 switch realmURL.Scheme {
226 case "https":
227 // always allowed
228 case "http":
229 if registryURL != nil && registryURL.Scheme == "https" {
230 return fmt.Errorf("bearer realm %q uses http but registry was contacted over https", realm)
231 }
232 default:
233 return fmt.Errorf("bearer realm %q uses unsupported scheme %q", realm, realmURL.Scheme)
234 }
235 if ip := net.ParseIP(realmURL.Hostname()); ip != nil {
236 if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||
237 ip.IsPrivate() || ip.IsUnspecified() {
238 if registryURL == nil || realmURL.Hostname() != registryURL.Hostname() {
239 return fmt.Errorf("bearer realm host %q is a loopback, link-local, private, or unspecified address", realmURL.Hostname())
240 }
241 }
242 }
243 return nil
244 }
245
246 // SetUserAgent sets the user agent for all out-going requests.
247 func (c *Client) SetUserAgent(userAgent string) {
248 if c.Header == nil {
249 c.Header = http.Header{}
250 }
251 c.Header.Set("User-Agent", userAgent)
252 }
253
254 // Do sends the request to the remote server, attempting to resolve
255 // authentication if 'Authorization' header is not set.
256 //
257 // On authentication failure due to bad credential,
258 // - Do returns error if it fails to fetch token for bearer auth.
259 // - Do returns the registry response without error for basic auth.
260 func (c *Client) Do(originalReq *http.Request) (*http.Response, error) {
261 if auth := originalReq.Header.Get("Authorization"); auth != "" {
262 return c.send(originalReq)
263 }
264
265 ctx := originalReq.Context()
266 req := originalReq.Clone(ctx)
267
268 // attempt cached auth token
269 var attemptedKey string
270 cache := c.cache()
271 host := originalReq.Host
272 if host == "" {
273 host = originalReq.URL.Host
274 }
275 scheme, err := cache.GetScheme(ctx, host)
276 if err == nil {
277 switch scheme {
278 case SchemeBasic:
279 token, err := cache.GetToken(ctx, host, SchemeBasic, "")
280 if err == nil {
281 req.Header.Set("Authorization", "Basic "+token)
282 }
283 case SchemeBearer:
284 scopes := GetAllScopesForHost(ctx, host)
285 attemptedKey = strings.Join(scopes, " ")
286 token, err := cache.GetToken(ctx, host, SchemeBearer, attemptedKey)
287 if err == nil {
288 req.Header.Set("Authorization", "Bearer "+token)
289 }
290 }
291 }
292
293 resp, err := c.send(req)
294 if err != nil {
295 return nil, err
296 }
297 if resp.StatusCode != http.StatusUnauthorized {
298 return resp, nil
299 }
300 // If the challenge came from a different origin than originally requested
301 // (e.g. the request was redirected to another host or port), do not resolve
302 // or send the registry credentials to that origin.
303 // Reference: https://github.com/oras-project/oras-go/security/advisories/GHSA-vh4v-2xq2-g5cg
304 if resp.Request != nil && !sameHTTPOrigin(originalReq.URL, resp.Request.URL) {
305 return resp, nil
306 }
307
308 // attempt again with credentials for recognized schemes
309 challenge := resp.Header.Get("Www-Authenticate")
310 scheme, params := parseChallenge(challenge)
311 switch scheme {
312 case SchemeBasic:
313 resp.Body.Close()
314
315 token, err := cache.Set(ctx, host, SchemeBasic, "", func(ctx context.Context) (string, error) {
316 return c.fetchBasicAuth(ctx, host)
317 })
318 if err != nil {
319 return nil, fmt.Errorf("%s %q: %w", resp.Request.Method, resp.Request.URL, err)
320 }
321
322 req = originalReq.Clone(ctx)
323 req.Header.Set("Authorization", "Basic "+token)
324 case SchemeBearer:
325 resp.Body.Close()
326
327 scopes := GetAllScopesForHost(ctx, host)
328 if paramScope := params["scope"]; paramScope != "" {
329 // merge hinted scopes with challenged scopes
330 scopes = append(scopes, strings.Split(paramScope, " ")...)
331 scopes = CleanScopes(scopes)
332 }
333 key := strings.Join(scopes, " ")
334
335 // attempt the cache again if there is a scope change
336 if key != attemptedKey {
337 if token, err := cache.GetToken(ctx, host, SchemeBearer, key); err == nil {
338 req = originalReq.Clone(ctx)
339 req.Header.Set("Authorization", "Bearer "+token)
340 if err := rewindRequestBody(req); err != nil {
341 return nil, err
342 }
343
344 resp, err := c.send(req)
345 if err != nil {
346 return nil, err
347 }
348 if resp.StatusCode != http.StatusUnauthorized {
349 return resp, nil
350 }
351 resp.Body.Close()
352 }
353 }
354
355 // attempt with credentials
356 realm := params["realm"]
357 if err := validateRealm(realm, originalReq.URL); err != nil {
358 return nil, fmt.Errorf("%s %q: %w", resp.Request.Method, resp.Request.URL, err)
359 }
360 service := params["service"]
361 token, err := cache.Set(ctx, host, SchemeBearer, key, func(ctx context.Context) (string, error) {
362 return c.fetchBearerToken(ctx, host, realm, service, scopes)
363 })
364 if err != nil {
365 return nil, fmt.Errorf("%s %q: %w", resp.Request.Method, resp.Request.URL, err)
366 }
367
368 req = originalReq.Clone(ctx)
369 req.Header.Set("Authorization", "Bearer "+token)
370 default:
371 return resp, nil
372 }
373 if err := rewindRequestBody(req); err != nil {
374 return nil, err
375 }
376
377 return c.send(req)
378 }
379
380 // fetchBasicAuth fetches a basic auth token for the basic challenge.
381 func (c *Client) fetchBasicAuth(ctx context.Context, registry string) (string, error) {
382 cred, err := c.credential(ctx, registry)
383 if err != nil {
384 return "", fmt.Errorf("failed to resolve credential: %w", err)
385 }
386 if cred == EmptyCredential {
387 return "", ErrBasicCredentialNotFound
388 }
389 if cred.Username == "" || cred.Password == "" {
390 return "", errors.New("missing username or password for basic auth")
391 }
392 auth := cred.Username + ":" + cred.Password
393 return base64.StdEncoding.EncodeToString([]byte(auth)), nil
394 }
395
396 // fetchBearerToken fetches an access token for the bearer challenge.
397 func (c *Client) fetchBearerToken(ctx context.Context, registry, realm, service string, scopes []string) (string, error) {
398 cred, err := c.credential(ctx, registry)
399 if err != nil {
400 return "", err
401 }
402 if cred.AccessToken != "" {
403 return cred.AccessToken, nil
404 }
405 if cred == EmptyCredential || (cred.RefreshToken == "" && !c.ForceAttemptOAuth2) {
406 return c.fetchDistributionToken(ctx, realm, service, scopes, cred.Username, cred.Password)
407 }
408 return c.fetchOAuth2Token(ctx, realm, service, scopes, cred)
409 }
410
411 // fetchDistributionToken fetches an access token as defined by the distribution
412 // specification.
413 // It fetches anonymous tokens if no credential is provided.
414 // References:
415 // - https://distribution.github.io/distribution/spec/auth/jwt/
416 // - https://distribution.github.io/distribution/spec/auth/token/
417 func (c *Client) fetchDistributionToken(ctx context.Context, realm, service string, scopes []string, username, password string) (string, error) {
418 req, err := http.NewRequestWithContext(ctx, http.MethodGet, realm, nil)
419 if err != nil {
420 return "", err
421 }
422 if username != "" || password != "" {
423 req.SetBasicAuth(username, password)
424 }
425 q := req.URL.Query()
426 if service != "" {
427 q.Set("service", service)
428 }
429 for _, scope := range scopes {
430 q.Add("scope", scope)
431 }
432 req.URL.RawQuery = q.Encode()
433
434 resp, err := c.send(req)
435 if err != nil {
436 return "", err
437 }
438 defer resp.Body.Close()
439 if resp.StatusCode != http.StatusOK {
440 return "", errutil.ParseErrorResponse(resp)
441 }
442
443 // As specified in https://distribution.github.io/distribution/spec/auth/token/ section
444 // "Token Response Fields", the token is either in `token` or
445 // `access_token`. If both present, they are identical.
446 var result struct {
447 Token string `json:"token"`
448 AccessToken string `json:"access_token"`
449 }
450 lr := io.LimitReader(resp.Body, maxResponseBytes)
451 if err := json.NewDecoder(lr).Decode(&result); err != nil {
452 return "", fmt.Errorf("%s %q: failed to decode response: %w", resp.Request.Method, resp.Request.URL, err)
453 }
454 if result.AccessToken != "" {
455 return result.AccessToken, nil
456 }
457 if result.Token != "" {
458 return result.Token, nil
459 }
460 return "", fmt.Errorf("%s %q: empty token returned", resp.Request.Method, resp.Request.URL)
461 }
462
463 // fetchOAuth2Token fetches an OAuth2 access token.
464 // Reference: https://distribution.github.io/distribution/spec/auth/oauth/
465 func (c *Client) fetchOAuth2Token(ctx context.Context, realm, service string, scopes []string, cred Credential) (string, error) {
466 form := url.Values{}
467 if cred.RefreshToken != "" {
468 form.Set("grant_type", "refresh_token")
469 form.Set("refresh_token", cred.RefreshToken)
470 } else if cred.Username != "" && cred.Password != "" {
471 form.Set("grant_type", "password")
472 form.Set("username", cred.Username)
473 form.Set("password", cred.Password)
474 } else {
475 return "", errors.New("missing username or password for bearer auth")
476 }
477 form.Set("service", service)
478 clientID := c.ClientID
479 if clientID == "" {
480 clientID = defaultClientID
481 }
482 form.Set("client_id", clientID)
483 if len(scopes) != 0 {
484 form.Set("scope", strings.Join(scopes, " "))
485 }
486 body := strings.NewReader(form.Encode())
487
488 req, err := http.NewRequestWithContext(ctx, http.MethodPost, realm, body)
489 if err != nil {
490 return "", err
491 }
492 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
493
494 resp, err := c.send(req)
495 if err != nil {
496 return "", err
497 }
498 defer resp.Body.Close()
499 if resp.StatusCode != http.StatusOK {
500 return "", errutil.ParseErrorResponse(resp)
501 }
502
503 var result struct {
504 AccessToken string `json:"access_token"`
505 }
506 lr := io.LimitReader(resp.Body, maxResponseBytes)
507 if err := json.NewDecoder(lr).Decode(&result); err != nil {
508 return "", fmt.Errorf("%s %q: failed to decode response: %w", resp.Request.Method, resp.Request.URL, err)
509 }
510 if result.AccessToken != "" {
511 return result.AccessToken, nil
512 }
513 return "", fmt.Errorf("%s %q: empty token returned", resp.Request.Method, resp.Request.URL)
514 }
515
516 // rewindRequestBody tries to rewind the request body if exists.
517 func rewindRequestBody(req *http.Request) error {
518 if req.Body == nil || req.Body == http.NoBody {
519 return nil
520 }
521 if req.GetBody == nil {
522 return fmt.Errorf("%s %q: request body is not rewindable", req.Method, req.URL)
523 }
524 body, err := req.GetBody()
525 if err != nil {
526 return fmt.Errorf("%s %q: failed to get request body: %w", req.Method, req.URL, err)
527 }
528 req.Body = body
529 return nil
530 }