httpclient.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package httpclient
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/hashicorp/go-retryablehttp"
  13. "github.com/drakkan/sftpgo/v2/logger"
  14. "github.com/drakkan/sftpgo/v2/util"
  15. )
  16. // TLSKeyPair defines the paths for a TLS key pair
  17. type TLSKeyPair struct {
  18. Cert string `json:"cert" mapstructure:"cert"`
  19. Key string `json:"key" mapstructure:"key"`
  20. }
  21. // Header defines an HTTP header.
  22. // If the URL is not empty, the header is added only if the
  23. // requested URL starts with the one specified
  24. type Header struct {
  25. Key string `json:"key" mapstructure:"key"`
  26. Value string `json:"value" mapstructure:"value"`
  27. URL string `json:"url" mapstructure:"url"`
  28. }
  29. // Config defines the configuration for HTTP clients.
  30. // HTTP clients are used for executing hooks such as the ones used for
  31. // custom actions, external authentication and pre-login user modifications
  32. type Config struct {
  33. // Timeout specifies a time limit, in seconds, for a request
  34. Timeout float64 `json:"timeout" mapstructure:"timeout"`
  35. // RetryWaitMin defines the minimum waiting time between attempts in seconds
  36. RetryWaitMin int `json:"retry_wait_min" mapstructure:"retry_wait_min"`
  37. // RetryWaitMax defines the minimum waiting time between attempts in seconds
  38. RetryWaitMax int `json:"retry_wait_max" mapstructure:"retry_wait_max"`
  39. // RetryMax defines the maximum number of attempts
  40. RetryMax int `json:"retry_max" mapstructure:"retry_max"`
  41. // CACertificates defines extra CA certificates to trust.
  42. // The paths can be absolute or relative to the config dir.
  43. // Adding trusted CA certificates is a convenient way to use self-signed
  44. // certificates without defeating the purpose of using TLS
  45. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  46. // Certificates defines the certificates to use for mutual TLS
  47. Certificates []TLSKeyPair `json:"certificates" mapstructure:"certificates"`
  48. // if enabled the HTTP client accepts any TLS certificate presented by
  49. // the server and any host name in that certificate.
  50. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  51. // This should be used only for testing.
  52. SkipTLSVerify bool `json:"skip_tls_verify" mapstructure:"skip_tls_verify"`
  53. // Headers defines a list of http headers to add to each request
  54. Headers []Header `json:"headers" mapstructure:"headers"`
  55. customTransport *http.Transport
  56. tlsConfig *tls.Config
  57. }
  58. const logSender = "httpclient"
  59. var httpConfig Config
  60. // Initialize configures HTTP clients
  61. func (c *Config) Initialize(configDir string) error {
  62. rootCAs, err := c.loadCACerts(configDir)
  63. if err != nil {
  64. return err
  65. }
  66. customTransport := http.DefaultTransport.(*http.Transport).Clone()
  67. if customTransport.TLSClientConfig != nil {
  68. customTransport.TLSClientConfig.RootCAs = rootCAs
  69. } else {
  70. customTransport.TLSClientConfig = &tls.Config{
  71. RootCAs: rootCAs,
  72. NextProtos: []string{"h2", "http/1.1"},
  73. }
  74. }
  75. customTransport.TLSClientConfig.InsecureSkipVerify = c.SkipTLSVerify
  76. c.customTransport = customTransport
  77. c.tlsConfig = customTransport.TLSClientConfig
  78. err = c.loadCertificates(configDir)
  79. if err != nil {
  80. return err
  81. }
  82. var headers []Header
  83. for _, h := range c.Headers {
  84. if h.Key != "" && h.Value != "" {
  85. headers = append(headers, h)
  86. }
  87. }
  88. c.Headers = headers
  89. httpConfig = *c
  90. return nil
  91. }
  92. // loadCACerts returns system cert pools and try to add the configured
  93. // CA certificates to it
  94. func (c *Config) loadCACerts(configDir string) (*x509.CertPool, error) {
  95. if len(c.CACertificates) == 0 {
  96. return nil, nil
  97. }
  98. rootCAs, err := x509.SystemCertPool()
  99. if err != nil {
  100. rootCAs = x509.NewCertPool()
  101. }
  102. for _, ca := range c.CACertificates {
  103. if !util.IsFileInputValid(ca) {
  104. return nil, fmt.Errorf("unable to load invalid CA certificate: %#v", ca)
  105. }
  106. if !filepath.IsAbs(ca) {
  107. ca = filepath.Join(configDir, ca)
  108. }
  109. certs, err := os.ReadFile(ca)
  110. if err != nil {
  111. return nil, fmt.Errorf("unable to load CA certificate: %v", err)
  112. }
  113. if rootCAs.AppendCertsFromPEM(certs) {
  114. logger.Debug(logSender, "", "CA certificate %#v added to the trusted certificates", ca)
  115. } else {
  116. return nil, fmt.Errorf("unable to add CA certificate %#v to the trusted cetificates", ca)
  117. }
  118. }
  119. return rootCAs, nil
  120. }
  121. func (c *Config) loadCertificates(configDir string) error {
  122. if len(c.Certificates) == 0 {
  123. return nil
  124. }
  125. for _, keyPair := range c.Certificates {
  126. cert := keyPair.Cert
  127. key := keyPair.Key
  128. if !util.IsFileInputValid(cert) {
  129. return fmt.Errorf("unable to load invalid certificate: %#v", cert)
  130. }
  131. if !util.IsFileInputValid(key) {
  132. return fmt.Errorf("unable to load invalid key: %#v", key)
  133. }
  134. if !filepath.IsAbs(cert) {
  135. cert = filepath.Join(configDir, cert)
  136. }
  137. if !filepath.IsAbs(key) {
  138. key = filepath.Join(configDir, key)
  139. }
  140. tlsCert, err := tls.LoadX509KeyPair(cert, key)
  141. if err != nil {
  142. return fmt.Errorf("unable to load key pair %#v, %#v: %v", cert, key, err)
  143. }
  144. logger.Debug(logSender, "", "client certificate %#v and key %#v successfully loaded", cert, key)
  145. c.tlsConfig.Certificates = append(c.tlsConfig.Certificates, tlsCert)
  146. }
  147. return nil
  148. }
  149. // GetHTTPClient returns an HTTP client with the configured parameters
  150. func GetHTTPClient() *http.Client {
  151. return &http.Client{
  152. Timeout: time.Duration(httpConfig.Timeout * float64(time.Second)),
  153. Transport: httpConfig.customTransport,
  154. }
  155. }
  156. // GetRetraybleHTTPClient returns an HTTP client that retry a request on error.
  157. // It uses the configured retry parameters
  158. func GetRetraybleHTTPClient() *retryablehttp.Client {
  159. client := retryablehttp.NewClient()
  160. client.HTTPClient.Timeout = time.Duration(httpConfig.Timeout * float64(time.Second))
  161. client.HTTPClient.Transport.(*http.Transport).TLSClientConfig = httpConfig.tlsConfig
  162. client.Logger = &logger.LeveledLogger{Sender: "RetryableHTTPClient"}
  163. client.RetryWaitMin = time.Duration(httpConfig.RetryWaitMin) * time.Second
  164. client.RetryWaitMax = time.Duration(httpConfig.RetryWaitMax) * time.Second
  165. client.RetryMax = httpConfig.RetryMax
  166. return client
  167. }
  168. // Get issues a GET to the specified URL
  169. func Get(url string) (*http.Response, error) {
  170. req, err := http.NewRequest(http.MethodGet, url, nil)
  171. if err != nil {
  172. return nil, err
  173. }
  174. addHeaders(req, url)
  175. client := GetHTTPClient()
  176. defer client.CloseIdleConnections()
  177. return client.Do(req)
  178. }
  179. // Post issues a POST to the specified URL
  180. func Post(url string, contentType string, body io.Reader) (*http.Response, error) {
  181. req, err := http.NewRequest(http.MethodPost, url, body)
  182. if err != nil {
  183. return nil, err
  184. }
  185. req.Header.Set("Content-Type", contentType)
  186. addHeaders(req, url)
  187. client := GetHTTPClient()
  188. defer client.CloseIdleConnections()
  189. return client.Do(req)
  190. }
  191. // RetryableGet issues a GET to the specified URL using the retryable client
  192. func RetryableGet(url string) (*http.Response, error) {
  193. req, err := retryablehttp.NewRequest(http.MethodGet, url, nil)
  194. if err != nil {
  195. return nil, err
  196. }
  197. addHeadersToRetryableReq(req, url)
  198. client := GetRetraybleHTTPClient()
  199. defer client.HTTPClient.CloseIdleConnections()
  200. return client.Do(req)
  201. }
  202. // RetryablePost issues a POST to the specified URL using the retryable client
  203. func RetryablePost(url string, contentType string, body io.Reader) (*http.Response, error) {
  204. req, err := retryablehttp.NewRequest(http.MethodPost, url, body)
  205. if err != nil {
  206. return nil, err
  207. }
  208. req.Header.Set("Content-Type", contentType)
  209. addHeadersToRetryableReq(req, url)
  210. client := GetRetraybleHTTPClient()
  211. defer client.HTTPClient.CloseIdleConnections()
  212. return client.Do(req)
  213. }
  214. func addHeaders(req *http.Request, url string) {
  215. for idx := range httpConfig.Headers {
  216. h := &httpConfig.Headers[idx]
  217. if h.URL == "" || strings.HasPrefix(url, h.URL) {
  218. req.Header.Set(h.Key, h.Value)
  219. }
  220. }
  221. }
  222. func addHeadersToRetryableReq(req *retryablehttp.Request, url string) {
  223. for idx := range httpConfig.Headers {
  224. h := &httpConfig.Headers[idx]
  225. if h.URL == "" || strings.HasPrefix(url, h.URL) {
  226. req.Header.Set(h.Key, h.Value)
  227. }
  228. }
  229. }