Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
mmetc committed Jan 5, 2024
1 parent 5622ac8 commit 12a74ac
Show file tree
Hide file tree
Showing 25 changed files with 397 additions and 187 deletions.
32 changes: 14 additions & 18 deletions pkg/apiclient/alerts_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@ type AlertsDeleteOpts struct {
}

func (s *AlertsService) Add(ctx context.Context, alerts models.AddAlertsRequest) (*models.AddAlertsResponse, *Response, error) {
var addedIds models.AddAlertsResponse

u := fmt.Sprintf("%s/alerts", s.client.URLPrefix)
req, err := s.client.NewRequest(http.MethodPost, u, &alerts)

req, err := s.client.NewRequest(http.MethodPost, u, &alerts)
if err != nil {
return nil, nil, err
}

addedIds := models.AddAlertsResponse{}

resp, err := s.client.Do(ctx, req, &addedIds)
if err != nil {
return nil, resp, err
Expand All @@ -68,29 +68,25 @@ func (s *AlertsService) Add(ctx context.Context, alerts models.AddAlertsRequest)

// to demo query arguments
func (s *AlertsService) List(ctx context.Context, opts AlertsListOpts) (*models.GetAlertsResponse, *Response, error) {
var (
alerts models.GetAlertsResponse
URI string
)

u := fmt.Sprintf("%s/alerts", s.client.URLPrefix)
params, err := qs.Values(opts)

params, err := qs.Values(opts)
if err != nil {
return nil, nil, fmt.Errorf("building query: %w", err)
}

URI := u
if len(params) > 0 {
URI = fmt.Sprintf("%s?%s", u, params.Encode())
} else {
URI = u
URI = fmt.Sprintf("%s?%s", URI, params.Encode())
}

req, err := s.client.NewRequest(http.MethodGet, URI, nil)
if err != nil {
return nil, nil, fmt.Errorf("building request: %w", err)
}

alerts := models.GetAlertsResponse{}

resp, err := s.client.Do(ctx, req, &alerts)
if err != nil {
return nil, resp, fmt.Errorf("performing request: %w", err)
Expand All @@ -101,8 +97,6 @@ func (s *AlertsService) List(ctx context.Context, opts AlertsListOpts) (*models.

// to demo query arguments
func (s *AlertsService) Delete(ctx context.Context, opts AlertsDeleteOpts) (*models.DeleteAlertsResponse, *Response, error) {
var alerts models.DeleteAlertsResponse

params, err := qs.Values(opts)
if err != nil {
return nil, nil, err
Expand All @@ -115,6 +109,8 @@ func (s *AlertsService) Delete(ctx context.Context, opts AlertsDeleteOpts) (*mod
return nil, nil, err
}

alerts := models.DeleteAlertsResponse{}

resp, err := s.client.Do(ctx, req, &alerts)
if err != nil {
return nil, resp, err
Expand All @@ -124,15 +120,15 @@ func (s *AlertsService) Delete(ctx context.Context, opts AlertsDeleteOpts) (*mod
}

func (s *AlertsService) DeleteOne(ctx context.Context, alertID string) (*models.DeleteAlertsResponse, *Response, error) {
var alerts models.DeleteAlertsResponse

u := fmt.Sprintf("%s/alerts/%s", s.client.URLPrefix, alertID)

req, err := s.client.NewRequest(http.MethodDelete, u, nil)
if err != nil {
return nil, nil, err
}

alerts := models.DeleteAlertsResponse{}

resp, err := s.client.Do(ctx, req, &alerts)
if err != nil {
return nil, resp, err
Expand All @@ -142,15 +138,15 @@ func (s *AlertsService) DeleteOne(ctx context.Context, alertID string) (*models.
}

func (s *AlertsService) GetByID(ctx context.Context, alertID int) (*models.Alert, *Response, error) {
var alert models.Alert

u := fmt.Sprintf("%s/alerts/%d", s.client.URLPrefix, alertID)

req, err := s.client.NewRequest(http.MethodGet, u, nil)
if err != nil {
return nil, nil, err
}

alert := models.Alert{}

resp, err := s.client.Do(ctx, req, &alert)
if err != nil {
return nil, nil, err
Expand Down
42 changes: 24 additions & 18 deletions pkg/apiclient/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package apiclient
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
Expand All @@ -13,7 +14,6 @@ import (
"time"

"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"

"github.com/crowdsecurity/crowdsec/pkg/fflag"
Expand Down Expand Up @@ -52,10 +52,12 @@ func (t *APIKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
dump, _ := httputil.DumpRequest(req, true)
log.Tracef("auth-api request: %s", string(dump))
}

// Make the HTTP request.
resp, err := t.transport().RoundTrip(req)
if err != nil {
log.Errorf("auth-api: auth with api key failed return nil response, error: %s", err)

Check warning on line 60 in pkg/apiclient/auth.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiclient/auth.go#L60

Added line #L60 was not covered by tests
return resp, err
}

Expand Down Expand Up @@ -115,13 +117,15 @@ func (r retryRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
for i := 0; i < maxAttempts; i++ {
if i > 0 {
if r.withBackOff {
//nolint:gosec

Check warning on line 120 in pkg/apiclient/auth.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiclient/auth.go#L120

Added line #L120 was not covered by tests
backoff += 10 + rand.Intn(20)
}

log.Infof("retrying in %d seconds (attempt %d of %d)", backoff, i+1, r.maxAttempts)

select {
case <-req.Context().Done():
return resp, req.Context().Err()
return nil, req.Context().Err()

Check warning on line 128 in pkg/apiclient/auth.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiclient/auth.go#L128

Added line #L128 was not covered by tests
case <-time.After(time.Duration(backoff) * time.Second):
}
}
Expand All @@ -131,11 +135,10 @@ func (r retryRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
}

clonedReq := cloneRequest(req)
resp, err = r.next.RoundTrip(clonedReq)

resp, err = r.next.RoundTrip(clonedReq)
if err != nil {
left := maxAttempts - i - 1
if left > 0 {
if left := maxAttempts - i - 1; left > 0 {
log.Errorf("error while performing request: %s; %d retries left", err, left)
}

Expand All @@ -147,7 +150,7 @@ func (r retryRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
}
}

return resp, err
return resp, nil
}

type JWTTransport struct {
Expand All @@ -168,23 +171,22 @@ type JWTTransport struct {

func (t *JWTTransport) refreshJwtToken() error {
var err error

if t.UpdateScenario != nil {
t.Scenarios, err = t.UpdateScenario()
if err != nil {
return fmt.Errorf("can't update scenario list: %s", err)
return fmt.Errorf("can't update scenario list: %w", err)

Check warning on line 178 in pkg/apiclient/auth.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiclient/auth.go#L178

Added line #L178 was not covered by tests
}

log.Debugf("scenarios list updated for '%s'", *t.MachineID)
}

var auth = models.WatcherAuthRequest{
auth := models.WatcherAuthRequest{
MachineID: t.MachineID,
Password: t.Password,
Scenarios: t.Scenarios,
}

var response models.WatcherAuthResponse

/*
we don't use the main client, so let's build the body
*/
Expand Down Expand Up @@ -247,6 +249,8 @@ func (t *JWTTransport) refreshJwtToken() error {
}
}

var response models.WatcherAuthResponse

if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return fmt.Errorf("unable to decode response: %w", err)
}
Expand All @@ -264,13 +268,14 @@ func (t *JWTTransport) refreshJwtToken() error {

// RoundTrip implements the RoundTripper interface.
func (t *JWTTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// in a few occasions several goroutines will execute refreshJwtToken concurrently which is useless and will cause overload on CAPI
// In a few occasions several goroutines will execute refreshJwtToken concurrently which is useless and will cause overload on CAPI
// we use a mutex to avoid this
//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)
// 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)
t.refreshTokenMutex.Lock()
if req.URL.Path != "/"+t.VersionPrefix+"/watchers/login" && (t.Token == "" || t.Expiration.Add(-time.Minute).Before(time.Now().UTC())) {
if err := t.refreshJwtToken(); err != nil {
t.refreshTokenMutex.Unlock()

return nil, err
}
}
Expand All @@ -296,8 +301,9 @@ func (t *JWTTransport) RoundTrip(req *http.Request) (*http.Response, error) {
}

if err != nil {
/*we had an error (network error for example, or 401 because token is refused), reset the token ?*/
// we had an error (network error for example, or 401 because token is refused), reset the token?

Check warning on line 304 in pkg/apiclient/auth.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiclient/auth.go#L304

Added line #L304 was not covered by tests
t.Token = ""

Check warning on line 306 in pkg/apiclient/auth.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiclient/auth.go#L306

Added line #L306 was not covered by tests
return resp, fmt.Errorf("performing jwt auth: %w", err)
}

Expand All @@ -319,14 +325,13 @@ func (t *JWTTransport) ResetToken() {
t.refreshTokenMutex.Unlock()
}

// transport() returns a round tripper that retries once when the status is unauthorized, and 5 times when infrastructure is overloaded.
func (t *JWTTransport) transport() http.RoundTripper {
var transport http.RoundTripper
if t.Transport != nil {
transport = t.Transport
} else {
transport := t.Transport
if transport == nil {
transport = http.DefaultTransport
}
// a round tripper that retries once when the status is unauthorized and 5 times when infrastructure is overloaded

return &retryRoundTripper{
next: &retryRoundTripper{
next: transport,
Expand Down Expand Up @@ -355,6 +360,7 @@ func cloneRequest(r *http.Request) *http.Request {
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header, len(r.Header))

for k, s := range r.Header {
r2.Header[k] = append([]string(nil), s...)
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/apiclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ func NewClient(config *Config) (*ApiClient, error) {
VersionPrefix: config.VersionPrefix,
UpdateScenario: config.UpdateScenario,
}

tlsconfig := tls.Config{InsecureSkipVerify: InsecureSkipVerify}
tlsconfig.RootCAs = CaCertPool

Expand Down Expand Up @@ -180,8 +181,7 @@ func (e *ErrorResponse) Error() string {
}

func newResponse(r *http.Response) *Response {
response := &Response{Response: r}
return response
return &Response{Response: r}
}

func CheckResponse(r *http.Response) error {
Expand Down
2 changes: 1 addition & 1 deletion pkg/apiclient/client_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (c *ApiClient) Do(ctx context.Context, req *http.Request, v interface{}) (*

if log.GetLevel() >= log.DebugLevel {
for k, v := range resp.Header {
log.Debugf("[headers] %s : %s", k, v)
log.Debugf("[headers] %s: %s", k, v)
}

dump, err := httputil.DumpResponse(resp, true)
Expand Down
Loading

0 comments on commit 12a74ac

Please sign in to comment.