123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303 |
- package transport
- import (
- "context"
- "crypto/tls"
- "crypto/x509"
- "fmt"
- "io/ioutil"
- "net/http"
- "sync"
- "time"
- utilnet "k8s.io/apimachinery/pkg/util/net"
- "k8s.io/klog/v2"
- )
- func New(config *Config) (http.RoundTripper, error) {
-
- if config.Transport != nil && (config.HasCA() || config.HasCertAuth() || config.HasCertCallback() || config.TLS.Insecure) {
- return nil, fmt.Errorf("using a custom transport with TLS certificate options or the insecure flag is not allowed")
- }
- var (
- rt http.RoundTripper
- err error
- )
- if config.Transport != nil {
- rt = config.Transport
- } else {
- rt, err = tlsCache.get(config)
- if err != nil {
- return nil, err
- }
- }
- return HTTPWrappersForConfig(config, rt)
- }
- func TLSConfigFor(c *Config) (*tls.Config, error) {
- if !(c.HasCA() || c.HasCertAuth() || c.HasCertCallback() || c.TLS.Insecure || len(c.TLS.ServerName) > 0 || len(c.TLS.NextProtos) > 0) {
- return nil, nil
- }
- if c.HasCA() && c.TLS.Insecure {
- return nil, fmt.Errorf("specifying a root certificates file with the insecure flag is not allowed")
- }
- if err := loadTLSFiles(c); err != nil {
- return nil, err
- }
- tlsConfig := &tls.Config{
-
-
-
- MinVersion: tls.VersionTLS12,
- InsecureSkipVerify: c.TLS.Insecure,
- ServerName: c.TLS.ServerName,
- NextProtos: c.TLS.NextProtos,
- }
- if c.HasCA() {
- tlsConfig.RootCAs = rootCertPool(c.TLS.CAData)
- }
- var staticCert *tls.Certificate
-
- if c.HasCertAuth() && !c.TLS.ReloadTLSFiles {
-
-
- cert, err := tls.X509KeyPair(c.TLS.CertData, c.TLS.KeyData)
- if err != nil {
- return nil, err
- }
- staticCert = &cert
- }
- var dynamicCertLoader func() (*tls.Certificate, error)
- if c.TLS.ReloadTLSFiles {
- dynamicCertLoader = cachingCertificateLoader(c.TLS.CertFile, c.TLS.KeyFile)
- }
- if c.HasCertAuth() || c.HasCertCallback() {
- tlsConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
-
-
- if staticCert != nil {
- return staticCert, nil
- }
-
- if dynamicCertLoader != nil {
- return dynamicCertLoader()
- }
- if c.HasCertCallback() {
- cert, err := c.TLS.GetCert()
- if err != nil {
- return nil, err
- }
-
- if cert != nil {
- return cert, nil
- }
- }
-
-
-
- return &tls.Certificate{}, nil
- }
- }
- return tlsConfig, nil
- }
- func loadTLSFiles(c *Config) error {
- var err error
- c.TLS.CAData, err = dataFromSliceOrFile(c.TLS.CAData, c.TLS.CAFile)
- if err != nil {
- return err
- }
-
- if len(c.TLS.CertFile) > 0 && len(c.TLS.CertData) == 0 && len(c.TLS.KeyFile) > 0 && len(c.TLS.KeyData) == 0 {
- c.TLS.ReloadTLSFiles = true
- }
- c.TLS.CertData, err = dataFromSliceOrFile(c.TLS.CertData, c.TLS.CertFile)
- if err != nil {
- return err
- }
- c.TLS.KeyData, err = dataFromSliceOrFile(c.TLS.KeyData, c.TLS.KeyFile)
- if err != nil {
- return err
- }
- return nil
- }
- func dataFromSliceOrFile(data []byte, file string) ([]byte, error) {
- if len(data) > 0 {
- return data, nil
- }
- if len(file) > 0 {
- fileData, err := ioutil.ReadFile(file)
- if err != nil {
- return []byte{}, err
- }
- return fileData, nil
- }
- return nil, nil
- }
- func rootCertPool(caData []byte) *x509.CertPool {
-
-
-
- if len(caData) == 0 {
- return nil
- }
-
- certPool := x509.NewCertPool()
- certPool.AppendCertsFromPEM(caData)
- return certPool
- }
- type WrapperFunc func(rt http.RoundTripper) http.RoundTripper
- func Wrappers(fns ...WrapperFunc) WrapperFunc {
- if len(fns) == 0 {
- return nil
- }
-
-
- if len(fns) == 2 && fns[0] == nil {
- return fns[1]
- }
- return func(rt http.RoundTripper) http.RoundTripper {
- base := rt
- for _, fn := range fns {
- if fn != nil {
- base = fn(base)
- }
- }
- return base
- }
- }
- func ContextCanceller(ctx context.Context, err error) WrapperFunc {
- return func(rt http.RoundTripper) http.RoundTripper {
- return &contextCanceller{
- ctx: ctx,
- rt: rt,
- err: err,
- }
- }
- }
- type contextCanceller struct {
- ctx context.Context
- rt http.RoundTripper
- err error
- }
- func (b *contextCanceller) RoundTrip(req *http.Request) (*http.Response, error) {
- select {
- case <-b.ctx.Done():
- return nil, b.err
- default:
- return b.rt.RoundTrip(req)
- }
- }
- func tryCancelRequest(rt http.RoundTripper, req *http.Request) {
- type canceler interface {
- CancelRequest(*http.Request)
- }
- switch rt := rt.(type) {
- case canceler:
- rt.CancelRequest(req)
- case utilnet.RoundTripperWrapper:
- tryCancelRequest(rt.WrappedRoundTripper(), req)
- default:
- klog.Warningf("Unable to cancel request for %T", rt)
- }
- }
- type certificateCacheEntry struct {
- cert *tls.Certificate
- err error
- birth time.Time
- }
- func (c *certificateCacheEntry) isStale() bool {
- return time.Now().Sub(c.birth) > time.Second
- }
- func newCertificateCacheEntry(certFile, keyFile string) certificateCacheEntry {
- cert, err := tls.LoadX509KeyPair(certFile, keyFile)
- return certificateCacheEntry{cert: &cert, err: err, birth: time.Now()}
- }
- func cachingCertificateLoader(certFile, keyFile string) func() (*tls.Certificate, error) {
- current := newCertificateCacheEntry(certFile, keyFile)
- var currentMtx sync.RWMutex
- return func() (*tls.Certificate, error) {
- currentMtx.RLock()
- if current.isStale() {
- currentMtx.RUnlock()
- currentMtx.Lock()
- defer currentMtx.Unlock()
- if current.isStale() {
- current = newCertificateCacheEntry(certFile, keyFile)
- }
- } else {
- defer currentMtx.RUnlock()
- }
- return current.cert, current.err
- }
- }
|