Skip to content

Commit 097c242

Browse files
authored
refact pkg/apiserver: happy path; nil guard (#4180)
* recoverFromPanic(): drop else * isBrokenConnection: dry * shouldAutoRegister(): nil guard * Authenticator(): replace loop with strings.Join() * prometheus middleware: happy path * promehteus middleware: happy path, redundant c.Next()
1 parent 222a061 commit 097c242

File tree

4 files changed

+49
-60
lines changed

4 files changed

+49
-60
lines changed

pkg/apiserver/apiserver.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ func isBrokenConnection(maybeError any) bool {
5454
if errors.As(err, &netOpError) {
5555
var syscallError *os.SyscallError
5656
if errors.As(netOpError.Err, &syscallError) {
57-
if strings.Contains(strings.ToLower(syscallError.Error()), "broken pipe") || strings.Contains(strings.ToLower(syscallError.Error()), "connection reset by peer") {
57+
s := strings.ToLower(syscallError.Error())
58+
if strings.Contains(s, "broken pipe") || strings.Contains(s, "connection reset by peer") {
5859
return true
5960
}
6061
}
@@ -92,17 +93,18 @@ func recoverFromPanic(c *gin.Context) {
9293
if isBrokenConnection(err) {
9394
log.Warningf("client %s disconnected: %s", c.ClientIP(), err)
9495
c.Abort()
95-
} else {
96-
log.Warningf("client %s error: %s", c.ClientIP(), err)
96+
return
97+
}
9798

98-
filename, err := trace.WriteStackTrace(err)
99-
if err != nil {
100-
log.Errorf("also while writing stacktrace: %s", err)
101-
}
99+
log.Warningf("client %s error: %s", c.ClientIP(), err)
102100

103-
log.Warningf("stacktrace written to %s, please join to your issue", filename)
104-
c.AbortWithStatus(http.StatusInternalServerError)
101+
filename, err := trace.WriteStackTrace(err)
102+
if err != nil {
103+
log.Errorf("also while writing stacktrace: %s", err)
105104
}
105+
106+
log.Warningf("stacktrace written to %s, please join to your issue", filename)
107+
c.AbortWithStatus(http.StatusInternalServerError)
106108
}
107109

108110
// CustomRecoveryWithWriter returns a middleware for a writer that recovers from any panics and writes a 500 if there was one.

pkg/apiserver/controllers/v1/machines.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import (
1414
)
1515

1616
func (c *Controller) shouldAutoRegister(token string, gctx *gin.Context) (bool, error) {
17-
if !*c.AutoRegisterCfg.Enable {
17+
if c.AutoRegisterCfg == nil || c.AutoRegisterCfg.Enable == nil || !*c.AutoRegisterCfg.Enable {
1818
return false, nil
1919
}
2020

@@ -26,7 +26,7 @@ func (c *Controller) shouldAutoRegister(token string, gctx *gin.Context) (bool,
2626
return false, nil
2727
}
2828

29-
if token == "" || c.AutoRegisterCfg == nil {
29+
if token == "" {
3030
return false, nil
3131
}
3232

Lines changed: 33 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package v1
22

33
import (
4+
"cmp"
45
"time"
56

67
"github.com/crowdsecurity/crowdsec/pkg/metrics"
@@ -10,76 +11,71 @@ import (
1011

1112
func PrometheusBouncersHasEmptyDecision(c *gin.Context) {
1213
bouncer, _ := getBouncerFromContext(c)
13-
if bouncer != nil {
14-
metrics.LapiNilDecisions.With(prometheus.Labels{
15-
"bouncer": bouncer.Name,
16-
}).Inc()
14+
if bouncer == nil {
15+
return
1716
}
17+
18+
metrics.LapiNilDecisions.With(prometheus.Labels{
19+
"bouncer": bouncer.Name,
20+
}).Inc()
1821
}
1922

2023
func PrometheusBouncersHasNonEmptyDecision(c *gin.Context) {
2124
bouncer, _ := getBouncerFromContext(c)
22-
if bouncer != nil {
23-
metrics.LapiNonNilDecisions.With(prometheus.Labels{
24-
"bouncer": bouncer.Name,
25-
}).Inc()
25+
if bouncer == nil {
26+
return
2627
}
28+
29+
metrics.LapiNonNilDecisions.With(prometheus.Labels{
30+
"bouncer": bouncer.Name,
31+
}).Inc()
2732
}
2833

2934
func PrometheusMachinesMiddleware() gin.HandlerFunc {
3035
return func(c *gin.Context) {
3136
machineID, _ := getMachineIDFromContext(c)
32-
if machineID != "" {
33-
fullPath := c.FullPath()
34-
if fullPath == "" {
35-
fullPath = "invalid-endpoint"
36-
}
37-
metrics.LapiMachineHits.With(prometheus.Labels{
38-
"machine": machineID,
39-
"route": fullPath,
40-
"method": c.Request.Method,
41-
}).Inc()
37+
if machineID == "" {
38+
return
4239
}
4340

44-
c.Next()
41+
metrics.LapiMachineHits.With(prometheus.Labels{
42+
"machine": machineID,
43+
"route": cmp.Or(c.FullPath(), "invalid-endpoint"),
44+
"method": c.Request.Method,
45+
}).Inc()
4546
}
4647
}
4748

4849
func PrometheusBouncersMiddleware() gin.HandlerFunc {
4950
return func(c *gin.Context) {
5051
bouncer, _ := getBouncerFromContext(c)
51-
if bouncer != nil {
52-
fullPath := c.FullPath()
53-
if fullPath == "" {
54-
fullPath = "invalid-endpoint"
55-
}
56-
metrics.LapiBouncerHits.With(prometheus.Labels{
57-
"bouncer": bouncer.Name,
58-
"route": fullPath,
59-
"method": c.Request.Method,
60-
}).Inc()
52+
if bouncer == nil {
53+
return
6154
}
6255

63-
c.Next()
56+
metrics.LapiBouncerHits.With(prometheus.Labels{
57+
"bouncer": bouncer.Name,
58+
"route": cmp.Or(c.FullPath(), "invalid-endpoint"),
59+
"method": c.Request.Method,
60+
}).Inc()
6461
}
6562
}
6663

6764
func PrometheusMiddleware() gin.HandlerFunc {
6865
return func(c *gin.Context) {
6966
startTime := time.Now()
7067

71-
fullPath := c.FullPath()
72-
if fullPath == "" {
73-
fullPath = "invalid-endpoint"
74-
}
75-
7668
metrics.LapiRouteHits.With(prometheus.Labels{
77-
"route": fullPath,
69+
"route": cmp.Or(c.FullPath(), "invalid-endpoint"),
7870
"method": c.Request.Method,
7971
}).Inc()
8072
c.Next()
8173

8274
elapsed := time.Since(startTime)
83-
metrics.LapiResponseTime.With(prometheus.Labels{"method": c.Request.Method, "endpoint": c.FullPath()}).Observe(elapsed.Seconds())
75+
metrics.LapiResponseTime.With(
76+
prometheus.Labels{
77+
"method": c.Request.Method,
78+
"endpoint": c.FullPath(),
79+
}).Observe(elapsed.Seconds())
8480
}
8581
}

pkg/apiserver/middlewares/v1/jwt.go

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -192,19 +192,10 @@ func (j *JWT) Authenticator(c *gin.Context) (any, error) {
192192
}
193193
}
194194

195-
var scenarios string
196-
197-
if len(auth.scenariosInput) > 0 {
198-
for _, scenario := range auth.scenariosInput {
199-
if scenarios == "" {
200-
scenarios = scenario
201-
} else {
202-
scenarios += "," + scenario
203-
}
204-
}
195+
if len(auth.scenariosInput) != 0 {
196+
scenarios := strings.Join(auth.scenariosInput, ",")
205197

206-
err = j.DbClient.UpdateMachineScenarios(ctx, scenarios, auth.clientMachine.ID)
207-
if err != nil {
198+
if err = j.DbClient.UpdateMachineScenarios(ctx, scenarios, auth.clientMachine.ID); err != nil {
208199
log.Errorf("Failed to update scenarios list for '%s': %s\n", auth.machineID, err)
209200
return nil, jwt.ErrFailedAuthentication
210201
}

0 commit comments

Comments
 (0)