From 7b2e2d088c77d573320a41d70a8e6d99af28bd28 Mon Sep 17 00:00:00 2001 From: guipguia Date: Sun, 28 Jul 2024 23:15:56 +0100 Subject: [PATCH] backend: istokenAboutToExpire: Refactor for clarify and maintainability Signed-off-by: guipguia --- backend/cmd/headlamp.go | 53 +++++++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/backend/cmd/headlamp.go b/backend/cmd/headlamp.go index c7927a08b48..d0ef999fc35 100644 --- a/backend/cmd/headlamp.go +++ b/backend/cmd/headlamp.go @@ -69,6 +69,8 @@ const ContextCacheTTL = 5 * time.Minute // minutes const ContextUpdateChacheTTL = 20 * time.Second // seconds +const JWTExpirationTTL = 10 * time.Second // seconds + type clientConfig struct { Clusters []Cluster `json:"clusters"` IsDyanmicClusterEnabled bool `json:"isDynamicClusterEnabled"` @@ -685,41 +687,50 @@ func parseClusterAndToken(r *http.Request) (string, string) { return cluster, token } -func isTokenAboutToExpire(token string) bool { - const TokenParts = 3 - - // parse expiry time from token - parts := strings.Split(token, ".") - if len(parts) != TokenParts { - return false +func decodePayload(payload string) (map[string]interface{}, error) { + payloadBytes, err := base64.RawStdEncoding.DecodeString(payload) + if err != nil { + return nil, err } - payloadPart := parts[1] + var payloadMap map[string]interface{} + if err := json.Unmarshal(payloadBytes, &payloadMap); err != nil { + return nil, err + } - payloadBytes, err := base64.RawStdEncoding.DecodeString(payloadPart) - if err != nil { - logger.Log(logger.LevelError, nil, err, "failed to decode payload") + return payloadMap, nil +} - return false +func getExpiryTime(payload map[string]interface{}) (time.Time, error) { + exp, ok := payload["exp"].(float64) + if !ok { + return time.Time{}, errors.New("expiry time not found or invalid") } - var payload map[string]interface{} - if err := json.Unmarshal(payloadBytes, &payload); err != nil { - logger.Log(logger.LevelError, nil, err, "failed to unmarshal payload") + return time.Unix(int64(exp), 0), nil +} +func isTokenAboutToExpire(token string) bool { + const tokenParts = 3 + + parts := strings.Split(token, ".") + if len(parts) != tokenParts { return false } - // check if token is expired - exp, ok := payload["exp"].(float64) - if !ok { + payload, err := decodePayload(parts[1]) + if err != nil { + logger.Log(logger.LevelError, nil, err, "failed to decode payload") return false } - // if token is not about to expire, then skip - expTime := time.Unix(int64(exp), 0) + expiryTime, err := getExpiryTime(payload) + if err != nil { + logger.Log(logger.LevelError, nil, err, "failed to get expiry time") + return false + } - return time.Until(expTime) <= time.Second*10 + return time.Until(expiryTime) <= JWTExpirationTTL } //nolint:funlen