Skip to content

Commit 31b9145

Browse files
authored
refact pkg/database: unnecessary pointers (#3611)
* refact pkg/database: unnecessary pointers * lint
1 parent 73a4230 commit 31b9145

File tree

7 files changed

+45
-40
lines changed

7 files changed

+45
-40
lines changed

cmd/crowdsec-cli/clipapi/papi.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@ import (
1111
"github.com/spf13/cobra"
1212
"gopkg.in/tomb.v2"
1313

14-
"github.com/crowdsecurity/go-cs-lib/ptr"
15-
1614
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/args"
1715
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
1816
"github.com/crowdsecurity/crowdsec/pkg/apiserver"
@@ -76,17 +74,17 @@ func (cli *cliPapi) Status(ctx context.Context, out io.Writer, db *database.Clie
7674

7775
lastTimestampStr, err := db.GetConfigItem(ctx, apiserver.PapiPullKey)
7876
if err != nil {
79-
lastTimestampStr = ptr.Of("never")
77+
lastTimestampStr = "never"
8078
}
8179

8280
// both can and did happen
83-
if lastTimestampStr == nil || *lastTimestampStr == "0001-01-01T00:00:00Z" {
84-
lastTimestampStr = ptr.Of("never")
81+
if lastTimestampStr == "" || lastTimestampStr == "0001-01-01T00:00:00Z" {
82+
lastTimestampStr = "never"
8583
}
8684

8785
fmt.Fprint(out, "You can successfully interact with Polling API (PAPI)\n")
8886
fmt.Fprintf(out, "Console plan: %s\n", perms.Plan)
89-
fmt.Fprintf(out, "Last order received: %s\n", *lastTimestampStr)
87+
fmt.Fprintf(out, "Last order received: %s\n", lastTimestampStr)
9088
fmt.Fprint(out, "PAPI subscriptions:\n")
9189

9290
for _, sub := range perms.Categories {

pkg/apiclient/decisions_service.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ func (s *DecisionsService) FetchV3Decisions(ctx context.Context, url string) (*m
174174
return &v2Decisions, resp, nil
175175
}
176176

177-
func (s *DecisionsService) GetDecisionsFromBlocklist(ctx context.Context, blocklist *modelscapi.BlocklistLink, lastPullTimestamp *string) ([]*models.Decision, bool, error) {
177+
func (s *DecisionsService) GetDecisionsFromBlocklist(ctx context.Context, blocklist *modelscapi.BlocklistLink, lastPullTimestamp string) ([]*models.Decision, bool, error) {
178178
if blocklist.URL == nil {
179179
return nil, false, errors.New("blocklist URL is nil")
180180
}
@@ -188,8 +188,8 @@ func (s *DecisionsService) GetDecisionsFromBlocklist(ctx context.Context, blockl
188188
return nil, false, err
189189
}
190190

191-
if lastPullTimestamp != nil {
192-
req.Header.Set("If-Modified-Since", *lastPullTimestamp)
191+
if lastPullTimestamp != "" {
192+
req.Header.Set("If-Modified-Since", lastPullTimestamp)
193193
}
194194

195195
log.Debugf("[URL] %s %s", req.Method, req.URL)
@@ -217,8 +217,8 @@ func (s *DecisionsService) GetDecisionsFromBlocklist(ctx context.Context, blockl
217217
}
218218

219219
if resp.StatusCode == http.StatusNotModified {
220-
if lastPullTimestamp != nil {
221-
log.Debugf("Blocklist %s has not been modified since %s", *blocklist.URL, *lastPullTimestamp)
220+
if lastPullTimestamp != "" {
221+
log.Debugf("Blocklist %s has not been modified since %s", *blocklist.URL, lastPullTimestamp)
222222
} else {
223223
log.Debugf("Blocklist %s has not been modified (decisions about to expire)", *blocklist.URL)
224224
}

pkg/apiclient/decisions_service_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ func TestDecisionsFromBlocklist(t *testing.T) {
362362
Remediation: &tremediationBlocklist,
363363
Name: &tnameBlocklist,
364364
Duration: &tdurationBlocklist,
365-
}, nil)
365+
}, "")
366366
require.NoError(t, err)
367367
assert.True(t, isModified)
368368

@@ -381,7 +381,7 @@ func TestDecisionsFromBlocklist(t *testing.T) {
381381
Remediation: &tremediationBlocklist,
382382
Name: &tnameBlocklist,
383383
Duration: &tdurationBlocklist,
384-
}, ptr.Of("Sun, 01 Jan 2023 01:01:01 GMT"))
384+
}, "Sun, 01 Jan 2023 01:01:01 GMT")
385385

386386
require.NoError(t, err)
387387
assert.False(t, isModified)
@@ -392,7 +392,7 @@ func TestDecisionsFromBlocklist(t *testing.T) {
392392
Remediation: &tremediationBlocklist,
393393
Name: &tnameBlocklist,
394394
Duration: &tdurationBlocklist,
395-
}, ptr.Of("Mon, 02 Jan 2023 01:01:01 GMT"))
395+
}, "Mon, 02 Jan 2023 01:01:01 GMT")
396396

397397
require.NoError(t, err)
398398
assert.True(t, isModified)

pkg/apiserver/apic.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ func NewAPIC(ctx context.Context, config *csconfig.OnlineApiClientCfg, dbClient
243243
}
244244

245245
err = ret.Authenticate(ctx, config)
246+
246247
return ret, err
247248
}
248249

@@ -260,13 +261,14 @@ func loadAPICToken(ctx context.Context, db *database.Client) (string, time.Time,
260261
return "", time.Time{}, false
261262
}
262263

263-
if token == nil {
264+
if token == "" {
264265
log.Debug("no token found in DB")
265266
return "", time.Time{}, false
266267
}
267268

268269
parser := new(jwt.Parser)
269-
tok, _, err := parser.ParseUnverified(*token, jwt.MapClaims{})
270+
271+
tok, _, err := parser.ParseUnverified(token, jwt.MapClaims{})
270272
if err != nil {
271273
log.Debugf("error parsing token: %s", err)
272274
return "", time.Time{}, false
@@ -285,12 +287,12 @@ func loadAPICToken(ctx context.Context, db *database.Client) (string, time.Time,
285287
}
286288

287289
exp := time.Unix(int64(expFloat), 0)
288-
if time.Now().UTC().After(exp.Add(-1*time.Minute)) {
290+
if time.Now().UTC().After(exp.Add(-1 * time.Minute)) {
289291
log.Debug("auth token expired")
290292
return "", time.Time{}, false
291293
}
292294

293-
return *token, exp, true
295+
return token, exp, true
294296
}
295297

296298
// saveAPICToken stores the given JWT token in the local database under the "apic_token" config item.
@@ -310,6 +312,7 @@ func saveAPICToken(ctx context.Context, db *database.Client, token string) error
310312
func (a *apic) Authenticate(ctx context.Context, config *csconfig.OnlineApiClientCfg) error {
311313
if token, exp, valid := loadAPICToken(ctx, a.dbClient); valid {
312314
log.Debug("using valid token from DB")
315+
313316
a.apiClient.GetClient().Transport.(*apiclient.JWTTransport).Token = token
314317
a.apiClient.GetClient().Transport.(*apiclient.JWTTransport).Expiration = exp
315318
}
@@ -1043,7 +1046,7 @@ func (a *apic) updateBlocklist(ctx context.Context, client *apiclient.ApiClient,
10431046
blocklistConfigItemName := fmt.Sprintf("blocklist:%s:last_pull", *blocklist.Name)
10441047

10451048
var (
1046-
lastPullTimestamp *string
1049+
lastPullTimestamp string
10471050
err error
10481051
)
10491052

@@ -1060,10 +1063,10 @@ func (a *apic) updateBlocklist(ctx context.Context, client *apiclient.ApiClient,
10601063
}
10611064

10621065
if !hasChanged {
1063-
if lastPullTimestamp == nil {
1066+
if lastPullTimestamp == "" {
10641067
log.Infof("blocklist %s hasn't been modified or there was an error reading it, skipping", *blocklist.Name)
10651068
} else {
1066-
log.Infof("blocklist %s hasn't been modified since %s, skipping", *blocklist.Name, *lastPullTimestamp)
1069+
log.Infof("blocklist %s hasn't been modified since %s, skipping", *blocklist.Name, lastPullTimestamp)
10671070
}
10681071

10691072
return nil

pkg/apiserver/apic_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ func assertTotalValidDecisionCount(t *testing.T, dbClient *database.Client, coun
9999
assert.Len(t, d, count)
100100
}
101101

102-
func jsonMarshalX(v interface{}) []byte {
102+
func jsonMarshalX(v any) []byte {
103103
data, err := json.Marshal(v)
104104
if err != nil {
105105
panic(err)
@@ -932,7 +932,7 @@ func TestAPICPullTopBLCacheFirstCall(t *testing.T) {
932932
blocklistConfigItemName := "blocklist:blocklist1:last_pull"
933933
lastPullTimestamp, err := api.dbClient.GetConfigItem(ctx, blocklistConfigItemName)
934934
require.NoError(t, err)
935-
assert.NotEmpty(t, *lastPullTimestamp)
935+
assert.NotEmpty(t, lastPullTimestamp)
936936

937937
// new call should return 304 and should not change lastPullTimestamp
938938
httpmock.RegisterResponder("GET", "http://api.crowdsec.net/blocklist1", func(req *http.Request) (*http.Response, error) {
@@ -944,7 +944,7 @@ func TestAPICPullTopBLCacheFirstCall(t *testing.T) {
944944
require.NoError(t, err)
945945
secondLastPullTimestamp, err := api.dbClient.GetConfigItem(ctx, blocklistConfigItemName)
946946
require.NoError(t, err)
947-
assert.Equal(t, *lastPullTimestamp, *secondLastPullTimestamp)
947+
assert.Equal(t, lastPullTimestamp, secondLastPullTimestamp)
948948
}
949949

950950
func TestAPICPullTopBLCacheForceCall(t *testing.T) {

pkg/apiserver/papi.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@ import (
2222
"github.com/crowdsecurity/crowdsec/pkg/types"
2323
)
2424

25-
const SyncInterval = time.Second * 10
26-
27-
const PapiPullKey = "papi:last_pull"
25+
const (
26+
SyncInterval = time.Second * 10
27+
PapiPullKey = "papi:last_pull"
28+
)
2829

2930
var operationMap = map[string]func(*Message, *Papi, bool) error{
3031
"decision": DecisionCmd,
@@ -48,7 +49,7 @@ type Source struct {
4849

4950
type Message struct {
5051
Header *Header
51-
Data interface{} `json:"data"`
52+
Data any `json:"data"`
5253
}
5354

5455
type OperationChannels struct {
@@ -240,7 +241,7 @@ func (p *Papi) Pull(ctx context.Context) error {
240241
}
241242

242243
// value doesn't exist, it's first time we're pulling
243-
if lastTimestampStr == nil {
244+
if lastTimestampStr == "" {
244245
binTime, err := lastTimestamp.MarshalText()
245246
if err != nil {
246247
return fmt.Errorf("failed to serialize last timestamp: %w", err)
@@ -252,7 +253,7 @@ func (p *Papi) Pull(ctx context.Context) error {
252253
p.Logger.Debugf("config item '%s' set in database with value '%s'", PapiPullKey, string(binTime))
253254
}
254255
} else {
255-
if err := lastTimestamp.UnmarshalText([]byte(*lastTimestampStr)); err != nil {
256+
if err := lastTimestamp.UnmarshalText([]byte(lastTimestampStr)); err != nil {
256257
return fmt.Errorf("failed to parse last timestamp: %w", err)
257258
}
258259
}

pkg/database/config.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,27 +9,30 @@ import (
99
"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
1010
)
1111

12-
func (c *Client) GetConfigItem(ctx context.Context, key string) (*string, error) {
12+
func (c *Client) GetConfigItem(ctx context.Context, key string) (string, error) {
1313
result, err := c.Ent.ConfigItem.Query().Where(configitem.NameEQ(key)).First(ctx)
14-
if err != nil && ent.IsNotFound(err) {
15-
return nil, nil
16-
}
1714

18-
if err != nil {
19-
return nil, errors.Wrapf(QueryFail, "select config item: %s", err)
15+
switch {
16+
case ent.IsNotFound(err):
17+
return "", nil
18+
case err != nil:
19+
return "", errors.Wrapf(QueryFail, "select config item: %s", err)
20+
default:
21+
return result.Value, nil
2022
}
21-
22-
return &result.Value, nil
2323
}
2424

2525
func (c *Client) SetConfigItem(ctx context.Context, key string, value string) error {
2626
nbUpdated, err := c.Ent.ConfigItem.Update().SetValue(value).Where(configitem.NameEQ(key)).Save(ctx)
27-
if (err != nil && ent.IsNotFound(err)) || nbUpdated == 0 { // not found, create
27+
28+
switch {
29+
case ent.IsNotFound(err) || nbUpdated == 0:
30+
// not found, create
2831
err := c.Ent.ConfigItem.Create().SetName(key).SetValue(value).Exec(ctx)
2932
if err != nil {
3033
return errors.Wrapf(QueryFail, "insert config item: %s", err)
3134
}
32-
} else if err != nil {
35+
case err != nil:
3336
return errors.Wrapf(QueryFail, "update config item: %s", err)
3437
}
3538

0 commit comments

Comments
 (0)