feat(api tokens): move token validation middleware to new function

This commit is contained in:
kolaente 2023-09-01 10:19:55 +02:00
parent d9bfcdab8e
commit e295d75e6e
Signed by untrusted user: konrad
GPG Key ID: F40E70337AB24C9B
2 changed files with 78 additions and 46 deletions

77
pkg/routes/api_tokens.go Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
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
}

View File

@ -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())