mirror of
https://github.com/kubeshark/kubeshark.git
synced 2025-09-12 21:01:36 +00:00
TRA-4157 fix ws auth (#669)
* Update socket_routes.go, user_controller.go, and 2 more files... * Update user_controller.go * Switch to http-only cookies for more security
This commit is contained in:
@@ -1,49 +1,51 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"mizuserver/pkg/config"
|
||||
"mizuserver/pkg/providers"
|
||||
"time"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/patrickmn/go-cache"
|
||||
"github.com/up9inc/mizu/shared/logger"
|
||||
)
|
||||
|
||||
const cachedValidTokensRetainmentTime = time.Minute * 1
|
||||
|
||||
var cachedValidTokens = cache.New(cachedValidTokensRetainmentTime, cachedValidTokensRetainmentTime)
|
||||
const errorMessage = "unknown authentication error occured"
|
||||
|
||||
func RequiresAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// auth is irrelevant for ephermeral mizu
|
||||
// authentication is irrelevant for ephermeral mizu
|
||||
if !config.Config.StandaloneMode {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
token := c.GetHeader("x-session-token")
|
||||
if token == "" {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "token header is empty"})
|
||||
token, err := c.Cookie("x-session-token")
|
||||
if err != nil {
|
||||
if errors.Is(err, http.ErrNoCookie) {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "could not find session cookie"})
|
||||
} else {
|
||||
logger.Log.Errorf("error reading cookie %s", err)
|
||||
c.AbortWithStatusJSON(500, gin.H{"error": errorMessage})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if _, isTokenCached := cachedValidTokens.Get(token); isTokenCached {
|
||||
c.Next()
|
||||
if token == "" {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "token cookie is empty"})
|
||||
return
|
||||
}
|
||||
|
||||
if isTokenValid, err := providers.VerifyToken(token, c.Request.Context()); err != nil {
|
||||
logger.Log.Errorf("error verifying token %s", err)
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "unknown auth error occured"})
|
||||
c.AbortWithStatusJSON(500, gin.H{"error": errorMessage})
|
||||
return
|
||||
} else if !isTokenValid {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "invalid token"})
|
||||
return
|
||||
}
|
||||
|
||||
cachedValidTokens.Set(token, true, cachedValidTokensRetainmentTime)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user