github.com/stefanmcshane/helm@v0.0.0-20221213002717-88a4a2c6e77d/internal/tlsutil/cfg.go (about) 1 /* 2 Copyright The Helm Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tlsutil 18 19 import ( 20 "crypto/tls" 21 "crypto/x509" 22 "os" 23 24 "github.com/pkg/errors" 25 ) 26 27 // Options represents configurable options used to create client and server TLS configurations. 28 type Options struct { 29 CaCertFile string 30 // If either the KeyFile or CertFile is empty, ClientConfig() will not load them. 31 KeyFile string 32 CertFile string 33 // Client-only options 34 InsecureSkipVerify bool 35 } 36 37 // ClientConfig returns a TLS configuration for use by a Helm client. 38 func ClientConfig(opts Options) (cfg *tls.Config, err error) { 39 var cert *tls.Certificate 40 var pool *x509.CertPool 41 42 if opts.CertFile != "" || opts.KeyFile != "" { 43 if cert, err = CertFromFilePair(opts.CertFile, opts.KeyFile); err != nil { 44 if os.IsNotExist(err) { 45 return nil, errors.Wrapf(err, "could not load x509 key pair (cert: %q, key: %q)", opts.CertFile, opts.KeyFile) 46 } 47 return nil, errors.Wrapf(err, "could not read x509 key pair (cert: %q, key: %q)", opts.CertFile, opts.KeyFile) 48 } 49 } 50 if !opts.InsecureSkipVerify && opts.CaCertFile != "" { 51 if pool, err = CertPoolFromFile(opts.CaCertFile); err != nil { 52 return nil, err 53 } 54 } 55 56 cfg = &tls.Config{InsecureSkipVerify: opts.InsecureSkipVerify, Certificates: []tls.Certificate{*cert}, RootCAs: pool} 57 return cfg, nil 58 }