From e295d75e6e4f0d2ea1d34dd82bf28cce0d70f000 Mon Sep 17 00:00:00 2001 From: kolaente Date: Fri, 1 Sep 2023 10:19:55 +0200 Subject: [PATCH] feat(api tokens): move token validation middleware to new function --- pkg/routes/api_tokens.go | 77 ++++++++++++++++++++++++++++++++++++++++ pkg/routes/routes.go | 47 +----------------------- 2 files changed, 78 insertions(+), 46 deletions(-) create mode 100644 pkg/routes/api_tokens.go diff --git a/pkg/routes/api_tokens.go b/pkg/routes/api_tokens.go new file mode 100644 index 000000000..d272ea40a --- /dev/null +++ b/pkg/routes/api_tokens.go @@ -0,0 +1,77 @@ +// Vikunja is a to-do list application to facilitate your life. +// Copyright 2018-present Vikunja and contributors. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public Licensee as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public Licensee for more details. +// +// You should have received a copy of the GNU Affero General Public Licensee +// along with this program. If not, see . + +package routes + +import ( + "net/http" + "strings" + "time" + + "code.vikunja.io/api/pkg/config" + "code.vikunja.io/api/pkg/db" + "code.vikunja.io/api/pkg/log" + "code.vikunja.io/api/pkg/models" + + echojwt "github.com/labstack/echo-jwt/v4" + "github.com/labstack/echo/v4" +) + +func SetupTokenMiddleware() echo.MiddlewareFunc { + return echojwt.WithConfig(echojwt.Config{ + SigningKey: []byte(config.ServiceJWTSecret.GetString()), + Skipper: func(c echo.Context) bool { + authHeader := c.Request().Header.Values("Authorization") + if len(authHeader) == 0 { + return false // let the jwt middleware handle invalid headers + } + + for _, s := range authHeader { + if strings.HasPrefix(s, "Bearer "+models.APITokenPrefix) { + err := checkAPITokenAndPutItInContext(s, c) + if err != nil { + log.Errorf("Could not check api token: %v", err) + return false + } + return true + } + } + + return false + }, + }) +} + +func checkAPITokenAndPutItInContext(tokenHeaderValue string, c echo.Context) error { + s := db.NewSession() + defer s.Close() + token, err := models.GetTokenFromTokenString(s, strings.TrimPrefix(tokenHeaderValue, "Bearer ")) + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err) + } + + if time.Now().After(token.ExpiresAt) { + return echo.NewHTTPError(http.StatusUnauthorized) + } + + if !models.CanDoAPIRoute(c, token) { + return echo.NewHTTPError(http.StatusUnauthorized) + } + + c.Set("api_token", token) + + return nil +} diff --git a/pkg/routes/routes.go b/pkg/routes/routes.go index 04ad65822..544096c13 100644 --- a/pkg/routes/routes.go +++ b/pkg/routes/routes.go @@ -51,7 +51,6 @@ package routes import ( "errors" - "net/http" "net/url" "strings" "time" @@ -81,7 +80,6 @@ import ( "github.com/getsentry/sentry-go" sentryecho "github.com/getsentry/sentry-go/echo" - echojwt "github.com/labstack/echo-jwt/v4" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" elog "github.com/labstack/gommon/log" @@ -281,50 +279,7 @@ func registerAPIRoutes(a *echo.Group) { } // ===== Routes with Authentication ===== - a.Use(echojwt.WithConfig(echojwt.Config{ - SigningKey: []byte(config.ServiceJWTSecret.GetString()), - Skipper: func(c echo.Context) bool { - authHeader := c.Request().Header.Values("Authorization") - if len(authHeader) == 0 { - return false // let the jwt middleware handle invalid headers - } - - for _, s := range authHeader { - if strings.HasPrefix(s, "Bearer "+models.APITokenPrefix) { - c.Set("api_token", s) - return true - } - } - - return false - }, - })) - - a.Use(func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - // If this is empty we assume we're dealing with a "real" user who has provided a jwt - tokenString, is := c.Get("api_token").(string) - if !is || tokenString == "" { - return next(c) - } - token, err := models.GetTokenFromTokenString(db.NewSession(), strings.TrimPrefix(tokenString, "Bearer ")) - if err != nil { - return echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err) - } - - if time.Now().After(token.ExpiresAt) { - return echo.NewHTTPError(http.StatusUnauthorized) - } - - if !models.CanDoAPIRoute(c, token) { - return echo.NewHTTPError(http.StatusUnauthorized) - } - - c.Set("api_token", token) - - return next(c) - } - }) + a.Use(SetupTokenMiddleware()) // Rate limit setupRateLimit(a, config.RateLimitKind.GetString())