auth.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package apiclient
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "math/rand"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "sync"
  12. "time"
  13. "github.com/go-openapi/strfmt"
  14. "github.com/pkg/errors"
  15. log "github.com/sirupsen/logrus"
  16. "github.com/crowdsecurity/crowdsec/pkg/fflag"
  17. "github.com/crowdsecurity/crowdsec/pkg/models"
  18. )
  19. type APIKeyTransport struct {
  20. APIKey string
  21. // Transport is the underlying HTTP transport to use when making requests.
  22. // It will default to http.DefaultTransport if nil.
  23. Transport http.RoundTripper
  24. URL *url.URL
  25. VersionPrefix string
  26. UserAgent string
  27. }
  28. // RoundTrip implements the RoundTripper interface.
  29. func (t *APIKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  30. if t.APIKey == "" {
  31. return nil, errors.New("APIKey is empty")
  32. }
  33. // We must make a copy of the Request so
  34. // that we don't modify the Request we were given. This is required by the
  35. // specification of http.RoundTripper.
  36. req = cloneRequest(req)
  37. req.Header.Add("X-Api-Key", t.APIKey)
  38. if t.UserAgent != "" {
  39. req.Header.Add("User-Agent", t.UserAgent)
  40. }
  41. log.Debugf("req-api: %s %s", req.Method, req.URL.String())
  42. if log.GetLevel() >= log.TraceLevel {
  43. dump, _ := httputil.DumpRequest(req, true)
  44. log.Tracef("auth-api request: %s", string(dump))
  45. }
  46. // Make the HTTP request.
  47. resp, err := t.transport().RoundTrip(req)
  48. if err != nil {
  49. log.Errorf("auth-api: auth with api key failed return nil response, error: %s", err)
  50. return resp, err
  51. }
  52. if log.GetLevel() >= log.TraceLevel {
  53. dump, _ := httputil.DumpResponse(resp, true)
  54. log.Tracef("auth-api response: %s", string(dump))
  55. }
  56. log.Debugf("resp-api: http %d", resp.StatusCode)
  57. return resp, err
  58. }
  59. func (t *APIKeyTransport) Client() *http.Client {
  60. return &http.Client{Transport: t}
  61. }
  62. func (t *APIKeyTransport) transport() http.RoundTripper {
  63. if t.Transport != nil {
  64. return t.Transport
  65. }
  66. return http.DefaultTransport
  67. }
  68. type retryRoundTripper struct {
  69. next http.RoundTripper
  70. maxAttempts int
  71. retryStatusCodes []int
  72. withBackOff bool
  73. onBeforeRequest func(attempt int)
  74. }
  75. func (r retryRoundTripper) ShouldRetry(statusCode int) bool {
  76. for _, code := range r.retryStatusCodes {
  77. if code == statusCode {
  78. return true
  79. }
  80. }
  81. return false
  82. }
  83. func (r retryRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  84. var resp *http.Response
  85. var err error
  86. backoff := 0
  87. maxAttempts := r.maxAttempts
  88. if fflag.DisableHttpRetryBackoff.IsEnabled() {
  89. maxAttempts = 1
  90. }
  91. for i := 0; i < maxAttempts; i++ {
  92. if i > 0 {
  93. if r.withBackOff {
  94. backoff += 10 + rand.Intn(20)
  95. }
  96. log.Infof("retrying in %d seconds (attempt %d of %d)", backoff, i+1, r.maxAttempts)
  97. select {
  98. case <-req.Context().Done():
  99. return resp, req.Context().Err()
  100. case <-time.After(time.Duration(backoff) * time.Second):
  101. }
  102. }
  103. if r.onBeforeRequest != nil {
  104. r.onBeforeRequest(i)
  105. }
  106. clonedReq := cloneRequest(req)
  107. resp, err = r.next.RoundTrip(clonedReq)
  108. if err != nil {
  109. left := maxAttempts - i - 1
  110. if left > 0 {
  111. log.Errorf("error while performing request: %s; %d retries left", err, left)
  112. }
  113. continue
  114. }
  115. if !r.ShouldRetry(resp.StatusCode) {
  116. return resp, nil
  117. }
  118. }
  119. return resp, err
  120. }
  121. type JWTTransport struct {
  122. MachineID *string
  123. Password *strfmt.Password
  124. Token string
  125. Expiration time.Time
  126. Scenarios []string
  127. URL *url.URL
  128. VersionPrefix string
  129. UserAgent string
  130. // Transport is the underlying HTTP transport to use when making requests.
  131. // It will default to http.DefaultTransport if nil.
  132. Transport http.RoundTripper
  133. UpdateScenario func() ([]string, error)
  134. refreshTokenMutex sync.Mutex
  135. }
  136. func (t *JWTTransport) refreshJwtToken() error {
  137. var err error
  138. if t.UpdateScenario != nil {
  139. t.Scenarios, err = t.UpdateScenario()
  140. if err != nil {
  141. return fmt.Errorf("can't update scenario list: %s", err)
  142. }
  143. log.Debugf("scenarios list updated for '%s'", *t.MachineID)
  144. }
  145. var auth = models.WatcherAuthRequest{
  146. MachineID: t.MachineID,
  147. Password: t.Password,
  148. Scenarios: t.Scenarios,
  149. }
  150. var response models.WatcherAuthResponse
  151. /*
  152. we don't use the main client, so let's build the body
  153. */
  154. var buf io.ReadWriter = &bytes.Buffer{}
  155. enc := json.NewEncoder(buf)
  156. enc.SetEscapeHTML(false)
  157. err = enc.Encode(auth)
  158. if err != nil {
  159. return fmt.Errorf("could not encode jwt auth body: %w", err)
  160. }
  161. req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s%s/watchers/login", t.URL, t.VersionPrefix), buf)
  162. if err != nil {
  163. return fmt.Errorf("could not create request: %w", err)
  164. }
  165. req.Header.Add("Content-Type", "application/json")
  166. client := &http.Client{
  167. Transport: &retryRoundTripper{
  168. next: http.DefaultTransport,
  169. maxAttempts: 5,
  170. withBackOff: true,
  171. retryStatusCodes: []int{http.StatusTooManyRequests, http.StatusServiceUnavailable, http.StatusGatewayTimeout, http.StatusInternalServerError},
  172. },
  173. }
  174. if t.UserAgent != "" {
  175. req.Header.Add("User-Agent", t.UserAgent)
  176. }
  177. if log.GetLevel() >= log.TraceLevel {
  178. dump, _ := httputil.DumpRequest(req, true)
  179. log.Tracef("auth-jwt request: %s", string(dump))
  180. }
  181. log.Debugf("auth-jwt(auth): %s %s", req.Method, req.URL.String())
  182. resp, err := client.Do(req)
  183. if err != nil {
  184. return fmt.Errorf("could not get jwt token: %w", err)
  185. }
  186. log.Debugf("auth-jwt : http %d", resp.StatusCode)
  187. if log.GetLevel() >= log.TraceLevel {
  188. dump, _ := httputil.DumpResponse(resp, true)
  189. log.Tracef("auth-jwt response: %s", string(dump))
  190. }
  191. defer resp.Body.Close()
  192. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  193. log.Debugf("received response status %q when fetching %v", resp.Status, req.URL)
  194. err = CheckResponse(resp)
  195. if err != nil {
  196. return err
  197. }
  198. }
  199. if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
  200. return fmt.Errorf("unable to decode response: %w", err)
  201. }
  202. if err := t.Expiration.UnmarshalText([]byte(response.Expire)); err != nil {
  203. return fmt.Errorf("unable to parse jwt expiration: %w", err)
  204. }
  205. t.Token = response.Token
  206. log.Debugf("token %s will expire on %s", t.Token, t.Expiration.String())
  207. return nil
  208. }
  209. // RoundTrip implements the RoundTripper interface.
  210. func (t *JWTTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  211. // in a few occasions several goroutines will execute refreshJwtToken concurrently which is useless and will cause overload on CAPI
  212. // we use a mutex to avoid this
  213. //We also bypass the refresh if we are requesting the login endpoint, as it does not require a token, and it leads to do 2 requests instead of one (refresh + actual login request)
  214. t.refreshTokenMutex.Lock()
  215. if req.URL.Path != "/"+t.VersionPrefix+"/watchers/login" && (t.Token == "" || t.Expiration.Add(-time.Minute).Before(time.Now().UTC())) {
  216. if err := t.refreshJwtToken(); err != nil {
  217. t.refreshTokenMutex.Unlock()
  218. return nil, err
  219. }
  220. }
  221. t.refreshTokenMutex.Unlock()
  222. if t.UserAgent != "" {
  223. req.Header.Add("User-Agent", t.UserAgent)
  224. }
  225. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", t.Token))
  226. if log.GetLevel() >= log.TraceLevel {
  227. //requestToDump := cloneRequest(req)
  228. dump, _ := httputil.DumpRequest(req, true)
  229. log.Tracef("req-jwt: %s", string(dump))
  230. }
  231. // Make the HTTP request.
  232. resp, err := t.transport().RoundTrip(req)
  233. if log.GetLevel() >= log.TraceLevel {
  234. dump, _ := httputil.DumpResponse(resp, true)
  235. log.Tracef("resp-jwt: %s (err:%v)", string(dump), err)
  236. }
  237. if err != nil {
  238. /*we had an error (network error for example, or 401 because token is refused), reset the token ?*/
  239. t.Token = ""
  240. return resp, fmt.Errorf("performing jwt auth: %w", err)
  241. }
  242. if resp != nil {
  243. log.Debugf("resp-jwt: %d", resp.StatusCode)
  244. }
  245. return resp, nil
  246. }
  247. func (t *JWTTransport) Client() *http.Client {
  248. return &http.Client{Transport: t}
  249. }
  250. func (t *JWTTransport) ResetToken() {
  251. log.Debug("resetting jwt token")
  252. t.refreshTokenMutex.Lock()
  253. t.Token = ""
  254. t.refreshTokenMutex.Unlock()
  255. }
  256. func (t *JWTTransport) transport() http.RoundTripper {
  257. var transport http.RoundTripper
  258. if t.Transport != nil {
  259. transport = t.Transport
  260. } else {
  261. transport = http.DefaultTransport
  262. }
  263. // a round tripper that retries once when the status is unauthorized and 5 times when infrastructure is overloaded
  264. return &retryRoundTripper{
  265. next: &retryRoundTripper{
  266. next: transport,
  267. maxAttempts: 5,
  268. withBackOff: true,
  269. retryStatusCodes: []int{http.StatusTooManyRequests, http.StatusServiceUnavailable, http.StatusGatewayTimeout},
  270. },
  271. maxAttempts: 2,
  272. withBackOff: false,
  273. retryStatusCodes: []int{http.StatusUnauthorized, http.StatusForbidden},
  274. onBeforeRequest: func(attempt int) {
  275. // reset the token only in the second attempt as this is when we know we had a 401 or 403
  276. // the second attempt is supposed to refresh the token
  277. if attempt > 0 {
  278. t.ResetToken()
  279. }
  280. },
  281. }
  282. }
  283. // cloneRequest returns a clone of the provided *http.Request. The clone is a
  284. // shallow copy of the struct and its Header map.
  285. func cloneRequest(r *http.Request) *http.Request {
  286. // shallow copy of the struct
  287. r2 := new(http.Request)
  288. *r2 = *r
  289. // deep copy of the Header
  290. r2.Header = make(http.Header, len(r.Header))
  291. for k, s := range r.Header {
  292. r2.Header[k] = append([]string(nil), s...)
  293. }
  294. if r.Body != nil {
  295. var b bytes.Buffer
  296. b.ReadFrom(r.Body)
  297. r.Body = io.NopCloser(&b)
  298. r2.Body = io.NopCloser(bytes.NewReader(b.Bytes()))
  299. }
  300. return r2
  301. }