Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refact pkg/apiserver (auth helpers) #2856

Merged
merged 1 commit into from
Feb 23, 2024
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
5 changes: 1 addition & 4 deletions pkg/apiserver/controllers/v1/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"strings"
"time"

jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"github.com/go-openapi/strfmt"
"github.com/google/uuid"
Expand Down Expand Up @@ -143,9 +142,7 @@ func normalizeScope(scope string) string {
func (c *Controller) CreateAlert(gctx *gin.Context) {
var input models.AddAlertsRequest

claims := jwt.ExtractClaims(gctx)
// TBD: use defined rather than hardcoded key to find back owner
machineID := claims["id"].(string)
machineID, _ := getMachineIDFromContext(gctx)

if err := gctx.ShouldBindJSON(&input); err != nil {
gctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
Expand Down
5 changes: 1 addition & 4 deletions pkg/apiserver/controllers/v1/heartbeat.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@ package v1
import (
"net/http"

jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
)

func (c *Controller) HeartBeat(gctx *gin.Context) {
claims := jwt.ExtractClaims(gctx)
// TBD: use defined rather than hardcoded key to find back owner
machineID := claims["id"].(string)
machineID, _ := getMachineIDFromContext(gctx)

if err := c.DBClient.UpdateMachineLastHeartBeat(machineID); err != nil {
c.HandleDBErrors(gctx, err)
Expand Down
34 changes: 15 additions & 19 deletions pkg/apiserver/controllers/v1/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package v1
import (
"time"

jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
)
Expand Down Expand Up @@ -66,32 +65,29 @@ var LapiResponseTime = prometheus.NewHistogramVec(
[]string{"endpoint", "method"})

func PrometheusBouncersHasEmptyDecision(c *gin.Context) {
name, ok := c.Get("BOUNCER_NAME")
if ok {
bouncer, _ := getBouncerFromContext(c)
if bouncer != nil {
LapiNilDecisions.With(prometheus.Labels{
"bouncer": name.(string)}).Inc()
"bouncer": bouncer.Name}).Inc()
}
}

func PrometheusBouncersHasNonEmptyDecision(c *gin.Context) {
name, ok := c.Get("BOUNCER_NAME")
if ok {
bouncer, _ := getBouncerFromContext(c)
if bouncer != nil {
LapiNonNilDecisions.With(prometheus.Labels{
"bouncer": name.(string)}).Inc()
"bouncer": bouncer.Name}).Inc()
}
}

func PrometheusMachinesMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
claims := jwt.ExtractClaims(c)
if claims != nil {
if rawID, ok := claims["id"]; ok {
machineID := rawID.(string)
LapiMachineHits.With(prometheus.Labels{
"machine": machineID,
"route": c.Request.URL.Path,
"method": c.Request.Method}).Inc()
}
machineID, _ := getMachineIDFromContext(c)
if machineID != "" {
LapiMachineHits.With(prometheus.Labels{
"machine": machineID,
"route": c.Request.URL.Path,
"method": c.Request.Method}).Inc()
}

c.Next()
Expand All @@ -100,10 +96,10 @@ func PrometheusMachinesMiddleware() gin.HandlerFunc {

func PrometheusBouncersMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
name, ok := c.Get("BOUNCER_NAME")
if ok {
bouncer, _ := getBouncerFromContext(c)
if bouncer != nil {
LapiBouncerHits.With(prometheus.Labels{
"bouncer": name.(string),
"bouncer": bouncer.Name,
"route": c.Request.URL.Path,
"method": c.Request.Method}).Inc()
}
Expand Down
32 changes: 26 additions & 6 deletions pkg/apiserver/controllers/v1/utils.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,50 @@
package v1

import (
"fmt"
"errors"
"net/http"

jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"

middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
)

const bouncerContextKey = "bouncer_info"

func getBouncerFromContext(ctx *gin.Context) (*ent.Bouncer, error) {
bouncerInterface, exist := ctx.Get(bouncerContextKey)
bouncerInterface, exist := ctx.Get(middlewares.BouncerContextKey)
if !exist {
return nil, fmt.Errorf("bouncer not found")
return nil, errors.New("bouncer not found")

Check warning on line 17 in pkg/apiserver/controllers/v1/utils.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiserver/controllers/v1/utils.go#L17

Added line #L17 was not covered by tests
}

bouncerInfo, ok := bouncerInterface.(*ent.Bouncer)
if !ok {
return nil, fmt.Errorf("bouncer not found")
return nil, errors.New("bouncer not found")

Check warning on line 22 in pkg/apiserver/controllers/v1/utils.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiserver/controllers/v1/utils.go#L22

Added line #L22 was not covered by tests
}

return bouncerInfo, nil
}

func getMachineIDFromContext(ctx *gin.Context) (string, error) {
claims := jwt.ExtractClaims(ctx)
if claims == nil {
return "", errors.New("failed to extract claims")
}

Check warning on line 32 in pkg/apiserver/controllers/v1/utils.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiserver/controllers/v1/utils.go#L31-L32

Added lines #L31 - L32 were not covered by tests

rawID, ok := claims[middlewares.MachineIDKey]
if !ok {
return "", errors.New("MachineID not found in claims")
}

Check warning on line 37 in pkg/apiserver/controllers/v1/utils.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiserver/controllers/v1/utils.go#L36-L37

Added lines #L36 - L37 were not covered by tests

id, ok := rawID.(string)
if !ok {
// should never happen
return "", errors.New("failed to cast machineID to string")
}

Check warning on line 43 in pkg/apiserver/controllers/v1/utils.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiserver/controllers/v1/utils.go#L41-L43

Added lines #L41 - L43 were not covered by tests

return id, nil
}

func (c *Controller) AbortRemoteIf(option bool) gin.HandlerFunc {
return func(gctx *gin.Context) {
incomingIP := gctx.ClientIP()
Expand Down
11 changes: 3 additions & 8 deletions pkg/apiserver/middlewares/v1/api_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import (

const (
APIKeyHeader = "X-Api-Key"
bouncerContextKey = "bouncer_info"
// max allowed by bcrypt 72 = 54 bytes in base64
BouncerContextKey = "bouncer_info"
dummyAPIKeySize = 54
// max allowed by bcrypt 72 = 54 bytes in base64
)

type APIKey struct {
Expand Down Expand Up @@ -159,11 +159,6 @@ func (a *APIKey) MiddlewareFunc() gin.HandlerFunc {
"name": bouncer.Name,
})

// maybe we want to store the whole bouncer object in the context instead, this would avoid another db query
// in StreamDecision
c.Set("BOUNCER_NAME", bouncer.Name)
c.Set("BOUNCER_HASHED_KEY", bouncer.APIKey)

if bouncer.IPAddress == "" {
if err := a.DbClient.UpdateBouncerIP(c.ClientIP(), bouncer.ID); err != nil {
logger.Errorf("Failed to update ip address for '%s': %s\n", bouncer.Name, err)
Expand Down Expand Up @@ -203,7 +198,7 @@ func (a *APIKey) MiddlewareFunc() gin.HandlerFunc {
}
}

c.Set(bouncerContextKey, bouncer)
c.Set(BouncerContextKey, bouncer)
c.Next()
}
}
8 changes: 4 additions & 4 deletions pkg/apiserver/middlewares/v1/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/types"
)

var identityKey = "id"
const MachineIDKey = "id"

type JWT struct {
Middleware *jwt.GinJWTMiddleware
Expand All @@ -33,7 +33,7 @@ type JWT struct {
func PayloadFunc(data interface{}) jwt.MapClaims {
if value, ok := data.(*models.WatcherAuthRequest); ok {
return jwt.MapClaims{
identityKey: &value.MachineID,
MachineIDKey: &value.MachineID,
}
}

Expand All @@ -42,7 +42,7 @@ func PayloadFunc(data interface{}) jwt.MapClaims {

func IdentityHandler(c *gin.Context) interface{} {
claims := jwt.ExtractClaims(c)
machineID := claims[identityKey].(string)
machineID := claims[MachineIDKey].(string)

return &models.WatcherAuthRequest{
MachineID: &machineID,
Expand Down Expand Up @@ -307,7 +307,7 @@ func NewJWT(dbClient *database.Client) (*JWT, error) {
Key: secret,
Timeout: time.Hour,
MaxRefresh: time.Hour,
IdentityKey: identityKey,
IdentityKey: MachineIDKey,
PayloadFunc: PayloadFunc,
IdentityHandler: IdentityHandler,
Authenticator: jwtMiddleware.Authenticator,
Expand Down
Loading