Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,6 @@ linters:
depguard:
rules:
wrap:
files:
- '!**/pkg/database/*.go'
deny:
- pkg: github.com/pkg/errors
desc: errors.Wrap() is deprecated in favor of fmt.Errorf()
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ require (
github.com/nxadm/tail v1.4.11
github.com/oschwald/geoip2-golang v1.9.0
github.com/oschwald/maxminddb-golang v1.12.0
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.23.2
github.com/prometheus/client_model v0.6.2
github.com/prometheus/common v0.66.1
Expand Down
4 changes: 2 additions & 2 deletions pkg/apiserver/alerts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func TestAlertListFilters(t *testing.T) {

w := lapi.RecordResponse(t, ctx, "GET", "/v1/alerts?test=test", alertContent, "password")
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.JSONEq(t, `{"message":"Filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())
assert.JSONEq(t, `{"message":"filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())

// get without filters

Expand Down Expand Up @@ -418,7 +418,7 @@ func TestListAlert(t *testing.T) {

w := lapi.RecordResponse(t, ctx, "GET", "/v1/alerts?test=test", emptyBody, "password")
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.JSONEq(t, `{"message":"Filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())
assert.JSONEq(t, `{"message":"filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())

// List Alert

Expand Down
9 changes: 4 additions & 5 deletions pkg/database/alertfilter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"strings"
"time"

"github.com/pkg/errors"
log "github.com/sirupsen/logrus"

"github.com/crowdsecurity/go-cs-lib/cstime"
Expand Down Expand Up @@ -148,7 +147,7 @@ func handleAlertIPPredicates(rng csnet.Range, contains bool, predicates *[]predi
case 0:
return nil
default:
return errors.Wrapf(InvalidFilter, "Unknown ip size %d", rng.Size())
return fmt.Errorf("unknown ip size %d: %w", rng.Size(), InvalidFilter)
}
}

Expand Down Expand Up @@ -200,7 +199,7 @@ func alertPredicatesFromFilter(filter map[string][]string) ([]predicate.Alert, e
case "contains":
contains, err = strconv.ParseBool(value[0])
if err != nil {
return nil, errors.Wrapf(InvalidFilter, "invalid contains value : %s", err)
return nil, fmt.Errorf("invalid contains value: %w: %w", err, InvalidFilter)
}
case "scope":
handleScopeFilter(value[0], &predicates)
Expand Down Expand Up @@ -230,7 +229,7 @@ func alertPredicatesFromFilter(filter map[string][]string) ([]predicate.Alert, e
}
case "has_active_decision":
if hasActiveDecision, err = strconv.ParseBool(value[0]); err != nil {
return nil, errors.Wrapf(ParseType, "'%s' is not a boolean: %s", value[0], err)
return nil, fmt.Errorf("'%s' is not a boolean: %w: %w", value[0], err, ParseType)
}

if hasActiveDecision {
Expand All @@ -247,7 +246,7 @@ func alertPredicatesFromFilter(filter map[string][]string) ([]predicate.Alert, e
case "with_decisions":
continue
default:
return nil, errors.Wrapf(InvalidFilter, "Filter parameter '%s' is unknown (=%s)", param, value[0])
return nil, fmt.Errorf("filter parameter '%s' is unknown (=%s): %w", param, value[0], InvalidFilter)
}
}

Expand Down
38 changes: 19 additions & 19 deletions pkg/database/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ package database
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"

"github.com/pkg/errors"
log "github.com/sirupsen/logrus"

"github.com/crowdsecurity/go-cs-lib/cstime"
Expand Down Expand Up @@ -201,7 +201,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models

startAtTime, err := time.Parse(time.RFC3339, *alertItem.StartAt)
if err != nil {
return 0, 0, 0, errors.Wrapf(ParseTimeFail, "start_at field time '%s': %s", *alertItem.StartAt, err)
return 0, 0, 0, fmt.Errorf("start_at field time '%s': %w: %w", *alertItem.StartAt, err, ParseTimeFail)
}

if alertItem.StopAt == nil {
Expand All @@ -210,7 +210,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models

stopAtTime, err := time.Parse(time.RFC3339, *alertItem.StopAt)
if err != nil {
return 0, 0, 0, errors.Wrapf(ParseTimeFail, "stop_at field time '%s': %s", *alertItem.StopAt, err)
return 0, 0, 0, fmt.Errorf("stop_at field time '%s': %w: %w", *alertItem.StopAt, err, ParseTimeFail)
}

ts, err := time.Parse(time.RFC3339, *alertItem.StopAt)
Expand Down Expand Up @@ -245,7 +245,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models

alertRef, err := alertB.Save(ctx)
if err != nil {
return 0, 0, 0, errors.Wrapf(BulkError, "error creating alert : %s", err)
return 0, 0, 0, fmt.Errorf("error creating alert: %w: %w", err, BulkError)
}

if len(alertItem.Decisions) == 0 {
Expand All @@ -254,7 +254,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models

txClient, err := c.Ent.Tx(ctx)
if err != nil {
return 0, 0, 0, errors.Wrapf(BulkError, "error creating transaction : %s", err)
return 0, 0, 0, fmt.Errorf("error creating transaction: %w: %w", err, BulkError)
}

decOrigin := CapiMachineID
Expand Down Expand Up @@ -373,7 +373,7 @@ func (c *Client) createDecisionBatch(ctx context.Context, simulated bool, stopAt

duration, err := cstime.ParseDurationWithDays(*decisionItem.Duration)
if err != nil {
return nil, errors.Wrapf(ParseDurationFail, "decision duration '%+v' : %s", *decisionItem.Duration, err)
return nil, fmt.Errorf("decision duration '%+v': %w: %w", *decisionItem.Duration, err, ParseDurationFail)
}

// if the scope is IP or Range, convert the value to integers
Expand Down Expand Up @@ -456,7 +456,7 @@ func buildEventCreates(ctx context.Context, logger log.FieldLogger, client *ent.

marshallMetas, err := json.Marshal(eventItem.Meta)
if err != nil {
return nil, errors.Wrapf(MarshalFail, "event meta '%v' : %s", eventItem.Meta, err)
return nil, fmt.Errorf("event meta '%v': %w: %w", eventItem.Meta, err, MarshalFail)
}

// the serialized field is too big, let's try to progressively strip it
Expand All @@ -475,7 +475,7 @@ func buildEventCreates(ctx context.Context, logger log.FieldLogger, client *ent.

marshallMetas, err = json.Marshal(eventItem.Meta)
if err != nil {
return nil, errors.Wrapf(MarshalFail, "event meta '%v' : %s", eventItem.Meta, err)
return nil, fmt.Errorf("event meta '%v': %w: %w", eventItem.Meta, err, MarshalFail)
}

if event.SerializedValidator(string(marshallMetas)) == nil {
Expand Down Expand Up @@ -599,7 +599,7 @@ func saveAlerts(ctx context.Context, c *Client, batch []alertCreatePlan) ([]stri

alertsCreateBulk, err := c.Ent.Alert.CreateBulk(builders...).Save(ctx)
if err != nil {
return nil, errors.Wrapf(BulkError, "bulk creating alert : %s", err)
return nil, fmt.Errorf("bulk creating alert: %w: %w", err, BulkError)
}

ret := make([]string, len(alertsCreateBulk))
Expand Down Expand Up @@ -798,7 +798,7 @@ func (c *Client) QueryAlertWithFilter(ctx context.Context, filter map[string][]s
if val, ok := filter["limit"]; ok {
limitConv, err := strconv.Atoi(val[0])
if err != nil {
return nil, errors.Wrapf(QueryFail, "bad limit in parameters: %s", val)
return nil, fmt.Errorf("bad limit in parameters: %s: %w", val, QueryFail)
}

limit = limitConv
Expand Down Expand Up @@ -843,7 +843,7 @@ func (c *Client) QueryAlertWithFilter(ctx context.Context, filter map[string][]s

result, err := alerts.Limit(paginationSize).Offset(offset).All(ctx)
if err != nil {
return nil, errors.Wrapf(QueryFail, "pagination size: %d, offset: %d: %s", paginationSize, offset, err)
return nil, fmt.Errorf("pagination size: %d, offset: %d: %w: %w", paginationSize, offset, err, QueryFail)
}

if len(result) == 0 { // no results, no need to try to paginate further
Expand Down Expand Up @@ -888,28 +888,28 @@ func (c *Client) DeleteAlertGraphBatch(ctx context.Context, alertItems []*ent.Al
Where(event.HasOwnerWith(alert.IDIn(idList...))).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
return 0, errors.Wrapf(DeleteFail, "alert graph delete batch events")
return 0, fmt.Errorf("alert graph delete batch events: %w", DeleteFail)
}

_, err = c.Ent.Meta.Delete().
Where(meta.HasOwnerWith(alert.IDIn(idList...))).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
return 0, errors.Wrapf(DeleteFail, "alert graph delete batch meta")
return 0, fmt.Errorf("alert graph delete batch meta: %w", DeleteFail)
}

_, err = c.Ent.Decision.Delete().
Where(decision.HasOwnerWith(alert.IDIn(idList...))).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
return 0, errors.Wrapf(DeleteFail, "alert graph delete batch decisions")
return 0, fmt.Errorf("alert graph delete batch decisions: %w", DeleteFail)
}

deleted, err := c.Ent.Alert.Delete().
Where(alert.IDIn(idList...)).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
return deleted, errors.Wrapf(DeleteFail, "alert graph delete batch")
return deleted, fmt.Errorf("alert graph delete batch: %w", DeleteFail)
}

c.Log.Debug("Done batch delete alerts")
Expand All @@ -923,30 +923,30 @@ func (c *Client) DeleteAlertGraph(ctx context.Context, alertItem *ent.Alert) err
Where(event.HasOwnerWith(alert.IDEQ(alertItem.ID))).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraph : %s", err)
return errors.Wrapf(DeleteFail, "event with alert ID '%d'", alertItem.ID)
return fmt.Errorf("event with alert ID '%d': %w", alertItem.ID, DeleteFail)
}

// delete the associated meta
_, err = c.Ent.Meta.Delete().
Where(meta.HasOwnerWith(alert.IDEQ(alertItem.ID))).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraph : %s", err)
return errors.Wrapf(DeleteFail, "meta with alert ID '%d'", alertItem.ID)
return fmt.Errorf("meta with alert ID '%d': %w", alertItem.ID, DeleteFail)
}

// delete the associated decisions
_, err = c.Ent.Decision.Delete().
Where(decision.HasOwnerWith(alert.IDEQ(alertItem.ID))).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraph : %s", err)
return errors.Wrapf(DeleteFail, "decision with alert ID '%d'", alertItem.ID)
return fmt.Errorf("decision with alert ID '%d': %w", alertItem.ID, DeleteFail)
}

// delete the alert
err = c.Ent.Alert.DeleteOne(alertItem).Exec(ctx)
if err != nil {
c.Log.Warningf("DeleteAlertGraph : %s", err)
return errors.Wrapf(DeleteFail, "alert with ID '%d'", alertItem.ID)
return fmt.Errorf("alert with ID '%d': %w", alertItem.ID, DeleteFail)
}

return nil
Expand Down
8 changes: 3 additions & 5 deletions pkg/database/bouncers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (
"strings"
"time"

"github.com/pkg/errors"

"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/bouncer"
"github.com/crowdsecurity/crowdsec/pkg/models"
Expand Down Expand Up @@ -43,8 +41,8 @@ func (c *Client) BouncerUpdateBaseMetrics(ctx context.Context, bouncerName strin
}

func (c *Client) SelectBouncers(ctx context.Context, apiKeyHash string, authType string) ([]*ent.Bouncer, error) {
//Order by ID so manually created bouncer will be first in the list to use as the base name
//when automatically creating a new entry if API keys are shared
// Order by ID so manually created bouncer will be first in the list to use as the base name
// when automatically creating a new entry if API keys are shared
result, err := c.Ent.Bouncer.Query().Where(bouncer.APIKeyEQ(apiKeyHash), bouncer.AuthTypeEQ(authType)).Order(ent.Asc(bouncer.FieldID)).All(ctx)
if err != nil {
return nil, err
Expand Down Expand Up @@ -74,7 +72,7 @@ func (c *Client) SelectBouncerByName(ctx context.Context, bouncerName string) (*
func (c *Client) ListBouncers(ctx context.Context) ([]*ent.Bouncer, error) {
result, err := c.Ent.Bouncer.Query().All(ctx)
if err != nil {
return nil, errors.Wrapf(QueryFail, "listing bouncers: %s", err)
return nil, fmt.Errorf("listing bouncers: %w: %w", err, QueryFail)
}

return result, nil
Expand Down
4 changes: 1 addition & 3 deletions pkg/database/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import (
"context"
"fmt"

"github.com/pkg/errors"

"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
)
Expand All @@ -17,7 +15,7 @@ func (c *Client) GetConfigItem(ctx context.Context, key string) (string, error)
case ent.IsNotFound(err):
return "", nil
case err != nil:
return "", errors.Wrapf(QueryFail, "select config item: %s", err)
return "", fmt.Errorf("select config item: %w: %w", err, QueryFail)
default:
return result.Value, nil
}
Expand Down
22 changes: 10 additions & 12 deletions pkg/database/decisionfilter.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"strconv"
"strings"

"github.com/pkg/errors"

"github.com/crowdsecurity/crowdsec/pkg/csnet"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
Expand Down Expand Up @@ -40,7 +38,7 @@ func applyDecisionFilter(query *ent.DecisionQuery, filter map[string][]string) (
case "contains":
contains, err = strconv.ParseBool(value[0])
if err != nil {
return nil, errors.Wrapf(InvalidFilter, "invalid contains value : %s", err)
return nil, fmt.Errorf("invalid contains value: %w: %w", err, InvalidFilter)
}
case "scopes", "scope": // Swagger mentions both of them, let's just support both to make sure we don't break anything
scopes := strings.Split(value[0], ",")
Expand Down Expand Up @@ -79,26 +77,26 @@ func applyDecisionFilter(query *ent.DecisionQuery, filter map[string][]string) (
case "ip", "range":
rng, err = csnet.NewRange(value[0])
if err != nil {
return nil, errors.Wrapf(InvalidIPOrRange, "unable to convert '%s' to int: %s", value[0], err)
return nil, fmt.Errorf("unable to convert '%s' to int: %w: %w", value[0], err, InvalidIPOrRange)
}
case "limit":
limit, err := strconv.Atoi(value[0])
if err != nil {
return nil, errors.Wrapf(InvalidFilter, "invalid limit value : %s", err)
return nil, fmt.Errorf("invalid limit value: %w: %w", err, InvalidFilter)
}

query = query.Limit(limit)
case "offset":
offset, err := strconv.Atoi(value[0])
if err != nil {
return nil, errors.Wrapf(InvalidFilter, "invalid offset value : %s", err)
return nil, fmt.Errorf("invalid offset value: %w: %w", err, InvalidFilter)
}

query = query.Offset(offset)
case "id_gt":
id, err := strconv.Atoi(value[0])
if err != nil {
return nil, errors.Wrapf(InvalidFilter, "invalid id_gt value : %s", err)
return nil, fmt.Errorf("invalid id_gt value: %w: %w", err, InvalidFilter)
}

query = query.Where(decision.IDGT(id))
Expand All @@ -115,22 +113,22 @@ func applyDecisionFilter(query *ent.DecisionQuery, filter map[string][]string) (

func decisionIPv4Filter(decisions *ent.DecisionQuery, contains bool, rng csnet.Range) (*ent.DecisionQuery, error) {
if contains {
/*Decision contains {start_ip,end_ip}*/
// Decision contains {start_ip,end_ip}
return decisions.Where(decision.And(
decision.StartIPLTE(rng.Start.Addr),
decision.EndIPGTE(rng.End.Addr),
decision.IPSizeEQ(int64(rng.Size())))), nil
}

/*Decision is contained within {start_ip,end_ip}*/
// Decision is contained within {start_ip,end_ip}
return decisions.Where(decision.And(
decision.StartIPGTE(rng.Start.Addr),
decision.EndIPLTE(rng.End.Addr),
decision.IPSizeEQ(int64(rng.Size())))), nil
}

func decisionIPv6Filter(decisions *ent.DecisionQuery, contains bool, rng csnet.Range) (*ent.DecisionQuery, error) {
/*decision contains {start_ip,end_ip}*/
// decision contains {start_ip,end_ip}
if contains {
return decisions.Where(decision.And(
// matching addr size
Expand All @@ -157,7 +155,7 @@ func decisionIPv6Filter(decisions *ent.DecisionQuery, contains bool, rng csnet.R
)), nil
}

/*decision is contained within {start_ip,end_ip}*/
// decision is contained within {start_ip,end_ip}
return decisions.Where(decision.And(
// matching addr size
decision.IPSizeEQ(int64(rng.Size())),
Expand Down Expand Up @@ -192,7 +190,7 @@ func decisionIPFilter(decisions *ent.DecisionQuery, contains bool, rng csnet.Ran
case 0:
return decisions, nil
default:
return nil, errors.Wrapf(InvalidFilter, "unknown ip size %d", rng.Size())
return nil, fmt.Errorf("unknown ip size %d: %w", rng.Size(), InvalidFilter)
}
}

Expand Down
Loading