...

Source file src/github.com/google/go-containerregistry/pkg/v1/remote/transport/basic.go

Documentation: github.com/google/go-containerregistry/pkg/v1/remote/transport

     1  // Copyright 2018 Google LLC All Rights Reserved.
     2  //
     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  package transport
    16  
    17  import (
    18  	"encoding/base64"
    19  	"fmt"
    20  	"net/http"
    21  
    22  	"github.com/google/go-containerregistry/pkg/authn"
    23  )
    24  
    25  type basicTransport struct {
    26  	inner  http.RoundTripper
    27  	auth   authn.Authenticator
    28  	target string
    29  }
    30  
    31  var _ http.RoundTripper = (*basicTransport)(nil)
    32  
    33  // RoundTrip implements http.RoundTripper
    34  func (bt *basicTransport) RoundTrip(in *http.Request) (*http.Response, error) {
    35  	if bt.auth != authn.Anonymous {
    36  		auth, err := bt.auth.Authorization()
    37  		if err != nil {
    38  			return nil, err
    39  		}
    40  
    41  		// http.Client handles redirects at a layer above the http.RoundTripper
    42  		// abstraction, so to avoid forwarding Authorization headers to places
    43  		// we are redirected, only set it when the authorization header matches
    44  		// the host with which we are interacting.
    45  		// In case of redirect http.Client can use an empty Host, check URL too.
    46  		if in.Host == bt.target || in.URL.Host == bt.target {
    47  			if bearer := auth.RegistryToken; bearer != "" {
    48  				hdr := fmt.Sprintf("Bearer %s", bearer)
    49  				in.Header.Set("Authorization", hdr)
    50  			} else if user, pass := auth.Username, auth.Password; user != "" && pass != "" {
    51  				delimited := fmt.Sprintf("%s:%s", user, pass)
    52  				encoded := base64.StdEncoding.EncodeToString([]byte(delimited))
    53  				hdr := fmt.Sprintf("Basic %s", encoded)
    54  				in.Header.Set("Authorization", hdr)
    55  			} else if token := auth.Auth; token != "" {
    56  				hdr := fmt.Sprintf("Basic %s", token)
    57  				in.Header.Set("Authorization", hdr)
    58  			}
    59  		}
    60  	}
    61  	return bt.inner.RoundTrip(in)
    62  }
    63  

View as plain text