github.com/Jeffail/benthos/v3@v3.65.0/public/service/config_tls.go (about) 1 package service 2 3 import ( 4 "crypto/tls" 5 "fmt" 6 "strings" 7 8 "github.com/Jeffail/benthos/v3/internal/docs" 9 btls "github.com/Jeffail/benthos/v3/lib/util/tls" 10 "gopkg.in/yaml.v3" 11 ) 12 13 // NewTLSField defines a new object type config field that describes TLS 14 // settings for networked components. It is then possible to extract a 15 // *tls.Config from the resulting parsed config with the method FieldTLS. 16 func NewTLSField(name string) *ConfigField { 17 tf := btls.FieldSpec() 18 tf.Name = name 19 var newChildren []docs.FieldSpec 20 for _, f := range tf.Children { 21 if f.Name != "enabled" { 22 newChildren = append(newChildren, f) 23 } 24 } 25 tf.Children = newChildren 26 return &ConfigField{field: tf} 27 } 28 29 // FieldTLS accesses a field from a parsed config that was defined with 30 // NewTLSField and returns a *tls.Config, or an error if the configuration was 31 // invalid. 32 func (p *ParsedConfig) FieldTLS(path ...string) (*tls.Config, error) { 33 v, exists := p.field(path...) 34 if !exists { 35 return nil, fmt.Errorf("field '%v' was not found in the config", strings.Join(path, ".")) 36 } 37 38 var node yaml.Node 39 if err := node.Encode(v); err != nil { 40 return nil, err 41 } 42 43 conf := btls.NewConfig() 44 if err := node.Decode(&conf); err != nil { 45 return nil, err 46 } 47 48 return conf.Get() 49 } 50 51 // NewTLSToggledField defines a new object type config field that describes TLS 52 // settings for networked components. This field differs from a standard 53 // TLSField as it includes a boolean field `enabled` which allows users to 54 // explicitly configure whether TLS should be enabled or not. 55 // 56 // A *tls.Config as well as an enabled boolean value can be extracted from the 57 // resulting parsed config with the method FieldTLSToggled. 58 func NewTLSToggledField(name string) *ConfigField { 59 tf := btls.FieldSpec() 60 tf.Name = name 61 return &ConfigField{field: tf} 62 } 63 64 // FieldTLSToggled accesses a field from a parsed config that was defined with 65 // NewTLSFieldToggled and returns a *tls.Config and a boolean flag indicating 66 // whether tls is explicitly enabled, or an error if the configuration was 67 // invalid. 68 func (p *ParsedConfig) FieldTLSToggled(path ...string) (tconf *tls.Config, enabled bool, err error) { 69 v, exists := p.field(path...) 70 if !exists { 71 return nil, false, fmt.Errorf("field '%v' was not found in the config", strings.Join(path, ".")) 72 } 73 74 var node yaml.Node 75 if err = node.Encode(v); err != nil { 76 return 77 } 78 79 conf := btls.NewConfig() 80 if err = node.Decode(&conf); err != nil { 81 return 82 } 83 84 if enabled = conf.Enabled; !enabled { 85 return 86 } 87 88 tconf, err = conf.Get() 89 return 90 }