github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/tls/tls.go (about) 1 package tls 2 3 import ( 4 "crypto/tls" 5 "crypto/x509" 6 "os" 7 8 "github.com/pkg/errors" 9 ) 10 11 var gDefaultTlsConfig = &tls.Config{ 12 ClientAuth: tls.NoClientCert, 13 ClientCAs: nil, 14 InsecureSkipVerify: true, 15 } 16 17 type X509KeyPair struct { 18 KeyPath string `json:""` 19 CrtPath string `json:""` 20 CaPath string `json:""` 21 Key string `json:"key"` 22 Crt string `json:"crt"` 23 Ca string `json:"ca"` 24 conf *tls.Config 25 } 26 27 func (c *X509KeyPair) IsZero() bool { 28 return c.Key == "" || c.Crt == "" || c.Ca == "" && 29 c.KeyPath == "" || c.CrtPath == "" || c.CaPath == "" 30 } 31 32 func (c *X509KeyPair) read() (key, crt, ca []byte, err error, empty bool) { 33 if c.Key+c.Ca+c.Crt != "" { 34 return []byte(c.Key), []byte(c.Crt), []byte(c.Ca), nil, false 35 } 36 if len(c.KeyPath+c.CrtPath+c.CaPath) == 0 { 37 empty = true 38 return 39 } 40 empty = false 41 var content []byte 42 content, err = os.ReadFile(c.KeyPath) 43 if err != nil { 44 return 45 } 46 key = content 47 content, err = os.ReadFile(c.CrtPath) 48 if err != nil { 49 return 50 } 51 crt = content 52 content, err = os.ReadFile(c.CaPath) 53 if err != nil { 54 return 55 } 56 ca = content 57 return 58 } 59 60 func (c *X509KeyPair) Init() error { 61 if c == nil { 62 return nil 63 } 64 65 key, crt, ca, err, empty := c.read() 66 if err != nil { 67 return err 68 } 69 70 if empty { 71 return nil 72 } 73 74 cert, err := tls.X509KeyPair(crt, key) 75 if err != nil { 76 return err 77 } 78 pool := x509.NewCertPool() 79 ok := pool.AppendCertsFromPEM(ca) 80 if !ok { 81 return errors.Wrap(err, "failed to append cert") 82 } 83 c.conf = &tls.Config{ 84 RootCAs: pool, 85 Certificates: []tls.Certificate{cert}, 86 InsecureSkipVerify: true, 87 } 88 return nil 89 } 90 91 func (c *X509KeyPair) TLSConfig() *tls.Config { 92 if c == nil { 93 return gDefaultTlsConfig 94 } 95 return c.conf 96 }