auth.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. for i := 0; i < r.maxAttempts; i++ {
  88. if i > 0 {
  89. if r.withBackOff && !fflag.DisableHttpRetryBackoff.IsEnabled() {
  90. backoff += 10 + rand.Intn(20)
  91. }
  92. log.Infof("retrying in %d seconds (attempt %d of %d)", backoff, i+1, r.maxAttempts)
  93. select {
  94. case <-req.Context().Done():
  95. return resp, req.Context().Err()
  96. case <-time.After(time.Duration(backoff) * time.Second):
  97. }
  98. }
  99. if r.onBeforeRequest != nil {
  100. r.onBeforeRequest(i)
  101. }
  102. clonedReq := cloneRequest(req)
  103. resp, err = r.next.RoundTrip(clonedReq)
  104. if err != nil {
  105. log.Errorf("error while performing request: %s; %d retries left", err, r.maxAttempts-i-1)
  106. continue
  107. }
  108. if !r.ShouldRetry(resp.StatusCode) {
  109. return resp, nil
  110. }
  111. }
  112. return resp, err
  113. }
  114. type JWTTransport struct {
  115. MachineID *string
  116. Password *strfmt.Password
  117. Token string
  118. Expiration time.Time
  119. Scenarios []string
  120. URL *url.URL
  121. VersionPrefix string
  122. UserAgent string
  123. // Transport is the underlying HTTP transport to use when making requests.
  124. // It will default to http.DefaultTransport if nil.
  125. Transport http.RoundTripper
  126. UpdateScenario func() ([]string, error)
  127. refreshTokenMutex sync.Mutex
  128. }
  129. func (t *JWTTransport) refreshJwtToken() error {
  130. var err error
  131. if t.UpdateScenario != nil {
  132. t.Scenarios, err = t.UpdateScenario()
  133. if err != nil {
  134. return fmt.Errorf("can't update scenario list: %s", err)
  135. }
  136. log.Debugf("scenarios list updated for '%s'", *t.MachineID)
  137. }
  138. var auth = models.WatcherAuthRequest{
  139. MachineID: t.MachineID,
  140. Password: t.Password,
  141. Scenarios: t.Scenarios,
  142. }
  143. var response models.WatcherAuthResponse
  144. /*
  145. we don't use the main client, so let's build the body
  146. */
  147. var buf io.ReadWriter = &bytes.Buffer{}
  148. enc := json.NewEncoder(buf)
  149. enc.SetEscapeHTML(false)
  150. err = enc.Encode(auth)
  151. if err != nil {
  152. return fmt.Errorf("could not encode jwt auth body: %w", err)
  153. }
  154. req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s%s/watchers/login", t.URL, t.VersionPrefix), buf)
  155. if err != nil {
  156. return fmt.Errorf("could not create request: %w", err)
  157. }
  158. req.Header.Add("Content-Type", "application/json")
  159. client := &http.Client{
  160. Transport: &retryRoundTripper{
  161. next: http.DefaultTransport,
  162. maxAttempts: 5,
  163. withBackOff: true,
  164. retryStatusCodes: []int{http.StatusTooManyRequests, http.StatusServiceUnavailable, http.StatusGatewayTimeout, http.StatusInternalServerError},
  165. },
  166. }
  167. if t.UserAgent != "" {
  168. req.Header.Add("User-Agent", t.UserAgent)
  169. }
  170. if log.GetLevel() >= log.TraceLevel {
  171. dump, _ := httputil.DumpRequest(req, true)
  172. log.Tracef("auth-jwt request: %s", string(dump))
  173. }
  174. log.Debugf("auth-jwt(auth): %s %s", req.Method, req.URL.String())
  175. resp, err := client.Do(req)
  176. if err != nil {
  177. return fmt.Errorf("could not get jwt token: %w", err)
  178. }
  179. log.Debugf("auth-jwt : http %d", resp.StatusCode)
  180. if log.GetLevel() >= log.TraceLevel {
  181. dump, _ := httputil.DumpResponse(resp, true)
  182. log.Tracef("auth-jwt response: %s", string(dump))
  183. }
  184. defer resp.Body.Close()
  185. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  186. log.Debugf("received response status %q when fetching %v", resp.Status, req.URL)
  187. err = CheckResponse(resp)
  188. if err != nil {
  189. return err
  190. }
  191. }
  192. if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
  193. return fmt.Errorf("unable to decode response: %w", err)
  194. }
  195. if err := t.Expiration.UnmarshalText([]byte(response.Expire)); err != nil {
  196. return fmt.Errorf("unable to parse jwt expiration: %w", err)
  197. }
  198. t.Token = response.Token
  199. log.Debugf("token %s will expire on %s", t.Token, t.Expiration.String())
  200. return nil
  201. }
  202. // RoundTrip implements the RoundTripper interface.
  203. func (t *JWTTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  204. // in a few occasions several goroutines will execute refreshJwtToken concurrently which is useless and will cause overload on CAPI
  205. // we use a mutex to avoid this
  206. //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)
  207. t.refreshTokenMutex.Lock()
  208. if req.URL.Path != "/"+t.VersionPrefix+"/watchers/login" && (t.Token == "" || t.Expiration.Add(-time.Minute).Before(time.Now().UTC())) {
  209. if err := t.refreshJwtToken(); err != nil {
  210. t.refreshTokenMutex.Unlock()
  211. return nil, err
  212. }
  213. }
  214. t.refreshTokenMutex.Unlock()
  215. if t.UserAgent != "" {
  216. req.Header.Add("User-Agent", t.UserAgent)
  217. }
  218. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", t.Token))
  219. if log.GetLevel() >= log.TraceLevel {
  220. //requestToDump := cloneRequest(req)
  221. dump, _ := httputil.DumpRequest(req, true)
  222. log.Tracef("req-jwt: %s", string(dump))
  223. }
  224. // Make the HTTP request.
  225. resp, err := t.transport().RoundTrip(req)
  226. if log.GetLevel() >= log.TraceLevel {
  227. dump, _ := httputil.DumpResponse(resp, true)
  228. log.Tracef("resp-jwt: %s (err:%v)", string(dump), err)
  229. }
  230. if err != nil {
  231. /*we had an error (network error for example, or 401 because token is refused), reset the token ?*/
  232. t.Token = ""
  233. return resp, fmt.Errorf("performing jwt auth: %w", err)
  234. }
  235. log.Debugf("resp-jwt: %d", resp.StatusCode)
  236. return resp, nil
  237. }
  238. func (t *JWTTransport) Client() *http.Client {
  239. return &http.Client{Transport: t}
  240. }
  241. func (t *JWTTransport) ResetToken() {
  242. log.Debug("resetting jwt token")
  243. t.refreshTokenMutex.Lock()
  244. t.Token = ""
  245. t.refreshTokenMutex.Unlock()
  246. }
  247. func (t *JWTTransport) transport() http.RoundTripper {
  248. var transport http.RoundTripper
  249. if t.Transport != nil {
  250. transport = t.Transport
  251. } else {
  252. transport = http.DefaultTransport
  253. }
  254. // a round tripper that retries once when the status is unauthorized and 5 times when infrastructure is overloaded
  255. return &retryRoundTripper{
  256. next: &retryRoundTripper{
  257. next: transport,
  258. maxAttempts: 5,
  259. withBackOff: true,
  260. retryStatusCodes: []int{http.StatusTooManyRequests, http.StatusServiceUnavailable, http.StatusGatewayTimeout},
  261. },
  262. maxAttempts: 2,
  263. withBackOff: false,
  264. retryStatusCodes: []int{http.StatusUnauthorized, http.StatusForbidden},
  265. onBeforeRequest: func(attempt int) {
  266. // reset the token only in the second attempt as this is when we know we had a 401 or 403
  267. // the second attempt is supposed to refresh the token
  268. if attempt > 0 {
  269. t.ResetToken()
  270. }
  271. },
  272. }
  273. }
  274. // cloneRequest returns a clone of the provided *http.Request. The clone is a
  275. // shallow copy of the struct and its Header map.
  276. func cloneRequest(r *http.Request) *http.Request {
  277. // shallow copy of the struct
  278. r2 := new(http.Request)
  279. *r2 = *r
  280. // deep copy of the Header
  281. r2.Header = make(http.Header, len(r.Header))
  282. for k, s := range r.Header {
  283. r2.Header[k] = append([]string(nil), s...)
  284. }
  285. if r.Body != nil {
  286. var b bytes.Buffer
  287. b.ReadFrom(r.Body)
  288. r.Body = io.NopCloser(&b)
  289. r2.Body = io.NopCloser(bytes.NewReader(b.Bytes()))
  290. }
  291. return r2
  292. }