auth.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package apiclient
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. //"errors"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "net/http/httputil"
  13. "net/url"
  14. "github.com/crowdsecurity/crowdsec/pkg/fflag"
  15. "github.com/crowdsecurity/crowdsec/pkg/models"
  16. "github.com/go-openapi/strfmt"
  17. "github.com/pkg/errors"
  18. log "github.com/sirupsen/logrus"
  19. //"google.golang.org/appengine/log"
  20. )
  21. type APIKeyTransport struct {
  22. APIKey string
  23. // Transport is the underlying HTTP transport to use when making requests.
  24. // It will default to http.DefaultTransport if nil.
  25. Transport http.RoundTripper
  26. URL *url.URL
  27. VersionPrefix string
  28. UserAgent string
  29. }
  30. // RoundTrip implements the RoundTripper interface.
  31. func (t *APIKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  32. if t.APIKey == "" {
  33. return nil, errors.New("APIKey is empty")
  34. }
  35. // We must make a copy of the Request so
  36. // that we don't modify the Request we were given. This is required by the
  37. // specification of http.RoundTripper.
  38. req = cloneRequest(req)
  39. req.Header.Add("X-Api-Key", t.APIKey)
  40. if t.UserAgent != "" {
  41. req.Header.Add("User-Agent", t.UserAgent)
  42. }
  43. log.Debugf("req-api: %s %s", req.Method, req.URL.String())
  44. if log.GetLevel() >= log.TraceLevel {
  45. dump, _ := httputil.DumpRequest(req, true)
  46. log.Tracef("auth-api request: %s", string(dump))
  47. }
  48. // Make the HTTP request.
  49. resp, err := t.transport().RoundTrip(req)
  50. if err != nil {
  51. log.Errorf("auth-api: auth with api key failed return nil response, error: %s", err)
  52. return resp, err
  53. }
  54. if log.GetLevel() >= log.TraceLevel {
  55. dump, _ := httputil.DumpResponse(resp, true)
  56. log.Tracef("auth-api response: %s", string(dump))
  57. }
  58. log.Debugf("resp-api: http %d", resp.StatusCode)
  59. return resp, err
  60. }
  61. func (t *APIKeyTransport) Client() *http.Client {
  62. return &http.Client{Transport: t}
  63. }
  64. func (t *APIKeyTransport) transport() http.RoundTripper {
  65. if t.Transport != nil {
  66. return t.Transport
  67. }
  68. return http.DefaultTransport
  69. }
  70. type retryRoundTripper struct {
  71. next http.RoundTripper
  72. maxAttempts int
  73. retryStatusCodes []int
  74. withBackOff bool
  75. onBeforeRequest func(attempt int)
  76. }
  77. func (r retryRoundTripper) ShouldRetry(statusCode int) bool {
  78. for _, code := range r.retryStatusCodes {
  79. if code == statusCode {
  80. return true
  81. }
  82. }
  83. return false
  84. }
  85. func (r retryRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  86. var resp *http.Response
  87. var err error
  88. backoff := 0
  89. for i := 0; i < r.maxAttempts; i++ {
  90. if i > 0 {
  91. if r.withBackOff && !fflag.DisableHttpRetryBackoff.IsEnabled() {
  92. backoff += 10 + rand.Intn(20)
  93. }
  94. log.Infof("retrying in %d seconds (attempt %d of %d)", backoff, i+1, r.maxAttempts)
  95. select {
  96. case <-req.Context().Done():
  97. return resp, req.Context().Err()
  98. case <-time.After(time.Duration(backoff) * time.Second):
  99. }
  100. }
  101. if r.onBeforeRequest != nil {
  102. r.onBeforeRequest(i)
  103. }
  104. clonedReq := cloneRequest(req)
  105. resp, err = r.next.RoundTrip(clonedReq)
  106. if err == nil {
  107. if !r.ShouldRetry(resp.StatusCode) {
  108. return resp, nil
  109. }
  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 errors.Wrap(err, "could not encode jwt auth body")
  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 errors.Wrap(err, "could not create request")
  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 errors.Wrap(err, "could not get jwt token")
  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 errors.Wrap(err, "unable to decode response")
  194. }
  195. if err := t.Expiration.UnmarshalText([]byte(response.Expire)); err != nil {
  196. return errors.Wrap(err, "unable to parse jwt expiration")
  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. t.refreshTokenMutex.Lock()
  207. if t.Token == "" || t.Expiration.Add(-time.Minute).Before(time.Now().UTC()) {
  208. if err := t.refreshJwtToken(); err != nil {
  209. t.refreshTokenMutex.Unlock()
  210. return nil, err
  211. }
  212. }
  213. t.refreshTokenMutex.Unlock()
  214. if t.UserAgent != "" {
  215. req.Header.Add("User-Agent", t.UserAgent)
  216. }
  217. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", t.Token))
  218. if log.GetLevel() >= log.TraceLevel {
  219. //requestToDump := cloneRequest(req)
  220. dump, _ := httputil.DumpRequest(req, true)
  221. log.Tracef("req-jwt: %s", string(dump))
  222. }
  223. // Make the HTTP request.
  224. resp, err := t.transport().RoundTrip(req)
  225. if log.GetLevel() >= log.TraceLevel {
  226. dump, _ := httputil.DumpResponse(resp, true)
  227. log.Tracef("resp-jwt: %s (err:%v)", string(dump), err)
  228. }
  229. if err != nil {
  230. /*we had an error (network error for example, or 401 because token is refused), reset the token ?*/
  231. t.Token = ""
  232. return resp, errors.Wrapf(err, "performing jwt auth")
  233. }
  234. log.Debugf("resp-jwt: %d", resp.StatusCode)
  235. return resp, nil
  236. }
  237. func (t *JWTTransport) Client() *http.Client {
  238. return &http.Client{Transport: t}
  239. }
  240. func (t *JWTTransport) ResetToken() {
  241. log.Debug("resetting jwt token")
  242. t.refreshTokenMutex.Lock()
  243. t.Token = ""
  244. t.refreshTokenMutex.Unlock()
  245. }
  246. func (t *JWTTransport) transport() http.RoundTripper {
  247. var transport http.RoundTripper
  248. if t.Transport != nil {
  249. transport = t.Transport
  250. } else {
  251. transport = http.DefaultTransport
  252. }
  253. // a round tripper that retries once when the status is unauthorized and 5 times when infrastructure is overloaded
  254. return &retryRoundTripper{
  255. next: &retryRoundTripper{
  256. next: transport,
  257. maxAttempts: 5,
  258. withBackOff: true,
  259. retryStatusCodes: []int{http.StatusTooManyRequests, http.StatusServiceUnavailable, http.StatusGatewayTimeout},
  260. },
  261. maxAttempts: 2,
  262. withBackOff: false,
  263. retryStatusCodes: []int{http.StatusUnauthorized, http.StatusForbidden},
  264. onBeforeRequest: func(attempt int) {
  265. // reset the token only in the second attempt as this is when we know we had a 401 or 403
  266. // the second attempt is supposed to refresh the token
  267. if attempt > 0 {
  268. t.ResetToken()
  269. }
  270. },
  271. }
  272. }
  273. // cloneRequest returns a clone of the provided *http.Request. The clone is a
  274. // shallow copy of the struct and its Header map.
  275. func cloneRequest(r *http.Request) *http.Request {
  276. // shallow copy of the struct
  277. r2 := new(http.Request)
  278. *r2 = *r
  279. // deep copy of the Header
  280. r2.Header = make(http.Header, len(r.Header))
  281. for k, s := range r.Header {
  282. r2.Header[k] = append([]string(nil), s...)
  283. }
  284. if r.Body != nil {
  285. var b bytes.Buffer
  286. b.ReadFrom(r.Body)
  287. r.Body = io.NopCloser(&b)
  288. r2.Body = io.NopCloser(bytes.NewReader(b.Bytes()))
  289. }
  290. return r2
  291. }